0

In the following code

#include<stdio.h>
int main()
{
    union myUnion
    {
        int intVar;
        char charVar;
        float floatVar;
    };
    union myUnion localVar;
    localVar.intVar = 10;
    localVar.charVar = 'A';
    localVar.floatVar = 20.2;
    printf("%d ", localVar.intVar);
    printf("%c ", localVar.charVar);
    printf("%f ", localVar.floatVar);
}

I understand that union can hold only one value at a time. So when I assign char value, int would be overwritten, n then when I assign floatValue, char would be overwritten. So I was expecting some garbage values for int and char variables and 20.200000 for float variable as it was last value to be assigned. But following is the output I'm getting on VS Express as well as gcc

1101109658 Ü 20.200001

unable to understand why float value is changed ?

timrau
  • 22,578
  • 4
  • 51
  • 64
Sagrian
  • 1,048
  • 2
  • 11
  • 29
  • I'd close this as duplicate, if I only could find a decent one. Your question has nothing to do with unions and everything to do with float numbers. Read the already posted Goldberg link and the [C FAQ](http://c-faq.com/fp/index.html). – Lundin Sep 10 '14 at 13:40

1 Answers1

4

This has nothing to do with union, and the float value was not changed.

It simply doesn't have enough bits to represent 20.2 exactly as a binary float. But that's okay, nobody has that many bits.

You should read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

unwind
  • 391,730
  • 64
  • 469
  • 606