StevoStephenson StevoStephenson - 21 days ago 6
C++ Question

Is case statement1 + statement2: poor coding?

I have written a switch statement that looks like this:

switch(statement){
case statement1:
break;
case statement2:
break;
case statement3:
break;
case statement4:
break;
case statement1 + statement2:
break;
case statement1 + statement3:
break;
case statement1 + statement4:
break;
default:
break;
}


with the statements defined in the header like this:

#define statement1 999


#define statement2 32898


#define statement3 32899


#define statement4 32900


This compiles and works fine using visual studio 2003.

For me this is providing more statements with out the need to define more variables. Allowing me to have different options depending on what statements have been selected in previous code.

How does the community perceive this code? Accepted? Bad practice? Avoidable?

The only risk I can see is if there is ever a definition 33897,33898,33899.

Answer

Well, although I don't like switches, I think your code could be improved a lot.

First, using operators in switches is not wrong. You can use any kind of constexpr things you want. Operations on integers are constexpr.

The thing I would change is this:

const int statement1 = 999;
const int statement2 = 32898;
const int statement3 = 32899;
const int statement4 = 32900;

I would use constexpr if c++11 was available.

Macros can hide shady stuff, such as function call and complex operation. Now they are ints, usable at compile time.

Beside, the constants are hard to read, especially with those namesĀ­. You could generate, at compile time, the value of these constants using constexpr functions, or simply give them a better name and maybe commenting it.

Adding integers together in switch statement is not bad in practice, but as you said, the only risk I can see is if there is ever a definition 33897, 33898, 33899. This is why you should give meaning to the result of those operation. If 33897 is really the value you want to test, then do this:

const int combine2 = statement1 + statement2;
const int combine3 = statement1 + statement3;

You can define those in your very function if you don't want them in your global scope.

Comments