In the last tutorial I told you about the syntax and working of a program using switch keyword. Well in day to day programming we generally don’t use that syntax in C. This is because if we use the earlier method then it will execute all the subsequent statements after the condition turns true.
switch statement in C
So we need a syntax that will execute only a certain set of statements when the condition turns true. So lets checkout the advance modification of switch statement with break keyword.
case constant 1: Statement 1;
case constant 2; Statement 2;
. . . . . .
. . . . . .
default: Statement 3;
Explanation of the above syntax
Well the whole syntax is almost same. But in the above syntax we have added break keyword after the cases. Remember we generally do not use continue keyword with switch.
Working of break keyword in switch statement
As you can see I have given break keyword after every case. Its working in switch case is almost same as in loops. If the compiler encounters break keyword in switch then it will take the control to the outside of switch block.
|Flowchart of switch statement in C – Image Source|
The perfect way to understand it is through a program.
case 1: printf("Hey its 1");
case 10: printf("Hey its 10");
case 7: printf("Hey its 7");
default: printf("Hey its default");
- In the beginning of the program I have declared an integer variable with value 10.
- After that I have written switch keyword with integer expression i. It means the compiler will check the value of i (which is 10) with all the cases.
- In the first case I have written integer constant ‘1’ which turns false. So compiler will skip that case.
- In the second case I have written integer constant ‘10’ which turns true. So compiler will execute the statements under that case.
- Now just after the printf() function I have written a break keyword. So it will take the control of the program outside the switch block.
Points to remember
- You can also write multiple statements under each case to execute them. And you will not need to give separate braces for them, as the switch statement executes all statements once the condition turns true.
- Remember default keyword is optional. Its completely depend on us whether we want it or not in our program.
- The order of cases and default in the switch block do no matter. You can write them in any order but you must take care of proper use of break after each case.