Why is int x[n] wrong where n is a const value?

后端 未结 5 1234
臣服心动
臣服心动 2020-12-15 03:28

I cannot understand why doing this is wrong:

const int n = 5; 
int x[n] = { 1,1,3,4,5 };

even though n is already a const valu

5条回答
  •  青春惊慌失措
    2020-12-15 04:17

    Why int x[n] is wrong where n is a const value?

    n is not a constant. const only promise that n is a 'read-only' variable that shouldn't be modified during the program execution.
    Note that in c, unlike c++, const qualified variables are not constant. Therefore, the array declared is a variable length array.
    You can't use initializer list to initialize variable length arrays.

    C11-§6.7.9/3:

    The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

    You can use #define or enum to make n a constant

    #define n 5
    int x[n] = { 1,1,3,4,5 };   
    

提交回复
热议问题