Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant expressions in array declarations

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?

like image 790
James Raitsev Avatar asked Dec 16 '22 20:12

James Raitsev


1 Answers

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
like image 114
Kerrek SB Avatar answered Dec 22 '22 01:12

Kerrek SB