What's the difference between switches and conditionals? [duplicate]
Possible Duplicate:
When to use If-else if-else over switch statments and vice versa
I'm sure they're fundamentally very different things, but in practical use I've never found a case where there's been any difference between
switch (value){
case 1:
//Do stuff
break;
case 2:
//Do other stuff
break;
}
and
if (value == true){
//Do stuff
}
else{
//D开发者_如何学运维o other stuff
}
What are some example scenarios where one is more appropriate than the other? How, conceptually, are the different? Are there performance of semantics advantages?
They are analogous, but not equivalent. The switch/case
statement is generally used when deciding what routine to invoke given a particular integer, and is commonly employed for checking an enum
. For these cases, it may be more expressive and more readable to use a switch.
The if/else
evaluates a boolean expression.
精彩评论