Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 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.

like image 232
gyozo kudor Avatar asked Jul 24 '10 08:07

gyozo kudor


2 Answers

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.

like image 104
Drew Hall Avatar answered Sep 20 '22 06:09

Drew Hall


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

like image 35
fredoverflow Avatar answered Sep 21 '22 06:09

fredoverflow