1

I could not understand how Union is printing data.

#include<stdio.h>
int main(){
 union Values{
  int a;
  char b;
  int c;
 };
union Values val;
val.a = 1;
val.b= 2 ;
val.c = 300;
printf("%d,%d,%d",val.a,val.b,val.c);
return 0;
}

I getting output to 300,44,300

Anis Mulla
  • 75
  • 7
  • 1
    An `union` can't hold all three of those at the same time. If you want to store all of those things, did you intend to make a `struct` instead? Change the two `union` in your code to `struct` and see if you like that result better. – Blaze Jun 26 '19 at 09:41
  • 2
    Me thinks you need to read this, possible duplicate, https://stackoverflow.com/questions/346536/difference-between-a-structure-and-a-union – StoryTeller - Unslander Monica Jun 26 '19 at 09:43
  • 1
    It's not clear what you're confused about. Did you expect `val.a`, `val.b`, and `val.c` to all retain their values? That's pretty much the opposite of what a union is for. If you want `val.a`, `val.b`, and `val.c` to all retain their values, what you want is a `struct`. The whole point of a union is that it's just big enough to hold *one* of the values; they all overlap each other in memory. The only value you can fetch from a union is the last value you stored in it. Whenever you store a new value in a union, it overwrites all or part of all the others. – Steve Summit Jun 26 '19 at 10:08
  • A union between an `int` and an `int` doesn't make sense. – Lundin Jun 26 '19 at 12:00

1 Answers1

2

Values is union type of size int, which is maximum size of its members.

Considering the size of int is 4 bytes, then.

                   +------------+-------------+-------------+-------------+
union Values val = |  1st byte  | 2nd byte    | 3rd byte    |  4th byte   |
                   +------------+-------------+-------------+-------------+

When you store

val.c = 300; //binary 0b100101100

val will become

        +------------+-------------+-------------+-------------+
  val = | 0010 1100  | 0000 0001   |             |             |
        +------------+-------------+-------------+-------------+

When you access val.b you will read the only one byte which contains 0010 1100. And decimal equivalent of 0010 1100 is 44.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44