I want to understand the output of this code, specifically the 2 last lines of the output (lines 4 and 5).
#include <stdio.h>
#include <stdlib.h>
int main()
{
double x = 2.1;
while (x * x <= 50) {
switch ((int) x) {
case 6:
x--;
printf("case 6, x= %f\n ", x);
case 5:
printf("case 5, x=%f\n ", x);
case 4:
printf("case 4, x=%f\n ", x);
break;
default:
printf("something else, x=%f\n ", x);
}
x +=2;
}
return 0;
}
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, sincex*x
is still less than 50, you hitcase 6
, and with no break statement, you also enter thecase 5
andcase 4
code. So, the value 5.1 (the result of decrementingx
) 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: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.