This post demonstrates not well-known features of switch statement in any programming language that makes use of switch-case structure.
Please share your thoughts on this post in the comments section.
Switch Statement -
When the program encounters the situation to choose a particular statement among many statements, then the programmer decides to choose one block of statement depending on the problem statement.This can be achieved with alternatives like
if
, if-else
, nested if-else
. But this makes no program readability and makes programming logic complex. So, this type of problem can be handled in C programming using switch statement.
Syntax -
switch(expression){ case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s); }
Flowchart Representation -
Note – Consider every code block contains thebreak
statement except thedefault
code block at the end.
break
statement is optional.
break
statement breaks the execution and exits the switch once the matched case statements are executed.
Not Well-Known Features -
A switch statement’s case labels can occur inside
- if-else statements
- loops (for, while)
Sample Code -
#include <stdio.h> #include <stdlib.h> int main() { int a,b; a=1; b=1; switch(a) { case 1: printf("Hello\n"); if(b==2) { case 2: printf("Printing the case statement from if\n"); } else case 3: { for(b=1;b<=10;b++) { case 5: printf("Printing the case statement from for loop\n"); } } break; case 4: printf("World\n"); break; } return 0;
Output -
Hello Printing the case statement from for loop Printing the case statement from for loop Printing the case statement from for loop Printing the case statement from for loop Printing the case statement from for loop Printing the case statement from for loop Printing the case statement from for loop Printing the case statement from for loop Printing the case statement from for loop Printing the case statement from for loop
Summary -
It is 100% allowed to includeif-else
andloops
inside the switch statement.
Please share your thoughts on this post in the comments section.
Wow! honestly, I have years programming C and never knew about this.
ReplyDeleteWhich compiler are you using? By my gcc 4.1.2 it is 10 "loop" print instead of "if", so maybe your result screenshot is wrong?
ReplyDeleteIn other words, some statement in a certain condition takes no effect, like in this case "case 2, 3, 5" are all takes no effect as they are being fall through by "case 1" with no break.
DeleteResult screen is updated.
DeleteThe diagram is incorrect as it implies that the flow automatically goes to the end after executing one of the branches. Without the optional break statement, it falls through to the next branch so this should be indicated in the flow diagram.
ReplyDeleteThanks for your comment. Added a note under flow diagram.
ReplyDelete