Does anyone know if it's possible to include a range in a switch statement (and if so, how)?
For example:
switch (x)
{
case 1:
//do something
break;
case 2..8:
//do something else
break;
default:
break;
}
The compiler doesn't seem to like this kind of syntax - neither does it like:
case <= 8:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single variable.
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
The syntax of the switch statement is:statement(s); break; case constant 2: statement(s);
No, this isn't possible. There are a few ways I've done this in the past:
Fixed coding:
switch (x)
{
case 1:
//do something
break;
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
//do something else
break;
default:
break;
}
In combination with an if {}
statement:
switch (x)
{
case 1:
//do something
break;
default:
if (x <= 8)
{
// do something
}
else
{
// throw exception
}
break;
}
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