Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!");
}
like image 971
wadafarfar Avatar asked Dec 11 '25 22:12

wadafarfar


2 Answers

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;
}
like image 50
jncraton Avatar answered Dec 14 '25 22:12

jncraton


What about this?

switch ((num-41)/9) {
case 0:
    printf("correct!");
    break;
}
like image 32
phlogratos Avatar answered Dec 14 '25 22:12

phlogratos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!