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

后端 未结 5 1228
臣服心动
臣服心动 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:01

    Even though n is a const, you cannot use it to define the size of an array unless you wish to create a VLA. However, you cannot use an initializer list to initialize a VLA.

    Use a macro to create a fixed size array.

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

提交回复
热议问题