3

C has a really cool feature called variable length arrays. Its available in C90 and above, and it allows deferring the size of the array until runtime. See GCC's manual 6.19 Arrays of Variable Length.

I'm working in C++. At std=c++11, I'm catching a compile failure due to the use of alloca under Cygwin. I want to switch to variable length arrays, if possible. I also want to try and avoid std::vector and std::array because I want to stay out of the memory manager. I believe every little bit helps, so I'm happy to take these opportunities (that some folks consider peepholes).

Can I use a variable length array in C++03 and C++11?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
jww
  • 97,681
  • 90
  • 411
  • 885
  • You can achieve VLA by using alloca – SwiftMango Jul 27 '15 at 05:23
  • Would it be a problem to put some sanity bounds on your program and use a static-sized array? – paddy Jul 27 '15 at 05:24
  • Its not the bounds checking that bothers me. Its going into the memory manager time and time again each time this particular function is invoked..... Since I can't depend on dynamic arrays (thanks Basile), I'll have to consider a switch to a `std::array` since this is C++ 11. – jww Jul 27 '15 at 05:32

2 Answers2

8

VLAs are not in standard C++03 or C++11, so you'll better avoid them if you want to write strictly standard conforming code (and use e.g. std::vector, which generally use heap for its data - but you might use your own allocator...).

However, several C++ compilers (recent GCC & Clang) are accepting VLAs as an extension.

It is the same for flexible array members; they are not standard in C++ (only in C) but some compilers accept them.

dynarray-s did not get into the C++11 standard...

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • Thanks Basile. I was kind of worried about that. I'm glad I asked. And thanks for the answer. – jww Jul 27 '15 at 05:28
  • I followed your link to [flexible array members](https://en.wikipedia.org/wiki/Flexible_array_member) and don't understand what's to special about them. Aren't they the same as `struct {unsigned length; double*array; };`, i.e. `double*array` instead of `double array[]`? – Walter Jul 27 '15 at 08:36
  • @Walter: No, pointers are not arrays. When allocating a pointer to a `struct` ended by a flexible array member, you will usually allocate some extra space for that flexible array member. – Basile Starynkevitch Jul 27 '15 at 08:37
2

Not if you want code that is standard C++.

No C++ standard supports VLAs, but some C++ compilers do as a vendor-specific extension.

You can achieve a similar effect in C++ using the standard vector. Note that, unlike VLAs which can only be sized when created, a standard vector can be resized as needed (subject to performing appropriate operations on it).

Peter
  • 35,646
  • 4
  • 32
  • 74