Please help me in understanding the following C Output:
#include<stdio.h>
int main() {
float x = 4.0;
printf("%f\n",x);
printf("%d\n",x);
int y=x;
printf("%d\n",y);
return 0;
}
Ouput on gcc compiler
4.000000
0
4
As far as i have read when we assign float to an int variable the decimal part of the variable is terminated and then assigned to the int.
Why it is not happening in this case?
floats
are automatically promoted todoubles
when passed as...
parameters (similarly to howchars
andshort ints
are promoted toints
). Whenprintf()
looks at a format specifier (%d
or%f
or whatever), it grabs and interprets the raw data it has received according to the format specifier (asint
ordouble
or whatever) and then prints it.printf("%d\n",x)
is wrong because you are passing adouble
toprintf()
but lie to it that it's going to be anint
.printf()
makes you pay for the lie. It takes 4 bytes (most likely, but not necessarily 4 bytes) from its parameters, which is the size of anint
, it grabs those bytes from where you have previously put 8 bytes (again, most likely, but not necessarily 8 bytes) of thedouble
4.0, of which those 4 bytes happen to be all zeroes and then it interprets them as an integer and prints it. Indeed, powers of 2 in the IEEE-754 double precision format normally have 52 zero bits, or more than 6 8-bit bytes that are zero.Those "most likely, but not necessarily" words mean that the C standard does not mandate a fixed size and range for types and they may vary from compiler to compiler, from OS to OS. These days 4-byte
ints
and 8-bytedoubles
are the most common (if we consider, e.g. the x86 platform).You're not printing
y
, you're printingx
again.As a side note,
printf
can't do conversions. So passing a float when a%d
is expected is undefined behavior.Statement is correct, but to make this conversion you must
cast
variable you wish to convert, not just assign it to another int variable.This causes problems also in the
printf
statement, since you are printing a float variable with int specifier%d
without a cast.Fix you're code like this:
and it will correctly print integer value
4
for variablex
.