10

There is such code:

#include <iostream>

int main()
{
  int size;
  std::cin >> size;

  size = size + 1;
  int tab3[size];

  tab3[0] = 5;
  std::cout << tab3[0] << " " << sizeof(tab3) << std::endl;
  return 0;
}

The result is:

$ g++ prog.cpp -o prog -Wall -W 
$ ./prog
5
5 24

Why does this code even compile? Shouldn't be length of array a constant variable?

I used g++ version 4.4.5.

3 Answers 3

13

Variable-length arrays in C++ are available as an extension in GCC. Compiling with all warnings should have alerted you to that fact (include -pedantic).

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

14 Comments

+1, tho I had no idea sizeof() can also be non-constant. If I ever thought of using sizeof() on that I'd expect it to fail for some reason.
@MichaelKrelin-hacker: again, as an extension... VLAs require a runtime sizeof(), so it's part of the C99 standard. It's just not a very C++-type of thing. Think about decltype and all this...
It is interesting though that there doesn't appear to exist any standardized method of allocating memory on the stack. We could handle object construction with placement-new, but it's just impossible in C++ to get a variable amount of raw memory on the stack.
Sure, I don't doubt it's a standard, it's just that I had no idea and never thought of it. Probably alloca() is not standardized, but it's pretty common, not?
There was a proposal to consider VLA's in C++ as well but the Standards committee dropped it because they considered the modifications to the type system for its support far outweighed the flexibility they would provide.
|
7

It is a C99 feature, not a part of C++. They are commonly refered to as VLAs(Variable Length Arrays.

If you run g++ with -pedantic it will be rejected.

See GCC docs for more info.

See also: VLAs are evil.

Comments

2

GCC provide's VLA's or variable length arrays. A better practice is to create a pointer and use the new keyword to allocate space. VLA's are not available in MSVC, so the second option is better for cross platform code

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.