A union stores different data types in the same memory location. The size of the union is the size of its largest member. An enum defines a type containing named integer constants.
C Unions and Enums
Share memory locations across datatypes with unions and define named integer constants.
Key Takeaways: C Unions and Enums
Mastering C Unions and Enums helps you write clean and reliable C code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
C Unions and Enums Code Example
C#include <stdio.h>
union Data {
int i;
float f;
};
int main() {
union Data data;
data.i = 10;
printf("data.i: %d\n", data.i);
data.f = 220.5;
printf("data.f: %.1f\n", data.f);
return 0;
}
Output
data.i: 10 data.f: 220.5
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
Finished this lesson?
Mark it complete to track your progress.
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services