Constant expressions in array declarations

C ++ Primer says that

Arrays must be known at compile time, which means that the dimension must be a constant expression

A separate point is made at which

unsigned count = 42; // not a constant expression constexpr unsigned size = 42; // a constant expression 

I would prefer the next ad to fail

 a[count]; // Is an error according to Primer 

And yet this is not so. Compiles and works fine.

It is also strange that ++count; after the declaration of the array also does not cause problems.

The program is compiled with the flag -std=c++11 on g++4.71

Why is this?

+4
source share
3 answers

Your code is actually not legal C ++. Some compilers allow variable-length arrays as an extension, but not standard C ++. To GCC complaint about this, go -pedantic . In general, you should always pass at least these warning flags to GCC:

 -W -Wall -Wextra -pedantic 
+8
source

According to this link: http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html , GCC supports variable-length arrays of C in C90 mode and C ++. Since this is not standard C ++, you should consider this as a compiler extension and, therefore, consider it not portable.

+3
source

Other answers already provide a solution, g ++ allows arrays of variable arrays (VLAs) as an extension in C ++ (technically, VLA is a C function from C90). To make sure you are using standard compatible C ++, go -pedantic to get the warning, and -pedantic -Werror to make the warning difficult.

I recommend the following when compiling in debug mode:

g ++ -std = C ++ 11 -O0 -g3 -pedantic -pedantic-errors -Wall -Wextra -Werror -Wconversion

O0 is the optimization flag and -g3 used for debugging . They need to be changed if you want to use optimization and do not need debugging. However, sometimes you may need to remove -Werror -Wconversion , since you will not be able to change the code for certain reasons, for example, when using third-party libraries. For a description of what each of them does, send here .

+1
source

All Articles