Given the following snippet of code:
int *iptr;
float *fptr;
float fval;
fval = 0.0;
fptr = &fval;
iptr = fptr;
printf("%d \n", *iptr);
fval = 1.0;
printf("%d \n", *iptr);
The output is:
0
1065353216
Why does the first print statement at least approximately match the value associated with *iptr (0.0), yet the second print statement doesn't?
When you write printf("%d \n", *iptr);
, you are asking printf
to interpret the value pointed to by iptr
as an integer.
It just so happens that float
version of 0
is represented by the same bits of the int
version of 0
. In particular, the bits are all 0
.
However, an arbitrary float, such as 1.0
will have a different bit representation (as defined by IEEE Standards) which will make little sense when interpreted as an int
.
This Wikipedia article explains how a float is represented as bits.
The statement iptr = fptr;
will invoke undefined behaviour.
There is not much point in speculating about the outcome therefore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With