3

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!");
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
wadafarfar
  • 41
  • 2

4 Answers4

1

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;
}
jncraton
  • 9,022
  • 3
  • 34
  • 49
1

What about this?

switch ((num-41)/9) {
case 0:
    printf("correct!");
    break;
}
phlogratos
  • 13,234
  • 1
  • 32
  • 37
0
bool criteria1 = (num < 50 && num > 40);
switch criteria1: ...

It may result in multilevel decision networks.. scary?

kagali-san
  • 2,964
  • 7
  • 48
  • 87
  • are booleans the only way to do this? is there another method? can i attach conditions to the case instead? just curious. – wadafarfar Jul 07 '11 at 20:40
  • @wadafarfar, if your desired language supports returning true|false values when evaluating (...) and they are seen by switch statement - then, yes. `switch (condition) true: code1; false: code2; end;` will work. Write a test for that? – kagali-san Jul 07 '11 at 21:06
0

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.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192