Union Keyword


In C programming, the 'union' keyword is used to define a user-defined data type called a union.

A union is a special data structure that allows different data types to be stored in the same memory location. Only one member of the union can hold a value at a time.

Here's an example of using the 'union' keyword to define a union:


union Data {
  int number;
  float value;
};

int main() {
  union Data data;
  data.number = 10;
  printf("Number: %d\n", data.number);

  data.value = 3.14;
  printf("Value: %.2f\n", data.value);

  return 0;
}
  

In this example, the 'union' keyword is used to define a union named 'Data' that contains two members: 'number' of type 'int' and 'value' of type 'float'.

Inside the 'main()' function, an instance of the 'Data' union named 'data' is declared.

The union allows you to store either an integer or a float value in the same memory location.

The values are assigned and accessed using the dot operator ('.') based on the desired member type.

Unions are particularly useful when you need to represent different data types using the same memory space.

They are commonly used in situations where memory efficiency is crucial or when you want to save space by sharing memory among different data types.

Loading...

Search