Archived

This topic is now archived and is closed to further replies.

constant extern variable as case expression

This topic is 5021 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

I have constant extern variable that is defined in main.cpp and I´m trying to use it as a case expression but compiler will give me an error: C:\OPENGL PROJECT1\classBlock.cpp(77) : error C2051: case expression not constant So..
RED_BLOCK = 3; // This gives error: "l-value specifies const object" like it should..


switch (blockType)
{	
case RED_BLOCK: // but still this one will give:

                // case expression not constant..

   break;
default:
   break;
}
..What I´m missing? [edited by - Mkk on March 20, 2004 2:15:03 PM]

Share this post


Link to post
Share on other sites

const int RED_BLOCK = 3;

switch (blockType)
{
case RED_BLOCK: // Should work now.

break;
default:
break;
}


That should do it, you have to explicitly imply if its constant or not, and the datatype (int in this case).

Share this post


Link to post
Share on other sites
You can''t use an expression as a value in a case statement unless the expression can be evaluated at compile time. Chances are that the way you have your extern const defined, the value would not be known until link time.

Consider changing the variable from const extern to simply const and define the value up front. Because const variables have implicit internal linkiage this shouldn''t give you any troubles with multiple definition linkage errors.

Share this post


Link to post
Share on other sites
the people who told you to use "const int" or "#defines" obviously don''t understand your quesion ...

your situation is you HAVE the item defined somewhere else, and are getting to it through an extern reference right?

SiCrane''s post is correct, this cannot be done - because EXTERN tells the compiler not to worry about the operation, the linker will resolve it, but the case statement cannot use such items ... sorry.

An if/else series could of course use them ... the switch statement is shothand for a series of if/else if''s only in very special cases (where all of the cases are of the same type, scalar, and known at compile time).

Share this post


Link to post
Share on other sites