Reputation: 41
How can I convert the following if=statement to a switch-statement WITHOUT needing to create a case for every number between that interval (41-49)? Is it possible?
if (num < 50 && num > 40)
{
printf("correct!");
}
Upvotes: 3
Views: 1431
Reputation: 13924
What about this?
switch ((num-41)/9) {
case 0:
printf("correct!");
break;
}
Upvotes: 1
Reputation: 9132
You have to enumerate every case for a switch. The compiler converts this to a jump table, so you can't use ranges. You can, however, have multiple cases use the same block of code, which may be closer to what you want.
switch(num) {
case 41:
case 42:
case 43:
case 44:
case 45:
case 46:
case 47:
case 48:
case 49:
printf("correct!");
break;
default:
break;
}
Upvotes: 1
Reputation: 89192
In C or C++ (since you are using printf, I'll assume that's what it is), cases need to be enumerated for each choice.
The only difference between switch/case
and if
is the possibility that the compiler can turn it into a computed goto instead of checking ranges. If switch/case
supported ranges, that would defeat the purpose of opening the possibility of this optimizaton.
Upvotes: 0
Reputation: 3082
bool criteria1 = (num < 50 && num > 40);
switch criteria1: ...
It may result in multilevel decision networks.. scary?
Upvotes: 0