In the C example this expression 18/4+18%4
will evaluate to an int since all the operands are integer constants but you are specifying that it is a double to printf
and therefore it is will be processed incorrectly. On the other hand if you had used a Floating constant in the division part of the expression for example 18.0/4+18%4
the whole expression would have evaluated to a double. Alternatively you could have used "%d"
in the format specifier as well.
This is also undefined behavior to incorrectly specify the format to printf
and this also demonstrates why building with warnings is important, using gcc -Wall
I receive the following warning(see it live):
warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’
In C++ std::cout's operator<< has an overload for int
and therefore that will be called in this case. We can see this overload an many others are required by the C++ draft standard, in section 27.7.3.1
Class template basic_ostream we find the following operator declaration:
basic_ostream<charT,traits>& operator<<(int n);
For completeness sake, circling back to the undefined behavior, the C99 draft standard in section 7.19.6.1
The fprintf function which printf
's section refers back to for the format string paragraph 9 says:
If a conversion specification is invalid, the behavior is undefined.[...]
"%d"
instead of"%.5f"
. – Foxholeprintf
from C++ so you could have tried it there and seen immediately where the problem was. – Briscoeprintf
invokes undefined behavior. – Lyris%f
isdouble
, in variadic functions floats are promoted to double. – Lyris