4

C++ Primer says that

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

A separate point is made that

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

I would, then expect for the following declaration to fail

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

And yet, it does not. Compiles and runs fine.

What is also kind of strange is that ++count; subsequent to array declaration also causes no issues.

Program compiled with -std=c++11 flag on g++4.71

Why is that?

Stals
  • 1,543
  • 4
  • 27
  • 52
James Raitsev
  • 92,517
  • 154
  • 335
  • 470

3 Answers3

8

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

-W -Wall -Wextra -pedantic
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
3

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

bstamour
  • 7,746
  • 1
  • 26
  • 39
1

The other answers already provide the solution, g++ allows variables length arrays (VLAs) as an extension in C++ (technically VLAs are a C feature from C90). To make sure that you are using standard conforming C++, pass -pedantic to get a warning and -pedantic -Werror to make the warning into a hard error.

I recommend the following when compiling in debug mode:

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

O0 is an optimization flag and -g3 is used for debugging. These need to be changed when you want to use optimization and don't need debugging. However, -Werror -Wconversion sometimes might need to be removed as you might not be able to change code for certain reasons, such as when using third party libraries. For a description of what each one does, refer to here.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166