Union in C

05 min read

Union is similar to a structure. In a structure, each member has its own storage location whereas in a union, all the members share the same memory location.

1) The compiler allocates memory large enough to hold the largest variable type in the union.

Declaration syntax:

union student
{
int sno;
char sname[20];
int total;
float avg;
};

Here, the member sname requires the largest number of memory bytes (20). Hence 20  bytes will be allocated for a union variable, of this type.

2) Only one member can be accessed at a time. (ie., the currently active member alone can be accessed).

union item
{
int m;
float x;
char c;
} i;

int main()
{
i.m=370;
i.x=189.57;
i.c='A';
printf("%c",i.c);
printf("%f%d",i.x,i.m);
i.x=50.75;
printf("%f",i.x);
}

Advantages: Union saves storage space.

Disadavantage: There is no way to know which member of the union is currently active, unless the user keep track of it.



POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error