IF-ELSE 和 SWITCH 有什么区别? [英] What is the difference between IF-ELSE and SWITCH?
本文介绍了IF-ELSE 和 SWITCH 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以向我解释一下吗?
Can someone please explain this to me?
推荐答案
它们非常相似,但都有一些特殊功能.
They are pretty similar but each has a few special features.
切换
switch
通常比许多嵌套的if else
更紧凑,因此更具可读性- 如果您省略两个 switch case 之间的
break
,在许多类 C 语言中,您可能会遇到下一个 case.使用if else
你需要一个goto
(这对你的读者来说不是很好......如果语言完全支持goto
). - 在大多数语言中,
switch
只接受原始类型作为键和常量作为大小写.这意味着编译器可以使用非常快的跳转表对其进行优化. 如何正确格式化
switch
并不是很清楚.从语义上讲,案例是跳转目标(如goto
的标签),应该向左对齐.当你有花括号时,事情会变得更糟:
switch
is usually more compact than lots of nestedif else
and therefore, more readable- If you omit the
break
between two switch cases, you can fall through to the next case in many C-like languages. Withif else
you'd need agoto
(which is not very nice to your readers ... if the language supportsgoto
at all). - In most languages,
switch
only accepts primitive types as key and constants as cases. This means it can be optimized by the compiler using a jump table which is very fast. It is not really clear how to format
switch
correctly. Semantically, the cases are jump targets (like labels forgoto
) which should be flush left. Things get worse when you have curly braces:
case XXX: {
} break;
或者大括号应该单独成行吗?右大括号应该放在 break
后面吗?那会有多难读?等
Or should the braces go into lines of their own? Should the closing brace go behind the break
? How unreadable would that be? etc.
if-else
if
允许条件中的复杂表达式而 switch 需要一个常量- 您不会不小心忘记了
if
之间的break
,但您可以忘记else
(尤其是在剪切和粘贴期间) - 它接受所有数据类型.
if
allows complex expressions in the condition while switch wants a constant- You can't accidentally forget the
break
betweenif
s but you can forget theelse
(especially during cut'n'paste) - it accepts all data types.
这篇关于IF-ELSE 和 SWITCH 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文