If the expression doesn't match any of the constants in the case statement then default case will be executed.
Syntax:
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
Let us look into some examples for better understanding,
Example 1:
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=5;i++)
{
switch(i)
{
case 1:
case 2:
case 3:
case 5:
case 4: printf("A");
default: printf("C");
}
}
return 0;
}
Output:
- In the above example there is no break in the case block. So in this kind of situation, all the case blocks below the matched case will be executed including default.
- For executing a particular case block alone it should be terminated with break, otherwise case blocks below that case block will also be executed.
- The order of the case doesn't matter.
- If the switch expression doesn't match with any of the case constants then default block will be executed.
- default case can be placed anywhere inside the switch block.
float x = 1.5;
switch (x)
{
case 1.1: printf("A");
....
}
The above code snippet will throw an error because the switch expression must be an integer type.
Example 3:
int x = 1.5;
switch (x)
{
case 1: printf("A"); break;
case 1: printf("B"); break;
....
}
The above code snippet will throw an compiler error because two case labels cannot have same value. We should not duplicate the case labels.
Example 4:
int x = 1.5;
int y;
switch (x)
{
y = x; //statement inside switch
case 1: printf("A"); break;
case 1: printf("B"); break;
....
}
Note: Any statement inside the switch block other than the case statements will not be executed. It will be skipped by the compiler, it won't throw an error.
No comments:
Post a Comment