• 12
• 9
• 9
• 13
• 10

# Weird little compiler error

This topic is 3291 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

This code doesn't compile: "x cannot appear in a constant-expression"
const unsigned int x = "1234"[0];

int main () {
switch (0) {
case x:
break;
};
}


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

##### Share on other sites
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.

##### Share on other sites
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.

##### Share on other sites
Well I was going to post you this to argue that they should be the same:
const unsigned int x = "1234"[0];struct Foo {	static const unsigned int x = ("1234")[0];};int main () {	switch (0) {	case Foo::x:		break;	};}
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?