0

I want to compare the real value in memory between float c and float d.

So I use the code printf("%x %x\n", d, c);, but the result is wrong.

I only use two unsigned int pointers f, g, and point to the c and d. Printing the value byprintf("%x %x\n", *f, *g);, the result is right.

My total code is:

#include<iostream>
#include<cstdio>
using namespace std;

int main()
{
    float a = 0.1f, b = 0.2f, c = 0.3f;
    float d = a + b;
    unsigned int* f = (unsigned int*)&c, * g = (unsigned int*)&d;
    printf("%x %x\n", d, c);
    printf("%x %x\n", *f, *g);
    return 0;
}

The output is:

40000000 3fd33333
3e99999a 3e99999a

The size of float and unsigned int both are 4 bytes, why printf function doesn't handle the float value as an unsigned int value

I want to know what causes the different output

YD Zhou
  • 317
  • 2
  • 8
  • 1
    floats are promoted to doubles while passing them as function arguments. You print garbage. – 273K Jan 13 '22 at 05:47
  • In that case use a `union` to avoid type-punning a pointer, e.g. `union float2hex { float f; unsigned h; } f2h = { .f = c; }` and now just `printf ("float: %f hex: %x\n", c, u2f.h);` – David C. Rankin Jan 13 '22 at 05:48
  • See answer to [Aliasing through unions](https://stackoverflow.com/a/55255921/3422102) – David C. Rankin Jan 13 '22 at 05:52
  • @DavidC.Rankin Does this count for `c++` as well? https://stackoverflow.com/a/25672839/1294207 I don't think it does. – Fantastic Mr Fox Jan 13 '22 at 05:55
  • Yes, the only difference is C++ unions have constructors and destruction (which you won't need to make use of here) so the defaults will be fine. (the only discussion in the linked question has to do with how optimizations in C++ "may" be affected) Recall `printf()` is C to begin with. Nothing in your code is C++ except `using namespace std;` and the header names (and `iostream` isn't used or needed). But see also [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/364696) – David C. Rankin Jan 13 '22 at 06:01

0 Answers0