I want to use a switch statement to check a range of numbers I have found a few places saying something like
case 1...5
or case (score >= 120) && (score <=125)
would work but I just somehow keep on getting errors.
What I want is if the number is between 1600-1699 then do something.
I can do if statements but figured it's time to start using switch if possible.
Case ranges and case labels can be freely intermixed, and multiple case ranges can be specified within a switch statement.
Using range in switch case in C/C++ You all are familiar with switch case in C/C++, but did you know you can use range of numbers instead of a single number or character in case statement.
Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte , short , char , and int primitive data types.
Using range in switch case in C/C++ In the switch statement we pass some value, and using different cases, we can check the value. Here we will see that we can use ranges in the case statement. After writing case, we have to put lower value, then one space, then three dots, then another space, and the higher value.
You can use ternary operator, ? :
int num = (score >= 120) && (score <=125) ? 1 : -1;
num = (score >= 1600) && (score <=1699 ) ? 2 : num;
switch (num) {
case 1 :
break;
case 2 :
break;
default :
//for -1
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With