David Smith
David Smith

Reputation: 187

int * vs float * type

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?

Upvotes: 4

Views: 399

Answers (6)

ajay
ajay

Reputation: 9680

@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.

Upvotes: 3

merlin2011
merlin2011

Reputation: 75585

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.

Upvotes: 12

Bathsheba
Bathsheba

Reputation: 234785

The statement iptr = fptr; will invoke undefined behaviour.

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

Upvotes: 3

Rahul Tripathi
Rahul Tripathi

Reputation: 172518

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);

Upvotes: 2

ntremble
ntremble

Reputation: 71

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.

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318568

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.

Upvotes: 1

Related Questions