Is it possible to write switch case code without specifying a variable in switch? say I have two variables int x and int y. I want to conditionally run code based on different combinations of x and y. For example
switch
{
case (x==1 && y==1): //do something.
break;
case (x==3 && y==-1): //do something.
break;
case (x==0 && y==3): //do something.
break;
default: //do something.
break;
}
This code gives me error.
Keep the switch parameter as ture
switch(true)
{
case (x==1 && y==1): //do something.
break;
case (x==3 && y==-1): //do something.
break;
case (x==0 && y==3): //do something.
break;
default: //do something.
break;
}
That doesn't really read or write better than
if (x==1 && y==1) {
//do something.
}
else if (x==3 && y==-1) {
//do something.
}
else if (x==0 && y==3) {
//do something.
}
else {
//do something.
}
But yea, it's not possible with switch case.
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