Search code examples
c++arraysconstantsconstant-expression

Why is it only sometimes allowed to use a const int as an array size?


  1. this can work:

    const int size = 2;
    int array[size] = {0}; 
    
  2. this has compile error:

    int a = 2;
    const int size = a;
    int array[size] = {0};
    

why?


Solution

  • Because the guys in the C++ committee decided so.

    The technical reason is that the first expression that is used to initialize size is a constant expression and it can be computed during compilation. This means that the compiler can also know how big the array is going to be and the allocation (in this case "reservation" may be a more appropriate term) can be done at compile time.

    In the second case instead the expression is not a constant expression (given the C++ definition) and this revervation is not possible.

    The fact that in the second case the value is indeed fixed by the time size is initialized is totally irrelevant. The rules are base on the "kind of expression" and the second expression uses mutable variables and thus the compiler considers it non-constant.

    Allowing the second form for compile-time initialization would require a flow analysis because the compiler would need to distinguish between

    int a = 2;
    const int size = a;
    

    and

    int a = foo();
    const int size = a;
    

    where the expression involving size is indeed identical.