Reputation: 4507
I'm just curious: Take a switch-statement like:
switch(myVar)
{
case(label):
...
break;
}
Why must label be const?
Upvotes: 0
Views: 574
Reputation: 129504
The whole idea behind a switch
in C is that the compiler can "prepare" where what myVar
value goes. Yes, it may still choose to use a if-else-if-else type chain of operations, but given a particular value of myVar
, the outcome should be the same every time. Of course, if the expression in label
is not a constant, then it can't determine where each value goes at compile-time.
If that's not what you want, then you need to do something else in your code - tables or a lot of if-statements would be the most obvious solutions.
Upvotes: 2
Reputation: 5239
If label is not constant it might lead to ambiguity perhaps,
int a = 1, b = 6;
switch(myVar)
{
case a+1;
//etc
break;
case 2;
//etc
break;
}
Upvotes: 2
Reputation: 16263
Andy Prowl has provided the relevant paragraph from the standard, here's a possible reason why you'd want it like that.
Consider switch (c) { case a: ...; break; case b: ...; break; }
. What would you expect to happen if a==b
and b==c
?
If you write this in terms of if ...; if ...
or if ...; else if ...
, the semantics are clear. In the case of switch
, not so much. Sure, you could define it to behave one way or the other, but imho it would result in code whose behaviour isn't immediately clear, and that's a bad thing in general.
Upvotes: 4
Reputation: 126522
Any constant expression can be used. Per Paragraph 6.4.2 of the C++11 Standard:
The condition shall be of integral type, enumeration type, or class type. If of class type, the condition is contextually implicitly converted (Clause 4) to an integral or enumeration type. Integral promotions are performed. Any statement within the switch statement can be labeled with one or more case labels as follows:
case constant-expression :
where the constant-expression shall be a converted constant expression (5.19) of the promoted type of the switch condition. No two of the case constants in the same switch shall have the same value after conversion to the promoted type of the switch condition.
Upvotes: 1