Interview Questions
- What is the use of a Switch statement?
- Can you give an example of a Switch Statement?
- Can a switch case consist of variable values?
- Can a switch be used without default?
- Should default always be at the start of a switch statement?
- What happens when there is no break in a switch case?
- Can Switch be used around a character variable?
What is the use of a Switch statement?
The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly.
Can you give an example of a Switch Statement?
Below is an example of a switch statement:
#include <stdio.h> #include <stdlib.h> int main() { int i = 3; switch(i){ case 0 : printf("DOT BALL"); break; case 1 : printf("SINGLE"); break; case 2 : printf("DOUBLE"); break; case 3 : printf("TRIPLE"); break; default : printf("FOUR OR A SIX"); break; } }
Can a switch case consist of variable values?
No. Below example would get a compilation error. Case with a variable runs will throw a compilation error.
#include <stdio.h> #include <stdlib.h> int main() { int i = 3; int runs = 5; switch(i){ case runs : printf("DOT BALL"); break; default : printf("FOUR OR A SIX"); break; } }
Can a switch be used without default?
Yes. Example program below:
#include <stdio.h> #include <stdlib.h> int main() { int i = 3; switch(i){ case 0 : printf("DOT BALL"); break; case 1 : printf("SINGLE"); break; case 2 : printf("DOUBLE"); break; case 3 : printf("TRIPLE"); break; } }
Should default always be at the start of a switch statement?
No. It can be anywhere in the switch. Example below:
#include <stdio.h> #include <stdlib.h> int main() { int i = 3; int runs = 5; switch(i){ default : printf("FOUR OR A SIX"); break; case 0 : printf("DOT BALL"); break; case 1 : printf("SINGLE"); break; case 2 : printf("DOUBLE"); break; case 3 : printf("TRIPLE"); break; } }
What happens when there is no break in a switch case?
Fall through happens. And all statements until the next break or until the end of switch is reached are executed. Example program below : All the printf statements from case 2 are executed.
#include <stdio.h> #include <stdlib.h> int main() { int i = 2; int runs = 5; switch(i){ case 0 : printf("DOT BALL"); case 1 : printf("SINGLE"); case 2 : printf("DOUBLE"); case 3 : printf("TRIPLE"); default : printf("FOUR OR A SIX"); } }
Can Switch be used around a character variable?
Yes. Switch can be done around int, long, short and also a char.