case语句用于条件判断 break必须与case配对吗?

[更新]
·
·
分类:行业
2220 阅读

case语句用于条件判断

break必须与case配对吗?

break必须与case配对吗?

不一定。如果不与其配对,如果执行完第一个case语句后,后面还有其它case,不需要再进行判断条件,依次执行下一个case。
如果与其匹配的话,遇到break就停止,结束程序。
例如:
switch(m)
{
case1:printf(“A
”);
case2:printf(“B
”);
}
如果m1,则程序运行结果为:
A
B
如果case后面加break语句:
switch(m)
{
case 1:printf(“A“);break;
case 2:printf(“B”):break;
}
如果m1,则程序运行结果为:
A

为什么符合case条件依然会直接执行default?

估计你是在开发时用switch语句出的问题。switch是一个用于分支条件的程序体,语法如下
switch(变量名)
{
case 变量值1:
……
break;
case 变量值2:
……
break;
case 变量值2:
……
break;
default:
……
break;
}
每一个分支时都应有break,表示其他分支不再执行,题主显然是忘了加break。

sql中的if判断语句应该怎么写?

语义上是按书写的从前到后顺序匹配的。参考SQL 2006标准的Part 2: Foundation (SQL/Foundation)的6.11 ltcase expressiongt:
2) Case:
a) If the value of the ltsearch conditiongt of some ltsearched when clausegt in a ltcase specificationgt is True, then the value of the ltcase specificationgt is the value of the ltresultgt of the first (leftmost) ltsearched when clausegt whose ltsearch conditiongt evaluates to True, cast as the declared type of the ltcase specificationgt.
b) If no ltsearch conditiongt in a ltcase specificationgt evaluates to True, then the value of the ltcase expressiongt is the value of the ltresultgt of the explicit or implicit ltelse clausegt, cast as the declared type of the ltcase specificationgt.
当然优化器有可能可以尝试分析when的条件是否互斥,如果互斥而且无副作用的话可以任意调整顺序,不过表面上展现的语义仍然跟从前到后顺序匹配是一样的。所以从使用的角度看就只认顺序匹配就对了。