Is it legal to include a constant in C ++?

I just found out about the error that I introduced, which surprised me that it was compiled, is it legal to include a constant?

Visual Studio 8 and Comeau both accept it (without warning).

switch(42) { // simplified version, this wasn't a literal in real life case 1: std::cout << "This is of course, imposible" << std::endl; } 
+4
source share
6 answers

It is possible that the inclusion of a constant makes sense. Consider:

 void f( const int x ) { switch( x ) { ... } } 

However, the inclusion of a constant constant rarely made sense. But it is legal.

Edit: Thinking about this, there is a case where including a literal makes perfect sense:

 int main() { switch( CONFIG ) { ... } } 

where the program was compiled with:

 g++ -DCONFIG=42 foo.cpp 
+18
source

Not everything that makes sense to the compiler makes sense!

The following will compile but does not make sense:

 if (false) { std::cout << "This is of course, imposible" << std::endl; } 

It is for us, as developers, to define them.

+16
source

One good reason for this is that the compiler may very well resolve the value at compile time, depending on what stage of development you are at.

eg. you can use something like this for debugging:

 int glyphIndex; ... #if CHECK_INVALID_GLYPH glyphIndex = -1; #endif switch (glyphIndex) ... 

The compiler knows for sure that glyphIndex is -1 here, so it is no worse than a constant. Alternatively, you can write it as follows:

 #if CHECK_INVALID_GLYPH const int glyphIndex = -1; #else int glyphIndex = GetGlyph(); #endif 

In fact, you would not want to change the body of the switch statement so that you can make small changes like this, and the compiler is quite capable of streamlining the code to exclude parts that will never be executed anyway.

+3
source

Yes, it is legal.

+2
source

Yes, it is legal to include any integer expression. This is the same as switch ing for the integer value returned by a function, a fairly commonly used construct.

+2
source

Yes, but why do you want (unless debugging) is another matter.

It is similar to if (0) or while (true) .

+2
source

All Articles