Home > Enterprise >  Unions and values stored
Unions and values stored

Time:10-28

I know that a union allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Consider this program:

    #include <stdio.h>

    union integer {

         short s;
         int i;
         long l;
    };

    int main() {

         union integer I;

         scanf("%hi", &I.s);
         scanf("%d", &I.i);
         scanf("%ld", &I.l);

         printf("%hi - %d - %ld ", I.s, I.i, I.l );
    }

Suppose we enter the values 11, 55, 13 the program will give as output

13 - 13 - 13, no problem here. However, if i were to create three different variables of type struct integer

    #include <stdio.h>

    union integer {

         short s;
         int i;
         long l;
    };

    int main() {

         union integer S;
         union integer I;
         union integer L;

         scanf("%hi", &S.s);
         scanf("%d", &I.i);
         scanf("%ld", &L.l);

         printf("%hi - %d - %ld ", S.s, I.i, L.l );
    
    }

than all the values will be preserved. How come? By using three variables am i actually using three unions, each holding just one value?

CodePudding user response:

The union members s, i and l of the same variable share the same memory. Reading a different member than you have written last is undefined behavior.

If you define 3 variables of the same union type it is not much different from defining 3 variables of type int. Every variable has its own memory, and every variable can hold only one of the union members.

CodePudding user response:

What output do you expect from this code? Three different values or the same one?

    #include <stdio.h>

    int main() {

         short S;
         int I;
         long L;

         scanf("%hi", &S);
         scanf("%d", &I);
         scanf("%ld", &L);

         printf("%hi - %d - %ld ", S, I, L );
    
    }

You are declaring three separate variables, even if they are unions, all of them have their storage.

  • Related