Switch & if-else

Which of the two is better, If-else or switch ? Everyone say Switch is better than if-else. But why ?

A sequence of if-else statement is translated as a sequence of labels and goto statements.

But for a switch statement, a compiler generates an internal table to find the matches at run time. Depending upon the constants in the case statement the table can be look up or range table. If the constants are unrelated the comparison are usualy done at the beggining and jump is made to specific entry in the table [lookup table]. If the constants are related and within a range [eg : ‘0’ to ‘9’ ] jump can be made to each range of values [i.e., the range table].


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s