Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch case without variable

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.

like image 839
user1868856 Avatar asked Aug 01 '26 17:08

user1868856


2 Answers

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;
}
like image 127
Devika B Avatar answered Aug 04 '26 05:08

Devika B


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.

like image 37
Esailija Avatar answered Aug 04 '26 06:08

Esailija



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!