const unsigned int x = "1234"[0];
int main () {
switch (0) {
case x:
break;
};
}
Weird little compiler error
This code doesn't compile: "x cannot appear in a constant-expression"
The strange-looking initialisation of x is the result of a macro expansion. I get the same error if x is initialised from an inline function call. What the hell is happening? I'm using gcc 4.2.4
A case label must consist of a constant expression. x is not a constant expression, it is a (const-qualified) variable. Furthermore a const-expression cannot be or contain an array referencing operation (so you couldn't replace 'x' with the "1234"[0] bit either).
What are you REALLY trying to do? I assume this is a contrived example, because 'switch(0)' is also pointless.
What are you REALLY trying to do? I assume this is a contrived example, because 'switch(0)' is also pointless.
x is not a constant, because you didn't initialize it with a constant-expression. To the best of my knowledge, accessing a string index dis not a constant expression.
Well I was going to post you this to argue that they should be the same:
However, a new error "an array reference cannot appear in a constant-expression"
So now there are two problems:
1) The compiler can't extract a character from the string at compile-time, which seems dumb.
2) If Foo::x is initialised to some number directly, the case statement compiles, yet x and Foo::x should be interchangable, right?
const unsigned int x = "1234"[0];struct Foo { static const unsigned int x = ("1234")[0];};int main () { switch (0) { case Foo::x: break; };}
So now there are two problems:
1) The compiler can't extract a character from the string at compile-time, which seems dumb.
2) If Foo::x is initialised to some number directly, the case statement compiles, yet x and Foo::x should be interchangable, right?
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement