c-union

Learn C - C tutorial - C union - C examples - C programs

C Union - Definition and Usage

  • Union and structure in C - Programming are same in concepts, except allocating memory for their members.
  • Structure allocates storage space for all its members separately.
  • Whereas, Union allocates one common storage space for all its members.
  • We can access only one member of union at a time.
  • We can’t access all member values at the same time in union.
  • But, structure can access all member values at the same time.
  • This is because, Union allocates one common storage space for all its members. Whereas Structure allocates storage space for all its members separately.
C Union

C Syntax

union tag_name
{
    data type var_name1;
    data type var_name2;
    data type var_name3;
}; 

Sample - C Code

#include <stdio.h>
#include <conio.h>
{
  union number
   {
     int  n1;
    float n2;
  }; 

   void main()
   union number x;
    clrscr();
    printf("Enter the value of n1: ");
    scanf("%d", &x.n1);
    printf("Value of n1 =%d", x.n1);
    printf("\nEnter the value of n2: ");
    scanf("%f", &x.n2);
    printf("Value of n2 = %f\n",x.n2);
    getch();
} 

C Code - Explanation

code-explanation-union
  1. In this statement we create the union with its union name as “number” where the union contain different data types.
  2. Here in this statement we create a variable for accessing a union element whose union variable name is “x” .
  3. In this statement we get the value for the variable “n1” with its union variable name by printing the value.
  4. In this statement we get the value for the variable “n2” with its union variable name by printing the value.

Sample Output - Programming Examples

code-explanation-union-output
  1. Here in this output we get the integer value for the variable “n1” where its value “24” has been displayed here.
  2. Here in this output we get the float value for the variable “n2” where its value “34.500000” has been displayed here..

View More Quick Examples


Related Searches to c union