Without a break statement, the code at the end of one case will fall through into the code of the next case.
So, when x
reaches the value 6.1, since x*x
is still less than 50, you hit case 6
, and with no break statement, you also enter the case 5
and case 4
code. So, the value 5.1 (the result of decrementing x
) is printed 3 times.
This is a good opportunity to stress that you should compile your code with all warnings enabled. With gcc -W -Wall
, your program will generate the following warnings:
.code.tio.c: In function ‘main’:
.code.tio.c:12:17: warning: this statement may fall through [-Wimplicit-fallthrough=]
printf("case 6, x= %f\n ", x);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.code.tio.c:14:13: note: here
case 5:
^~~~
.code.tio.c:15:17: warning: this statement may fall through [-Wimplicit-fallthrough=]
printf("case 5, x=%f\n ", x);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~
.code.tio.c:17:13: note: here
case 4:
^~~~
If your code is intentionally wanting to fall-through to the next case, gcc
will honor a comment annotating that intent. The warning will then not be emitted.
switch ((int) x) {
case 6:
x--;
printf("case 6, x= %f\n ", x);
// FALLTHROUGH
case 5:
printf("case 5, x=%f\n ", x);
// FALLTHROUGH
case 4:
printf("case 4, x=%f\n ", x);
break;
default:
printf("something else, x=%f\n ", x);