Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 549
David Smith Avatar asked Nov 30 '22 00:11

David Smith


2 Answers

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.

like image 56
merlin2011 Avatar answered Dec 01 '22 12:12

merlin2011


The statement iptr = fptr; will invoke undefined behaviour.

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

like image 44
Bathsheba Avatar answered Dec 01 '22 13:12

Bathsheba