0

Is it true that the size of an array has to be a constant variable? Like for example,

const int size = 5;//would int size = 5 not be allowed?
int array[size];

Also if this this is true what happens when you work with dynamic arrays? Would int size = 5; be fine then?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
filipanton1
  • 59
  • 1
  • 1
  • 9
  • 2
    It has to be a compile-time constant. It doesn't have to be a named constant. –  Nov 11 '18 at 14:52
  • Are you talking about c++ standard or g++ compiler extension? – user202729 Nov 11 '18 at 14:52
  • 3
    Sounds like a [good book on C++](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) is what you need. Learning by trial/error and SO isn't effective. – StoryTeller - Unslander Monica Nov 11 '18 at 14:53
  • I just mean, what is the right way of doing it? – filipanton1 Nov 11 '18 at 14:54
  • For static array's yes, it has to be a compile time constant. Dynamic arrays reallocate memory on the heap as needed. – mreff555 Nov 11 '18 at 14:55
  • Things to research: [std::array](https://en.cppreference.com/w/cpp/container/array), [std::vector](https://en.cppreference.com/w/cpp/container/vector), [std::size](https://en.cppreference.com/w/cpp/iterator/size). Advice: Stay away from C-style arrays in C++. – Jesper Juhl Nov 11 '18 at 14:55
  • "what is the right way of doing it?" - the right way is to *not* do it. If you need a dynamic array use `std::vector`. For a static array use `std::array`. – Jesper Juhl Nov 11 '18 at 14:57
  • @JesperJuhl I mean, if im just using a standard array, the variable has to be const. – filipanton1 Nov 11 '18 at 14:59
  • @filipanton1 as others have already said. It has to be *a compile time constant*. But, just use `std::array` or `std::vector` already. – Jesper Juhl Nov 11 '18 at 15:02
  • The size of a static array must be const and known at compile time, although some compilers are not so fuzzy and will allow it to be a runtime variable, but that is not portable and bad practice. – Fabio Nov 11 '18 at 15:03
  • The size of an array must be `constexpr`. Being `const` is just not enough, due to the possibility of having `const` variable, which has value computed at runtime. – Algirdas Preidžius Nov 11 '18 at 15:06

1 Answers1

2

In C++, yes, arrays have to have a compile time value (explicit content or a constant variable).

Variable Length Arrays are C99, and a GCC extension. You should not use them in C++, even if g++ allows them.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62