为什么即使找不到匹配项,switch语句也执行case块? [英] Why does the switch statement execute a case block even when a match is not found?

查看:560
本文介绍了为什么即使找不到匹配项,switch语句也执行case块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

switch(1){
    case 1: print 1; // prints 1 (as expected)
    case 2: print 2; // prints 2 (even though match is not equal?)
    case 3: print 3; // prints 3 (even though match is not equal?)
}

我知道,如果在每个case表达式匹配之后不使用break,大多数编程语言将继续执行每个语句.但是我对于大多数语言为什么在第二和第三种case语句上成功执行case块感到困惑.

I know that most programming languages continue to execute each statement if you don't use break after each case expression match. But I'm confused as to why most languages execute a case block as a successful match on this second and third case statement.

仅需澄清一下: 我知道switch语句的行为,但是我不理解即使没有找到匹配项也将执行case语句/语句作为成功匹配项的逻辑.

Just to clarify: I am aware of the behavior of the switch statement, but I don't understand the logic that it makes sense to execute a case block/statement as a successful match even though a match is not found.

更新:我刚刚更新了问题,以反映大多数编程语言,而不仅仅是PHP.

UPDATE: I just updated the question to reflect most programming languages and not just PHP.

推荐答案

之所以这样,可能是因为PHP从C借用了语法.

The reason it's that way is probably because PHP borrowed the syntax from C.

我之所以最初使用这种方式,是因为它有助于减少我怀疑的代码重复.

However the reason it was originally this way is it helps to reduce code duplication I suspect.

如果您有类似的话:

if($item == 'SOUP' || $item == 'FRIES'){
    eat($item);
}elseif($item == 'JUICE'){
    drink($item);
}else{
    use($item);
}

如果从不进行切换,则需要4种情况,"SOUP"和"FRIES"具有相同的逻辑,否则,您可以使切换更好:

If switches never followed through you would need 4 cases with 'SOUP' and 'FRIES' having the same logic, without this you can make the switch nicer:

switch($item){
    case 'SOUP':
    case 'FRIES':
        eat($item);
        break;
    case 'JUICE':
        drink($item);
        break;
    default:
        use($item);
        break;
}

这篇关于为什么即使找不到匹配项,switch语句也执行case块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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