2

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?

1
  • 1
    It's a non-standard g++ extension. C++ doesn't support non-const sized arrays. Commented Dec 6, 2015 at 14:34

2 Answers 2

1

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
                   ^
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I did not know about the -pedantic compiler flag which i find useful when learning C++.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.