![if !IE]> <![endif]>
Switch vs if-else
“if-else” and “switch” both are selection statements. The selection statements, transfer the flow of the program to the particular block of statements based upon whether the condition is “true” or “false”. However, there are some differences in their operations. These are given below:
1. Expression inside if statement decide whether to execute the statements inside if block or under else block. On the other hand, expression inside switch statement decide which case to execute.
2. An if-else statement uses multiple statements for multiple choices. On other hand, switch statement uses single expression for multiple choices.
3. If-esle statement checks for equality as well as for logical expression. On the other hand, switch checks only for equality.
4. The if statement evaluates integer, character, pointer or floating-point type or Boolean type. On the other hand, switch statement evaluates only character or a integer data type.
5. Sequence of execution is like either statement under if block will execute or statements under else block statement will execute. On the other hand the expression in switch statement decide which case to execute and if do not apply a break statement after each case it will execute till the end of switch statement.
6. If expression inside if turn out to be false, statement inside else block will be executed. If expression inside switch statement turn out to be false then default statements are executed.
7. It is difficult to edit if-else statements as it is tedious to trace where the correction is required. On the other hand, it is easy to edit switch statements as they are easy to trace.
There are some important things to know about switch statement. They are
1. A switch statement can only work for quality of comparisons.
2. No two case labels in the same switch can have identical values.
3. If character constants are used in the switch statement, they are automatically converted to their equivalent ASCII codes.
4. The switch statement is more efficient choice than if in a situation that supports the nature of the switch operation.
Tips: The switch statement is more efficient than if-else statement.
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.