I'm aware that if you set a dynamic value in c/c++ you can't use that value within brackets to allocate an array (which would make it a so-called variable length array (VLA), which the current C++ standard does not support)...
i.e. See:
C++ : Variable Length Array
http://en.wikipedia.org/wiki/Variable-length_array
What I don't quite get (and what I haven't see asked precisely here) is why GNU c/c++ compilers (gcc, g++) are okay with using dynamic allocation based on an integer value (as far as I can tell) so long as that value is a constant within the scope of the array allocation, but Visual Studio's does not support this and will refuse to compile the code, spitting out errors.
e.g. in g++
void Foo(const unsigned int bar) { double myStuff[bar]; //... do stuff... } ...compiles just fine...
But the same code refuses to compile in versions of VS I've used, unless whatever I pass to bar is const in all scopes or is a #define, static const, etc.
I would suspect that maybe GNU compilers use the scope to infer that this value is a constant within that scope and either simply assign it to a malloc or handle it specially somehow.
My questions are:
- Who (VS or GNU) is closer to the standard in terms of how they handle this?
- Is there a way to do this VS using
[]on a value that's constant within scope, but not globallyconstthroughout the entire program without amalloccall? - Are there any issues I should be aware of if I use this in my GNU-compiled code?
constw/in the scope of the declaration, as I say below. By contrastbarisconstwithin the scope but was not known at compile time. I guessg++supports allocation via both non-constandconstvars within the current scope (according to a quick test I did). And I know either way the array is dynamic. That said I was unsure whether theconstcase was considered a VLA in spec terms, as the lack of examples of this flavor might hint @....constwithin the declaration scope (which would make the VLAs in spec-terms a specific subset of dynamic arrays).