+ 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.
4 Réponses
+ 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/
+ 1
Martin Taylor i have to say, you are so creative 😅
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.