Why type conversion between int and float causes data loss?

Walkbitterwyrm Lightwarg 20 Reputation points
2023-08-25T17:02:39.9933333+00:00

In the following program type conversion of pointers from int to float and from floar to int is done but the output is not correct.

#include <stdio.h>

int main()
{
    int a, *ptr_i, *ptr_xi;
    float f, *ptr_f, *ptr_xf;

    a = 65;
    f = 65.5;

    ptr_i = &a;
    ptr_f = &f;
    ptr_xi = ptr_i;
    ptr_xf = ptr_f;

    ptr_f = (float*) ptr_xi;
    ptr_i = (int*) ptr_xf;
            
    printf("The value of \"ptr_i\" is %d\n", *ptr_i);
    printf("The value of \"ptr_f\" is %f\n", *ptr_f);

    return 0;
}

Output:

The value of "ptr_i" is 1115881472

The value of "ptr_f" is 0.000000

Why the output is different?

Developer technologies C++
Developer technologies Visual Studio Other
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Barry Schwarz 3,746 Reputation points
    2023-08-25T19:53:19.4566667+00:00

    If the alignment requirements of types int and float are not the same, then this program potentially causes undefined behavior.

    If the requirements are the same, then

    1. The value of ptr_i is NOT 1115881472. The value of ptr_i is the address of object f. 1115881472 is the decimal representation of whatever data is in object f when those bits are interpreted as an int.
    2. The value of ptr_f is NOT 0.000000. The value of ptr_f is the address of object a. 0.000000 is the decimal representation of whatever data is in object a when those bits are interpreted as a float.
    3. You printed the values in different formats (one int and one promoted to double). Why would you expect the output to be the same?
    4. You printed different values. Even if you used the same format, the output would be different.
    5. If you want to know how the system arrived at that particular set of output, you need to research how your system stores int and float data.

    You initialized your two primary variables to bit patterns appropriate for their defined types. Why do you think telling printf to interpret those patterns as a different type produces anything meaningful? Did you think that changing the type of the pointer used to access the memory would somehow magically convert the data in memory to match the new pointer?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.