不同情况下相同动作的 switch 语句语法 [英] Switch statement syntax for same action through different cases

查看:44
本文介绍了不同情况下相同动作的 switch 语句语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个常量 (1+2) 共享同一个 case 语句.我不想加倍代码.

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

推荐答案

使用 :

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

编辑 1:

switch 中,我们有一个术语叫做fall-through.每当控制到达一个标签时,说 case 0: 它会下降,直到找到 break.break 控制被发送到 switch 的右大括号.

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.

如果没有遇到break,它将转到下一个case,如case 然后case 2.所以上面的 case 1case 2 共享一个 break 语句.

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.

这篇关于不同情况下相同动作的 switch 语句语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆