Jump to content
  • Advertisement
Sign in to follow this  
spraff

Weird little compiler error

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

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!