union typedef and enumeration in C : In C programming, managing and organizing data efficiently is crucial for building robust applications. Two essential features that help in this task are union and typedef. While union provides a way to handle multiple data types in a single memory location, typedef simplifies and enhances the readability of code by providing custom names for existing types. The enum in C programming is a powerful feature that improves the readability and maintainability of code by giving names to sets of related constants. Whether you’re working with directions, states, or any other group of predefined values, enum can make your code cleaner, safer, and easier to understand.
Table of Content:
What is union in C Programming Language
A union is a user-defined data type in C that allows storing different data types in the same memory location. Unlike struct, where each member has its own memory location, in a union, all members share the same memory space. This feature is useful when working with variables that will never be used simultaneously, thus saving memory.
Syntax of union
union union_name {
data_type1 member1;
data_type2 member2;
…
};
union_name is the name of the union.
data_type1, data_type2, … represent the data types of the members.
Example of union in C Programming Language
Example: Defining a Union
#include<stdio.h> // preprocessor directive
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
data.i = 10;
printf("data.i: %d\n", data.i);
data.f = 220.5;
printf("data.f: %f\n", data.f);
// Overwrites previous values in memory
strcpy(data.str, "C Programming");
printf("data.str: %s\n", data.str);
return 0;
}
Explanation:
Shared Memory: In the above example, the union Data has three members: i, f, and str. When one member is assigned a value, it overwrites the memory of the others. For instance, assigning str will overwrite i and f because they all share the same memory.
Memory Optimization: A union is ideal when only one member is required at any given time, thus reducing memory usage.
Advantages of union in C Programming Language
Memory Efficiency: Since all members share the same memory, union consumes less space compared to struct.
Versatility: Useful for interpreting the same memory in different ways, such as for creating variants in a programming language.
Disadvantages of union in C Programming Language
One Active Member: Only one member can hold a value at a time.
No Simultaneous Access: Members cannot be used simultaneously, unlike in struct.
typedef in C Programming Language
The typedef keyword in C is used to give a new name (alias) to an existing data type. This enhances code readability and makes the code easier to maintain, especially in complex declarations involving pointers, structures, and arrays.
Syntax of typedef
typedef existing_type new_type_name;
existing_type is the original data type.
new_type_name is the alias or the new name given to the existing type.
Example: Using typedef
#include<stdio.h>
typedef unsigned int uint;
int main() {
uint num = 100;
printf(“Value of num: %u\n”, num);
return 0;
}
Explanation:
In this example, typedef gives the alias uint to the unsigned int type. This allows us to use uint instead of repeatedly writing unsigned int in the code.
typedef with struct
One of the common uses of typedef is with struct. Without typedef, we need to repeat the struct keyword every time we declare a variable.
#include<stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p1;
p1.x = 10;
p1.y = 20;
printf("Point p1: (%d, %d)\n", p1.x, p1.y);
return 0;
}
With typedef, we can simplify the code by eliminating the need for the struct keyword during variable declarations.
#include<stdio.h> // preprocessor directive
typedef struct Point {
int x;
int y;
} Point;
int main() {
Point p1;
p1.x = 10;
p1.y = 20;
printf("Point p1: (%d, %d)\n", p1.x, p1.y);
return 0;
}
Advantages of typedef in C Programming Language
Code Simplification: It makes complex data type declarations easier to understand and maintain.
Code Flexibility: It allows changing the underlying data type without modifying the rest of the code. This can be particularly useful when changing platform-specific types like int to long or using different pointer types.
Disadvantages of typedef in C Programming Language
Creating shorter names for data types, especially struct, enum, or pointers.
Defining platform-independent types, such as size_t, uint32_t, etc., in libraries or cross-platform code.
Combining typedef and union in C Programming Language
In some scenarios, combining typedef with union can improve code readability, particularly when dealing with complex data structures.
Example: typedef with union
#include<stdio.h> // preprocessor directives
typedef union {
int i;
float f;
char str[20];
} Data;
int main() {
Data data;
data.i = 50;
printf(“data.i: %d\n”, data.i);
data.f = 21.9;
printf("data.f: %f\n", data.f);
return 0;
}
In this example, we used typedef to create an alias Data for the union. This simplifies the declaration process and improves code readability.
Summary
Both union and typedef are powerful features in C programming that help optimize memory usage and improve code readability. Union allows multiple types to share the same memory location, making it useful for scenarios where memory is limited. On the other hand, typedef allows developers to create more intuitive and manageable code by providing aliases for complex types. Together, these features contribute to writing efficient and clean C programs.
What is enumeration in C?
An enum (short for enumeration) in C is a way to define a variable that can hold one of a set of predefined values. Each value is represented by an identifier, which by default is assigned an integer starting from 0. You can also assign specific integer values to each identifier.
Syntax of enum
enum enum_name {
constant1,
constant2,
constant3,
…
};
enum_name: The name of the enumeration.
constant1, constant2, constant3: The named integer constants.
Example of enumeration in C
Example: Defining an enum
#include<stdio.h>
enum Weekday {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
};
int main() {
enum Weekday today;
today = WEDNESDAY;
printf("The value of today is: %d\n", today);
return 0;
}
Explanation:
Here, we define an enum named Weekday with constants SUNDAY through SATURDAY. The constants are automatically assigned integer values starting from 0, so SUNDAY is 0, MONDAY is 1, and so on.
In the main function, we declare a variable today of type enum Weekday and assign it the value WEDNESDAY. Since WEDNESDAY is the fourth constant, it has the value 3, so the output will be:
The value of today is: 3
Assigning Custom Values to an enumeration in C
By default, the values assigned to constants in an enum start at 0 and increase by 1 for each subsequent constant. However, you can explicitly assign specific integer values to any or all constants.
Example: Custom Values in enum
#include<stdio.h>
enum Color {
RED = 1,
GREEN = 3,
BLUE = 5
};
int main() {
enum Color myColor;
myColor = GREEN;
printf("The value of myColor is: %d\n", myColor);
return 0;
}
Explanation:
In this example, we explicitly set the values for RED, GREEN, and BLUE. RED is set to 1, GREEN to 3, and BLUE to 5.
When we assign myColor = GREEN, the output will be:
The value of myColor is: 3
You can assign values selectively. If no value is assigned to a constant, it will take the value of the previous constant plus 1.
Advantages of enumeration in C
- Readability: enum makes code more readable by replacing integer constants with meaningful names.
- Maintainability: You can easily modify the constants in one place without affecting the rest of the code.
- Type Safety: In C, enum types give you some level of type checking, making it less likely to accidentally assign invalid values to a variable.
Example: Readability with enum
Without enum, you might write code like this:
int trafficLight = 1; // 0 = Red, 1 = Green, 2 = Yellow
if (trafficLight == 1) {
printf(“Go!\n”);
}
With enum, this becomes much clearer:
enum TrafficLight { RED, GREEN, YELLOW };
enum TrafficLight light = GREEN;
if (light == GREEN) {
printf(“Go!\n”);
}
In this example, using enum makes it immediately obvious what the variable light represents, enhancing readability.
Using enumeration in Switch Statements in C
One of the common uses of enum is in switch statements, where a variable is checked against different constants. This leads to clean, readable code.
Example: enum with Switch Statement
#include<stdio.h>
enum Direction {
NORTH,
EAST,
SOUTH,
WEST
};
int main() {
enum Direction dir = EAST;
switch (dir) {
case NORTH:
printf("You are heading North.\n");
break;
case EAST:
printf("You are heading East.\n");
break;
case SOUTH:
printf("You are heading South.\n");
break;
case WEST:
printf("You are heading West.\n");
break;
default:
printf("Unknown direction.\n");
}
return 0;
}
Explanation:
We use the enum Direction to define the possible directions: NORTH, EAST, SOUTH, and WEST.
In the switch statement, we check the value of dir and print a message accordingly. Since dir = EAST, the output will be:
You are heading East.
typedef with enumeration in C
Just like with struct, you can use typedef to simplify the use of enum in your program. This reduces the need to repeat the enum keyword every time you declare a variable.
Example: typedef with enum
#include<stdio.h>
typedef enum {
LOW,
MEDIUM,
HIGH
} Priority;
int main() {
Priority taskPriority = HIGH;
if (taskPriority == HIGH) {
printf("This task has high priority!\n");
}
return 0;
}
Explanation:
We use typedef to create an alias Priority for the enum. Now, we can declare a variable of type Priority without using the enum keyword repeatedly.
In this example, taskPriority is assigned the value HIGH, and the program prints:
This task has high priority!
Enum vs. Macro Constants in C
Although enum and #define macro constants can both be used to define named values, enum offers several advantages:
Scope: Enum values are scoped within the enum, whereas macro constants are global.
Debugging: Debuggers often display enum values by their names, making debugging easier compared to macro constants.
Type Safety: Enums provide better type safety compared to macros.
Example: Enum vs. Macro in C
#define RED 0
#define GREEN 1
#define BLUE 2
// vs.
enum Color { RED, GREEN, BLUE };
Summary of enumeration in C
The enum in C programming is a powerful feature that improves the readability and maintainability of code by giving names to sets of related constants. Whether you’re working with directions, states, or any other group of predefined values, enum can make your code cleaner, safer, and easier to understand.

What is a union in C?
How does a union save memory?
Can a union hold values for all members simultaneously?
What is the difference between a union and a struct in C?
When should I use a union instead of a struct?
What is an enum in C programming?
How are values assigned to the members of an enum?
Can we assign custom values to an enum in C?
What is the difference between enum and #define for defining constants?
Can an enum variable hold values other than the predefined constants?
Is enum in C the same as in other programming languages?
How is enum typically used in programs?
Can you use an enum in a switch statement?
What happens if you do not assign a value to one of the members in an enum?
Can you use typedef with enum?
Learn More
Subscribe “JNG ACADEMY” for more learning best content.
Important Links
C Programming Language Lecture-01
C Programming Language Lecture-02
C Programming Language Lecture-03
C Programming Language Lecture-04
C Programming Language Lecture-05
C Programming Language Lecture-06
C Programming Language Youtube Playlist
Thank You So Much, Guys… For Visiting our Website and Youtube.