Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How is it possible this array compiles?

29 views
Skip to first unread message

JiiPee

unread,
Dec 3, 2014, 6:11:20 AM12/3/14
to
How is it possible this array compiles? Last time I studied C++ the
array size must be a constant value (double checked: "NOTE: The
|elements| field within square brackets |[]|, representing the number of
elements in the array, must be a /constant expression/"). How is it
possible howMany can be a variable below? Obviously there is something I
do not see... But I do see a normal array int arr[howMany]; .... so...

#include <iostream>

using namespace std;

int main()
{
int howMany;
cout << "How big array?: ";
cin >> howMany;

int arr[howMany];
if(howMany > 5)
{
arr[howMany-2] = 67;
cout<<arr[howMany-2];
}

return 0;
}

Martijn Lievaart

unread,
Dec 3, 2014, 6:45:14 AM12/3/14
to
martijn@garfield:~/t$ g++ -std=c++11 -pedantic -c -o vararray.o
vararray.cpp
vararray.cpp: In function ‘int main()’:
vararray.cpp:11:21: warning: ISO C++ forbids variable length array
‘arr’ [-Wvla]
int arr[howMany];
^

It's an extension from C, known as Variable Length Array (VLA). It's not
legal C++. It's accepted by many compilers unless you tell them to be
pedantic.

HTH,
M4

JiiPee

unread,
Dec 3, 2014, 7:25:10 AM12/3/14
to
oh ok, thanks. So I guess its not totally portable neither as its not
legal.... so not good to use I would think.
0 new messages