Click here to Skip to main content
15,917,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Because using if...else statement we can compare only one condition.

Switch is a multiple selection statement.
Posted
Comments
Dylan Morley 9-Sep-10 7:33am    
Are you asking a question and answering yourself? Good work, very efficient!

The switch statement is faster because the compiler can optimize the switch statement, whereas it cannot optimize a if/else ladder. Which you use is more a matter of style than anything else.

Sometimes, you simply can't use a switch statement, and those instances are pretty much the only time I won't use a switch statement.
 
Share this answer
 
v2
Have you never heard of nested if...then...else?

But hey thanks for sharing.
 
Share this answer
 
Comments
CPallini 9-Sep-10 7:52am    
'then'? :-D
Dalek Dave 9-Sep-10 9:16am    
oops, c++! :)
The switch statement is a short-hand form of an if-else chain, provided the test is performed on an expression returning an 'integral type' ( see The C++ switch statement[^] at MSDN).
That is the if-else chain is more general and powerful, while the switch statement is often handy.
:)
 
Share this answer
 
v2
Not sure exactly what you're asking here, but... If it's what's the point of a switch statement then about the only difference between a switch and a if/else is syntax. All modern compilers (and I'm including VC++2005 onwards, gcc 3.x onwards and EDG) will generate the same sort of code for a switch as it will for a nested if/else on an integer.

So in both cases the compiler will generate a jump table if the ints switched/ifed on are sequential and otherwise will use tests and jumps. If you use several ranges of sequential ints it will use tests and jumps to get you to the right jump table.

[As a complete aside, if you've got lots of sequential IDs and you're writing well factored code with loads of functions you'll usually end up doing better by avoiding both and implementing a function table. This has the added advantage of making the switching/iffing code indepenent of the values switched on.]

Cheers,

Ash
 
Share this answer
 
// When we use switch in c language in case of if....else statement?

It is comfortable,
when you would check the multiple value variants
of a single variable (given or returned) only... :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900