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 globallyconst
throughout the entire program without amalloc
call? - Are there any issues I should be aware of if I use this in my GNU-compiled code?