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.
切换
-
切换
通常比许多嵌套更紧凑,如果没有
,因此更具可读性 - 如果省略在两个交换机案例之间
中断
,您可以使用许多类C语言进入下一个案例。使用if else
你需要一个goto
(这对你的读者来说不是很好......如果语言完全支持转到
。 - 在大多数语言中,
开关
只接受原始类型作为键和常量作为案例。这意味着它可以由编译器使用非常快的跳转表进行优化。 -
目前还不清楚如何格式化
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;
或者大括号是否属于他们自己的行?闭合支撑是否应该落后于中断
?这有多难以理解?等等。
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想要一个常量 - 你不能不小心忘记
break
如果
s但你可以忘记else
(特别是在cut'n'paste期间) - 它接受所有数据类型。
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屋!
查看全文