Why is new int[n] valid when int array[n] is not?

前端 未结 9 2027
暗喜
暗喜 2020-12-31 02:00

For the following code:

foo(int n){
    int array[n];
}

I understand that this is invalid syntax and that it is invalid because the c++ sta

9条回答
  •  伪装坚强ぢ
    2020-12-31 02:43

    Because it has different semantics:

    If n is a compile-time constant (unlike in your example):

    int array[n]; //valid iff n is compile-time constant, space known at compile-time
    

    But consider when n is a runtime value:

    int array[n]; //Cannot have a static array with a runtime value in C++
    int * array = new int[n]; //This works because it happens at run-time, 
                              // not at compile-time! Different semantics, similar syntax.
    

    In C99 you can have a runtime n for an array and space will be made in the stack at runtime. There are some proposals for similar extensions in C++, but none of them is into the standard yet.

提交回复
热议问题