mkiesner
mkiesner

Reputation: 695

Array initialization from non-constexpression

I am trying to understand an example taken from the C++ Primer Book regarding array initialization. They say that

The number of elements in an array is part of the array’s type. As a result, the dimension must be known at compile time, which means that the dimension must be a constant expression

An example follows which is supposed to result in an error:

unsigned cnt = 42; // not a constant expression
string bad[cnt];   // error: cnt is not a constant expression

However, compiling this with g++ 4.8.4 does not result in an error.

Is this an error or outdated information in the book, or is it just a g++ feature?

Upvotes: 2

Views: 134

Answers (2)

Kadir Erdem Demir
Kadir Erdem Demir

Reputation: 3595

I think it is worth to talk about "alloca" here. This is how those types of arrays are implemented. Of course they have their limitations like size of operator is not supported for them. You can check details: http://man7.org/linux/man-pages/man3/alloca.3.html

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

Yes, it should be a g++ feature.

It will emit a warning when -pedantic option is used.

test program

#include <string>
using std::string;

int main(void){
    unsigned cnt = 42; // not a constant expression
    string bad[cnt];   // error: cnt is not a constant expression
    return 0;
}

result on Wandbox

prog.cc: In function 'int main()':
prog.cc:6:19: warning: ISO C++ forbids variable length array 'bad' [-Wvla]
     string bad[cnt];   // error: cnt is not a constant expression
                   ^

Upvotes: 1

Related Questions