Search code examples
cunions

Assigning two values with an union variable


The variable a is assigned by value 10 and the variable b is assigned by 20 with the union variable v. Then it gives the output of a is 20 instead of 10. I don't get it.

#include<stdio.h>  
int main()  
{
   union var
   {
       int a, b;
   };
   union var v;
   v.a=10;
   v.b=20;
   printf("%d\n", v.a);
   return 0;
}  

I executed the program and I got 20 as output.


Solution

  • union overlays all the listed members on top of each other (although some may extend farther than the overlapping initial sections), so assigning to either .a or .b is writing over the same part of memory. With that in mind, the output should make sense.

    You probably were thinking of struct's behavior if you were expecting an output of 10.

    In really twisted scenarios, it's possible to have parts of different values stored in a union simultaneously, but generally the partially overwritten values will be assumed corrupt. For example, this:

    union {
        char a;
        struct { char ba; char bb; } b;
    } s;
    

    can store s.a and s.b.bb at the same time, but since s.a overlaps s.b.ba, assigning to s.a stomps on s.b.ba, and by implication all of s.b is no longer trustworthy.

    Often unions intended to store different types will be embedded in a struct whose first member records which union member is in use:

    struct {
        int type;
        union {
           char ch;
           int n;
        } datum;
    } atom;
    

    Here, type probably would contain an enumerated value to indicate whether datum.ch or datum.n was in use in the atom.