+ 1

(C) 's switch is behaving unpredictable. Can anyone Give me reason for this?

#include <stdio.h> int main() { int s = 1; switch (s){ case 1 : printf("1"); case 2 : printf("2"); case 3 : printf("3"); } return 0; } // copy it on your editor, you'll see its Printing "123". // i dont understand why?? as, case 2 and case 3 isn't true.

15th Jan 2021, 12:47 AM
BlackShadow334
BlackShadow334 - avatar
4 Answers
+ 10
This is due to fallthrough. In C, C++, Java, and a few other languages if the keyword break isn't used at the end of a case then the code will fallthrough to the next case and run its code as well. This will continue until a break statement or the end of the switch is reached. https://www.sololearn.com/learning/2924/
15th Jan 2021, 12:58 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Martin Taylor i have to say, you are so creative 😅
15th Jan 2021, 10:46 AM
BlackShadow334
BlackShadow334 - avatar
0
here in "case 2", 2 is referring to s, and s is actually 1. similarly, in "case 3", 3 is referring to s, and s is actually 1. then why its printing "123", i didn't use break, so what?? case 2 and case 3 isn't true after all.
15th Jan 2021, 12:48 AM
BlackShadow334
BlackShadow334 - avatar