+ 3

Need help in switch in c

This is code: #include<stdio.h> int main() { char inchar = 'A'; switch (inchar) { case 'A' : printf ("choice A ") ; case 'B' : printf ("choice B ") ; case 'C' : case 'D' : case 'E' : default: printf ("No Choice") ; } return 0; } when i compiled answer is choice A choice B No Choice why?? shouldn't answer be choice A

24th Jan 2018, 4:42 AM
Ayush walia
Ayush walia - avatar
5 Answers
+ 5
you have no use of break statement
24th Jan 2018, 3:22 PM
Deepak Gehlot
Deepak Gehlot - avatar
+ 3
It should be: #include<stdio.h> int main() { char inchar = 'A'; switch (inchar) { case 'A' : printf ("choice A ") ; break; case 'B' : printf ("choice B ") ; break; case 'C' : break; case 'D' : break; case 'E' : break; default: printf ("No Choice") ; break; } return 0; }
24th Jan 2018, 4:00 PM
Thinh Re
Thinh Re - avatar
+ 2
Here is my explanation to myself: https://code.sololearn.com/cHpx2r85kn8A/#c And here is how I figured it out, please someone, correct me if I am wrong. In C, when the case is true all cases after that one, are also true or accounted for. I was trying to work out why is the answer for a challenge question 17, this is the code for it: int x switch(x){ case 1: {x+=x;} case 3: {x+=x;} case 5: {x+=x;} default: {x+=5;} } printf("%d", x); I thought it was 11, case 3 and default, right? But when I did this: int x switch(x){ case 1: {x+=x;} case 2: {x+=x;} case 3: {x+=x;} default: {x+=5;} } printf("%d", x); the result was 11 and after this int x switch(x){ case 1: {x+=x;} case 3: {x+=x;} case 5: {x+=x;} case 6: {x+=x;} default: {x+=5;} } printf("%d", x); The result was 29. same can be applied for your switch if you put case 'B' : before case 'A'... And Yes because no breaks are applyed. :)
14th Aug 2020, 12:41 AM
Milena Jovac
Milena Jovac - avatar
+ 1
you forget to use break... in the end of every case write break;
24th Jan 2018, 5:16 AM
jatin verma
jatin verma - avatar