Gnijuohz
Gnijuohz

Reputation: 3364

define the length of an array with a variable in c++/c

I am reading a book saying that in C++ you can't do this:

int array_size = 3;
int array[array_size];

Then I tried it with gcc,but it didn't complain at all(exception warned about unused array).

Also I read about this question.The 4th answer says that you can use something like this:char someCondition[ condition ];To me the condition would only be known until runtime,so the whole thing seems really confounding to me.Can anyone help explain this?

Thanks,G

Upvotes: 1

Views: 502

Answers (1)

Alok Save
Alok Save

Reputation: 206518

If You are using a C++ compiler it works because most of the C++ compilers provide a compiler extension that supports Variable Length arguments(VLA).

If You are using a C compiler it works because the standard allows it.


In C++, VLA are not allowed by the C++ Standard, so any usage of it through compiler extensions will make your code non portable.
C++ provides std::vector or std::array(C++11) which satisfy all the requirements using variable length array or c-style arrays resp and you should use them.

Note that,since C99 standard, VLA's are allowed in C.

Upvotes: 7

Related Questions