C Unions

C Tutorial

1. What is a C Unions?

  • C Unions is similar to a structure (struct) in C, but all members share the same memory location.

  • Only one member can store a value at a time.

  • Useful for memory-efficient programs when you need alternative data types in the same location.

Syntax:



2. Example: Basic Union


 

Output:

data.i = 10
data.f = 220.50
data.str = Hello
data.i = <garbage>
data.f = <garbage>

Only one member’s value is valid at a time.


3. Size of a Union

  • The size of a union is equal to the size of its largest member.


 

Output:

Size of union = 20 bytes
  • str is the largest member → union size = 20 bytes.


4. Union with Struct Example


 

Output:

Name: Alice
Integer: 100
Float: 220.50

5. Key Points About Unions

  1. All members share the same memory location.

  2. Only one member can hold a value at a time.

  3. Memory size = size of largest member.

  4. Useful for memory-efficient storage and type alternatives.

  5. Access union members with dot . (normal) or arrow -> (pointer).

  6. Often used in embedded systems, protocol implementations, and type conversion.

You may also like...