I have the following code:
double dtemp = (some value)
printf("\n***Hand washing: cost per kg/item: %.2f, cost: %.2f.\n", 5, dtemp);
It prints out:
***Hand washing: cost per kg/item: 0.00, cost: 0.00.
And when I change the constant 5 into a double variable holding 5, it prints (according to the input):
***Hand washing: cost per kg/item: 5.00, cost: 20.00.
Why would the constant 5 affect the evaluation of the dtemp? I’m using gcc 4.6.2 (MinGW) and tested it also in TCC.
My compiler’s (gcc 4.4.3) warning message explains this:
Since you are passing a different type of value (
int) than specified (double) in the format string, the behavior is undefined due to this mismatchAs you observed, once you adjust this to be consistent you get the output you expect. I.e.,
output:
or
output:
Always a good idea to crank up the warning levels on the compiler and then follow up on all warnings and make deliberate decisions about what can be ignored and what can’t.