+ 1

What is a case statement in C programming?

21st Dec 2017, 3:18 PM
Amish Sharma
Amish Sharma - avatar
2 Antworten
+ 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/
21st Dec 2017, 3:27 PM
James16
James16 - avatar
0
thanks bro
21st Dec 2017, 3:30 PM
Amish Sharma
Amish Sharma - avatar