A union can store different data types in the same memory space not simultaneously. - C Data Type

C examples for Data Type:union

Introduction

Here is an example of a union template with a tag:

union myU { 
      int digit; 
      double bigfl; 
      char letter; 
};    

Here is an example of defining three union variables of the myU type:

union myU fit;      // union variable of myU type 
union myU save[10]; // array of 10 union variables 
union myU * pu;     // pointer to a variable of myU type    

You can initialize a union.

You have three choices:

  • You can initialize a union to another union of the same type,
  • You can initialize the first element of a union, or, with C99,
  • You can use a designated initializer:
union myU valA; 
valA.letter = 'R'; 
union myU valB = valA;  // initialize one union to another 
union myU valC = {88};  // initialize digit member of union 
union myU valD = {.bigfl = 118.2};  // designated initializer

Related Tutorials