Sign in to follow this  
spraff

Weird little compiler error

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this