Int * vs float * type

Given the following code snippet:

int *iptr;
float *fptr;
float fval;
fval = 0.0;
fptr = &fval;
iptr = fptr;
printf("%d \n", *iptr);
fval = 1.0;
printf("%d \n", *iptr);

Output:

0
1065353216

Why does the first print statement at least roughly match the value associated with * iptr (0.0), but the second print statement doesn't work?

+4
source share
6 answers

When you write printf("%d \n", *iptr);, you are asking to printfinterpret the value that is indicated iptras an integer.

It so happened that the floatversion 0is represented by the same version bits int 0. In particular, all bits 0.

float, 1.0, ( IEEE), int.

Wikipedia , float .

+12

iptr = fptr; undefined.

.

+3

@merlin . , , . undefined. , .

iptr = fptr;

iptr int * fptr float *. fptr to iptr - , , fval. . undefined, . , . , , undefined.

+3

undefined: iptr = fptr;. float int, IEEE754

:

printf("%d", fval);
+2

A floating point number consists of zeros. Any other number is not just a number, but an exponent and a mantissa - of course, not one of them is your number.

+1
source

Floats are stored in the IEEE754 format, in which the value of a number, such as 1.0, is very different from 1 (it is offset to allow negative numbers and numbers). You cannot print float as int and get a result similar to the number assigned to a floating point.

+1
source

Source: https://habr.com/ru/post/1536060/


All Articles