Question

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?

Était-ce utile?

La solution

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.

Autres conseils

The statement iptr = fptr; will invoke undefined behaviour.

There is not much point in speculating about the outcome therefore.

@merlin has explained the output of your code very nicely and clearly. However, there's more to it so I will add it here. Your code violates the strict aliasing rule and invokes undefined behaviour. Strict aliasing rule means different pointer types should not point to the same memory location.

iptr = fptr;

iptr is of type int * and fptr is of type float *. This statement assigns fptr to iptr - a different type - which means both now point to fval. This breaks the strict aliasing rule. This causes undefined behaviour which means unpredictable behaviour. The standard imposes no requirements on the implementation to deal which such cases. In short, you should avoid code which causes undefined behaviour.

Its an undefined behavior: iptr = fptr;. You cannot print a float as an int, floats are stored in IEEE754 format

You need to try this:

printf("%d", fval);

A zero floating point number consists of zeroes. Any other number is not just the number but an exponent and a mantissa - of course neither of them is just your number.

Floats are stored in IEEE754 format, in which the value of a number such as 1.0 is quite different to 1 (it is offset to allow for negative numbers and exponents). You cannot print a float as an int and have the result resemble the number assigned to the float.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top