Last updated on July 27, 2020
The switch statement is a multi-directional statement used to handle decisions. It works almost exactly like theif-else statement. The difference is that the switch statement produces a more readable code in comparison to if-else statement. Also, sometimes it executes faster than the if-else counterpart. The syntax of switch statement is as follows:
Syntax:
1 2 3 4 5 6 7 8 9101112131415161718 | switch(expression){caseconstant1:statement1;statement2;...caseconstant2:statement3;statement4;...caseconstant3:statement5;statement6;...default:statement7;...} |
Theexpression in the switch statement can be any valid expression which yields an integral value. Theexpression can also be a character constant ( because all characters are eventually converted to an integer before any operation ) but it can’t be floating point or string.
constant1,constant2 and so on following thecase keywords must be of integer type (likeint,long int etc ) or character type. It can also be an expression which yields an integer value. Eachcase statement must have only one constant. Multiple constants in the singlecase statement are not allowed. Further, all case constants must be unique.
After each case constant, we can have any number of statements or no statement at all. If there are multiple statements then you don't need to enclose them with the braces ({}).
Here are some valid switch expressions and case constants.
123 | inta,b,c;float,f1,f2;charch1,ch2; |
123456 | switch(a)switch(a+b+c)switch(ch1+a)switch(a<b)switch(my_func(12))switch('a') |
123 | switch(a+12.2)// expression must yield an integer value not double or float.switch(f1)// same reason as above.switch("string")// string is not allowed. |
1234 | case1case1+2case'a'case'a'<'b' |
12345 | case"string"// string constants are not allowedcase1.2// floating point constants are not allowedcasea// variables are not allowedcasea+b// variables are not allowedcase1,2,3// each case must contain only one constant</pre> |
How it works:
First of all, the expression following the switch is evaluated, then the value of this expression is compared against every case one by one. If the value of the expression matches with any case constant then the statements under that case are executed. If the value of the expression does not match any case constants then the statements under default are executed. The default statement is optional if omitted and no case matches then no action takes place.
Let's now see the switch statement in action.
The following program asks the user to enter a number and prints the message accordingly:
1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930 | #include<stdio.h>intmain(){inti,sum;printf("Enter a number: ");scanf("%d",&i);switch(i){case1:printf("Number is one\n");case2:printf("Number is two\n");case3:printf("Number is three\n");case4:printf("Number is four\n");default:printf("something else\n");}// return 0 to operating systemreturn0;} |
Expected Output:
12345 | Enter a number: 2Number is twoNumber is threeNumber is foursomething else |
How it works:
Let’s say user entered2. Then the switch expression is evaluated, the value of the expression is compared against every case. When a match is found, all statements under that case are executed. In our case, the value of the 2nd case matches the value of the expression (i.e 2). As a result, all the statements under that case are executed. The important thing to note is that that statements undercase 3,case 4 anddefault are also executed. This is known as falling through cases and this is how the switch statement works by default.
Most of the time, we don't want the control to fall through the statements of all the cases, instead, we want to just execute the statements under the matching case and break out of the switch statement. We can achieve this using thebreak statement. When thebreak statement is countered inside the switch statement, the program control immediately breaks out of the switch and resumes execution with the statement following it.
Let's rewrite our previous program, but this time, only the statements of the matching case will be executed.
1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930 | #include<stdio.h>intmain(){inti,sum;printf("Enter a number:\n");scanf("%d",&i);switch(i){case1:printf("Number is one\n");break;case2:printf("Number is two\n");break;case3:printf("Number is three\n");break;case4:printf("Number is four\n");break;default:printf("something else\n");}// return 0 to operating systemreturn0;} |
Expected Output:
1st run:
123 | Enter a number:3Number is three |
2nd run:
123 | Enter a number:11something else |
1 2 3 4 5 6 7 8 910111213141516171819202122232425262728293031323334353637 | #include<stdio.h>intmain(){inta=1,b=2;charop;printf("Enter first number: ");scanf("%d",&a);printf("Enter second number: ");scanf("%d",&b);printf("Enter operation: ");scanf(" %c",&op);switch(op){case'+':printf("%d + %d = %d",a,b,a+b);break;case'-':printf("%d - %d = %d",a,b,a-b);break;case'*':printf("%d * %d = %d",a,b,a*b);break;case'/':printf("%d / %d = %d",a,b,a/b);break;default:printf("Invalid Operation\n");}// return 0 to operating systemreturn0;} |
Expected Output:
1st run:
1234 | Enter first number: 34Enter second number: 13Enter operation: *34 * 13 = 442 |
2nd run:
1234 | Enter first number: 441Enter second number: 981Enter operation: +441 + 981 = 1422 |
How it works:
In line 5, two variablesa andb of typeint are declared. These variables will store the numbers entered by the user.
In line 6, a variableop of typechar is declared. This will store the sign of the operator entered by the user.
In lines 8-9, the program asks the user to enter the first number. The entered number is stored in the variablea.
In lines 11-12, the program again asks the user to enter the second number. The entered number is stored in the variableb.
In lines 14-15, the program asks the user to enter the symbol of the operation he/she wants to perform on the two numbers. The entered symbol is assigned to the variableop.
In lines 17-33, we have a switch statement. The variableop is used as an expression in the switch statement. The value ofop is then compared against every case one by one. If the value of theop matches any case then the statements in that case are executed and thebreak statement causes the program control to break out of the switch statement.