开发者

C++ int a[n] working in g++ but not with vs2008

开发者 https://www.devze.com 2023-01-08 21:58 出处:网络
I have the following code: ... int n; cin >> n; int numbers[n]; ... It compiled with NetBeans on Mac using g++ (I think) and it didn\'t compile using VS2008 on Windows. Why is it so hard to m

I have the following code:

...
int n;
cin >> n;
int numbers[n];
...

It compiled with NetBeans on Mac using g++ (I think) and it didn't compile using VS2008 on Windows. Why is it so hard to make it work with every开发者_如何学JAVA compiler? The size of the array is known before allocating it.

EDIT: I know about std::vector. Actually this was part of a homework assignment and I started it at work on a mac, then got home and was surprised that it didn't work on VS2008. Thanks for all the answers. But I still find it logical that if the compiler can generate some code like alloc(123) where the value 123 is hardcoded, why can't it generate something like alloc(n) where you get n from a memory address that holds an int n or something. It just seems more logical to allow something like this by default.


Although the size of the array is known before it is allocated, it's still not known until runtime. This is known as variable length array (VLA) and is a C99ism, supported in g++ by an extension that is enabled by default. To be explicit, this is not conformant C++ 98/03, and thus Visual C++ is well within its right to reject it.

If you really want runtime dynamic sizing, allocate on the heap (via new[]). That will work everywhere, and as a bonus, protect you from stack overflows.


Because the size of an array must be a compile time constant in standard C++ (see 8.3.4 §1).


why not use some cpp real stuff like std::vector<int> for that


Something similar can ne done with

 int* numbers = (int*)alloca(n * sizeof(int));  // equivalent to int numbers[n]

this is not recommended function, but if used carefully, gives exactly the same result.


By book the array dimension should be a constant expression whose value is greater than or equal to one. Constant expression in the sense integral literal constants, enumerators or const objects of integral type that are themselves initialized from const expressions. A non const variable whose value is not known until runtime can not be used to specify the dimension of an array.

But the compiler version i use allows the allows the way you mentioned.


Support for VLAs is not present in Visual Studio 2008.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号