Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

language agnostic - What is the difference between IF-ELSE and SWITCH?

Can someone please explain this to me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They are pretty similar but each has a few special features.

switch

  • switch is usually more compact than lots of nested if 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. With if else you'd need a goto (which is not very nice to your readers ... if the language supports goto 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 for goto) 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.

  • In many languages, switch only accepts only some data types.

if-else

  • if allows complex expressions in the condition while switch wants a constant
  • You can't accidentally forget the break between ifs but you can forget the else (especially during cut'n'paste)
  • it accepts all data types.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...