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

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

    Is your code semantically different from myfunc() here:

    void myfunc(const int n) { 
        int x[n] = { 1,1,3,4,5 };
        printf("%d\n", x[n-1]);
        *( (int *) &n) = 17;    //  Somewhat less "constant" than hoped...
        return ;
    }
    
    int main(){
        myfunc(4);
        myfunc(5);
        myfunc(6);  //  Haven't actually tested this.  Boom?  Maybe just printf(noise)?
        return 0;
    }
    

    Is n really all that constant? How much space do you think the compiler should allocated for x[] (since it is the compiler's job to do so)?

    As others have pointed out, the cv-qualifier const does not mean "a value that is constant during compilation and for all times after". It means "a value that the local code is not supposed to change (although it can)".

提交回复
热议问题