I am getting output 0.23
from second printf
. But typecasting gives required output. If I am not using type casting previous value is printed.
Compiler
The problem is a combination of two factors:
The first is that for vararg functions like printf
, the compiler will not do any implicit conversions of the arguments. So the 0
in the argument list is an integer constant (of type int
).
The second factor is the mismatching format specifier. The printf
function doesn't know anything about the arguments being passed, except what is specified in the format string. Mismatching format and argument type leads to undefined behavior. And since the "%f"
specifier make printf
expect a value of type double
, and you have given an int
value, you have such a mismatch.
in
> printf("%f",0);
You ask to print a double but you give an int, this is contradictory
You are not in the case where the generated code makes a double from the int because printf is not int printf(const char *, double);
but int printf ( const char * format, ... );
and the compiler does not look at the format to make the necessary conversions ( but in a lot of cases the compiler warn you )
When prints access to the second argument is does to get a double using 64b and probably your int use only 32b, the behavior is undefined.
(edit, thank you @chqrlie)
I get previous float value when i am printing new value
In your case may be printf retrieves a double value from the MMX registers as opposed to the int value that was passed via the stack or regular registers... which may explain why the same value gets printed twice. But of course as always with undefined behavior, anything else could happen at any time