Reputation: 114795
I was just made aware of a bug I introduced, the thing that surprised me is that it compiled, is it legal to switch on a constant?
Visual Studio 8 and Comeau both accept it (with no warnings).
switch(42) { // simplified version, this wasn't a literal in real life
case 1:
std::cout << "This is of course, imposible" << std::endl;
}
Upvotes: 4
Views: 886
Reputation:
It's not impossible that switching on a constant makes sense. Consider:
void f( const int x ) {
switch( x ) {
...
}
}
Switching on a literal constant would rarely make sense, however. But it is legal.
Edit: Thinking about it, there is case where switching on a literal makes perfect sense:
int main() {
switch( CONFIG ) {
...
}
}
where the program was compiled with:
g++ -DCONFIG=42 foo.cpp
Upvotes: 18
Reputation: 1364
One good reason for this being legal is that the compiler might well be able to resolve the value at compile time, depending on what stage of development you're at.
E.g. you might use something like this for debugging stuff:
int glyphIndex;
...
#if CHECK_INVALID_GLYPH
glyphIndex = -1;
#endif
switch (glyphIndex)
...
The compiler knows for certain that glyphIndex is -1 here, so it's as good as a constant. Alternatively, you might code it like this:
#if CHECK_INVALID_GLYPH
const int glyphIndex = -1;
#else
int glyphIndex = GetGlyph();
#endif
You wouldn't really want to have to change the body of your switch statement just so you could make little changes like this, and the compiler is perfectly capable of rationalising the code to eliminate the parts that will never be executed anyway.
Upvotes: 3
Reputation: 16486
Yes, but why you'd want to (unless debugging) is another matter.
It's similar to if (0)
or while (true)
.
Upvotes: 2
Reputation: 137178
Not everything that makes sense to the compiler makes sense!
The following will also compile but makes no sense:
if (false)
{
std::cout << "This is of course, imposible" << std::endl;
}
It's up to us as developers to spot these.
Upvotes: 16
Reputation: 170519
Yes, it's perfectly legal to switch on any integer expression. It's the same as switch
ing on an integer value returned by a function - a construct used quite often.
Upvotes: 2