+ 1
What is a case statement in C programming?
2 Answers
+ 3
C â Switch Case Statement
Syntax:
switch (variable or an integer expression) { case constant: //C Statements ; case constant: //C Statements ; default: //C Statements ; }
Flow Diagram of Switch Case
Example of Switch Case in C
#include <stdio.h> int main() { int num=2; switch(num+2) { case 1: printf("Case1: Value is: %d", num); case 2: printf("Case1: Value is: %d", num); case 3: printf("Case1: Value is: %d", num); default: printf("Default: Value is: %d", num); } return 0; }
Output:
Default: value is: 2
Explanation:Â In switch I gave an expression, you can give variable also. I gave num+2, where num value is 2 and after addition the expression resulted 4. Since there is no case defined with value 4 the default case is executed.
Twist in a story â Introducing Break statement
Before we discuss more about break statement, guess the output of this C program.
#include <stdio.h> int main() { int i=2; switch (i) { case 1: printf("Case1 "); case 2: printf("Case2 "); case 3: printf("Case3 "); case 4: printf("Case4 "); default: printf("Default "); } return 0; }
Output:
Case2 Case3 Case4 Default
I passed a variable to switch, the value of the variable is 2 so the control jumped to the case 2, However there are no such statements in the above program which could break the flow after the execution of case 2. Thatâs the reason after case 2, all the subsequent cases and default statements got executed.
How to avoid this situation?
We can use break statement to break the flow of control after every case block.
âââ :)
https://beginnersbook.com/2014/01/switch-case-statements-in-c/
0
thanks bro