开发者

What's the difference between switches and conditionals? [duplicate]

开发者 https://www.devze.com 2023-02-14 12:13 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: When to use If-else if-else over switch statments and vice versa
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消