开发者

converting an if statement to a switch statement

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!");
}


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;
}


What about this?

switch ((num-41)/9) {
case 0:
    printf("correct!");
    break;
}


bool criteria1 = (num < 50 && num > 40);
switch criteria1: ...

It may result in multilevel decision networks.. scary?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜