array size and const


In C++
const int a[]={1,2,3,4,5}; int b[a[2]]; 
int main()
{
    return 0;
} 
The code is giving error in line 2; However, if it is something like below it gives no error after compilation:
const int a=3; int b[a]; 
int main()
{
    return 0;
} 
Why is that?

Comments

  1. In first case declaring array a constant doesn't make its all element constant so it will showing variable type declaration outside the main error when we compile it........

    ReplyDelete
  2. when we declare an array a constant, why doesnt it make all elements constant??

    ReplyDelete
  3. @ B Ramesh Because in C++ array sizes must be constant expressions, not just constant data. Array data, even though const, is not a constant expression.

    Second version IS a constant expression.

    ReplyDelete

Post a Comment

Popular posts from this blog