Unions and Enumerations

📘 C 👁 29 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

A union is a user-defined data type in which all members share the same memory location.


Difference Between Structure and Union

  • Structure allocates separate memory for each member

  • Union allocates memory equal to the largest member only


Declaration of Union

union union_name { data_type member1; data_type member2; };

Example of Union

union data { int i; float f; char c; };

Declaring Union Variables

union data d;

Accessing Union Members

  • Use dot (.) operator

d.i = 10;

Example Program (Union)

#include union data { int i; float f; char c; }; int main() { union data d; d.i = 10; printf("i = %d\n", d.i); d.f = 5.5; printf("f = %.2f\n", d.f); return 0; }

Applications of Union

  • Memory-efficient programming

  • Embedded systems

  • Handling multiple data types in same memory


Enumerations in C

An enumeration (enum) is a user-defined data type that assigns names to integer constants.


Declaration of Enumeration

enum enum_name { constant1, constant2, constant3 };

Example of Enumeration

enum day { MON, TUE, WED, THU, FRI };

Using Enumeration Variables

enum day d; d = MON;

Example Program (Enumeration)

#include enum day {SUN, MON, TUE, WED, THU, FRI, SAT}; int main() { enum day d = MON; printf("%d", d); return 0; }

Advantages of Enumeration

  • Improves code readability

  • Reduces use of numeric constants

  • Easy maintenance


Summary

  • Union shares memory among members

  • Structure vs Union differ in memory allocation

  • Enumeration represents named integer constants

  • Both are user-defined data types


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes