Switch Statement is also known as the conditional statement in the C Programming language. Instead of using multiple if else conditions or nested if else we can go with a switch statement.
Syntax of Switch in C
switch(expression) {
case x:
// code block to execute
break;
case y:
// code block to execute
break;
default:
// code block to execute
}
switch statement rules C language
- switch expression can be an integer or a character.
- Expression is evaluated only once and then it will be compared with the cases.
- If the case matched the expression result, that code block will be executed.
default
block is optional and it is executed if there is no case match.break
keyword breaks the switch block and comes out from the switch block.
break Keyword
- When execution reaches to
break
keyword, it breaks out of the switch block. - It stops the execution of the current block.
- It is used in the switch statements to break the next case check if a match is found. This means if the case matches the expression result, then no need to check the next case as already work is done.
C Program to demonstrate Switch Expression
#include<stdio.h>
int main() {
int number = 20;
switch (number) {
case 10:
printf("Matched with case 10");
break;
case 20:
printf("Matched with case 20");
break;
case 30:
printf("Matched with case 30");
break;
default:
printf("No match found");
}
return 0;
}
Output
Matched with case 20