0

From C++ document http://www.cplusplus.com/doc/tutorial/arrays/
To define an array like this int a[b]; the variable b must be a constant.

Here is what I am running under g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

int main(){
    int a = 10;
    int b[a];

    for(int i = 0; i < 10; i++){
        cout << b[i] << endl;
    }
    return 0;
}

variable a is not a constant and I have no error. May I ask start from what version of g++ will accept this kind of array definition?

3
  • Well, in this case I expect the compiler optimizes a out so that you are, in fact, initializing with a constant. Try instead initializing with rand()/100000 and see what happens (#include <cstdlib>) Commented Oct 18, 2013 at 0:09
  • 3
    @MattPhillips doubt that, the optimizer comes in long after that. Commented Oct 18, 2013 at 0:10
  • @MattPhillips: Optimization shouldn't be relevant. The language rules require a constant expression, and that doesn't just mean something that the compiler is able to figure out how to evaluate at compile time. Commented Oct 18, 2013 at 0:11

4 Answers 4

4

The compiler is using a non-standard extension. Your code isn't valid, standard C++. Variable length arrays aren't a feature of C++.

Note that the size has to be a compile-time constant, not merely a constant (i.e. const).

Sign up to request clarification or add additional context in comments.

3 Comments

"Variable length arrays aren't a feature of C++" yet
@PeterT hopefully, never.
I meant this could be in C++14. I don't particularly like it either, but some people seem to want it badly. Not to mention all the new special restrictions that they have will only confuse beginners
4

Variable length arrays are allowed as an extension in GCC.

See GCC Docs.

Comments

1

You can't create dynamic arrays in C++, because your compiler needs to know how big your program is before compiling. But to you can create an array with 'new':

int *b = new int[a];

This will create a new array reserving new storage. You can access this array the normal way.

for(int i=0; i<a; i++)
{
   b[i];
}

Comments

0

For a dynamically sized array you can use a std::vector in C++ (not exactly an array, but close enough and the backing store is available to you if you need the raw array). If you insist on creating a dynamic block of data you can simply use 'new type[]'.

int a = 100;
int[] b = new int[a];

1 Comment

Thanks for helping but this is not I want.

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.