Switch statement syntax for same action through different cases

社会主义新天地 提交于 2019-12-23 12:09:50

问题


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;
    }

回答1:


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.




回答2:


Multiple case labels can refer to the same statement if break or return are not used at the end of the case. If you do not use a break statement in case 1, the execution flows into case 2.



来源:https://stackoverflow.com/questions/15072171/switch-statement-syntax-for-same-action-through-different-cases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!