0

my first own question at Stack Overflow:

I am working on a C++ program where something happens that I thought would not work. My colleague is setting up a vector myvec of elements of some class we are working with. Its size is chosen by the user on calling the program, so it is not fixed when compiling! Nevertheless, the code includes the following statement which is working:

    const unsigned myNumber = myvec.size();
    bool valid_PDFplot[myNumber];

I always thought that you cannot define an array of a size that is not already known at compile time unless you are using dynamically allocated memory with new? As said above, the size of the vector is not set at compile time as the user has the possibility to add an arbitrary number of elements using push_back. Why is the code shown above still working?

DerAuenlaender
  • 139
  • 2
  • 6

1 Answers1

2

It's accepted because your compiler implements variable-length arrays as an extension. (VLAs were introduced to standard C in 1999, and made optional in 2011. They've never been added to standard C++.)

If you're using gcc, the -pedantic compiler option will cause it to reject the declaration.

c.cpp: In function 'int main()':
c.cpp:6:32: warning: ISO C++ forbids variable length array 'valid_PDFplot' [-Wvla]
     bool valid_PDFplot[myNumber];
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • Thanks, that is exactly the answer I've been looking for. Is it considered bad style if I use this 'feature'? – DerAuenlaender Feb 03 '16 at 13:50
  • @DerAuenlaender: It's not portable, so your code might not compile with another C++ compiler. As a matter of style, if you need variable-length arrays in C++, you should probably be using `std::vector`, or perhaps some other container class. – Keith Thompson Feb 03 '16 at 17:07