I've looked at these and they do not answer my question:
variable-sized object may not be initialized
C compile error: "Variable-sized object may not be initialized"
Error: Variable-sized object may not be initialized. But why?
I am trying to write some fairly portable c
code:
int main ()
{
const int foo=13;
int bar[foo]={0};
return 0;
}
I get a variable-sized object may not be initialized
error when compiling as c
code using either:
- gcc 4.3.4
- arm-linux-gnueabi-gcc 4.4.5
And if i compile it as c
in VS2008 i get a slightly different error C2057: expected constant expression
I understand that here, the c
code compiler is not recognising const int foo=13;
to be truely constant; for example we might have
void a(int fool)
{
const int foo=fool;
int bar[foo]={0};
}
I also realise that unlike the gcc compilers, the VS2008 compiler has no concept of C99 variable-length arrays. And that MS apparently has not mentioned any future support.
And yet, cpp
code compilation with either gcc or MS compilers is altogether different/cleverer ?!
And also what i do not understand regarding the gcc c
code compiler is:
(NB: in this last case, MS c
code compilation fails; consistently as with int bar[foo]={0};
)
As Matt has already quoted the standard,
const
qualifier applied to an integer variable does not count as an integer constant expression. We might wonder why? It looks as innocent as an integer constant!This may be because
const
are not absolutelyconsts
. You might alter their values through pointers and all a compiler might do, if at all it catches such an assignment , is throw a warning but cant really prevent you from altering theconst
value.PS: Don't trust the online compilers like ideone.com etc. Here's one silly runtime error it throws for a very simple C program.
Actually, for my gcc (version 4.4.4), your last example
also does not compile, just as one would expect. You might want to double-check your toolchain (to verify you didn't relink an existing '.o' in there somewhere), and try again.
If you find that it really does work, here is my
gcc -v
output, perhaps you can detect a difference in the configuration and that might lend some light.C99 §6.7.8 Initialization says this:
So your initialization is invalid C.
The only way for
type a[size]
to not be a VLA is forsize
to be an integer constant expression (§6.7.5.2). What you have there is not an integer constant expression, so you have a VLA:Part §6.6/6 Constant expressions defines them as: