If-Else vs Switch Statement in C
The if-else and switch statements are used for decision-making in C programming, but they serve different purposes. This page compares these two control structures, helping you understand when to use one over the other.
1. If-Else Statement
The if-else statement evaluates a condition and executes the corresponding block of code depending on whether the condition is true or false. It's flexible and can evaluate complex conditions.
Syntax:
if (condition) {
// code to be executed if condition is true
}
else {
// code to be executed if condition is false
}
Example:
#include <stdio.h>
int main()
{
int num = 2;
if (num == 1) {
printf("Number is 1\n");
} else {
printf("Number is not 1\n");
}
return 0;
}
Output:
Number is not 1
2. Switch Statement
The switch statement evaluates a single expression and compares it with several possible values (called cases). It is useful when you have multiple conditions based on the same expression. Unlike if-else, it requires constant values for the case labels.
Syntax:
Syntax:
switch(expression)
{
case value1:
// code to be executed
break;
case value2:
// code to be executed
break;
default:
// code to be executed if no case matches
}
Example:
#include <stdio.h>
int main()
{
int num = 2;
switch (num) {
case 1:
printf("Number is 1\n");
break;
case 2:
printf("Number is 2\n");
break;
default:
printf("Number is not 1 or 2\n");
break;
}
return 0;
}
Output:
Number is 2
3. Key Differences
Feature | If-Else | Switch |
---|---|---|
Expression Type | Can evaluate any condition | Can only evaluate an integer or character |
Complexity | Suitable for simple or complex conditions | Suitable for comparing a single expression to multiple values |
Control Flow | Can handle multiple conditions with logical operators | Handles multiple cases for a single expression |
Break Statement | Not necessary | Break is required to exit the switch |
4. When to Use
- Use if-else when you need to check multiple conditions that are not related to a single expression.
- Use switch when you have a single expression with multiple possible values, and each value requires a different operation.