Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement syntax for same action through different cases

Two constants (1+2) share the same case statement. I don´t want to double the code.

What is the right syntax to do this?

switch (expression) {
        case 0:
            [self taskA];
            break;
        case 1:
            [self taskB];
            break;
        case 2:
            [self taskB]
            break;
        default:
            break;
    }
like image 413
coco Avatar asked Dec 20 '22 09:12

coco


1 Answers

Use :

switch (expression) {
    case 0:
        [self taskA];
        break;
    case 1:
    case 2:
        [self taskB];
        break;
    default:
        break;
}

Edit 1:

In switch we say a term called fall-through. Whenever control reaches to a label say case 0: it falls till break is found. On break control is sent to the closing braces of switch.

If break is not encountered it goes to next case as in case then case 2. So above case 1 and case 2 shares one break statement.

like image 73
Anoop Vaidya Avatar answered Dec 24 '22 00:12

Anoop Vaidya