Introduction
C provides several useful features for creating and organizing custom data types. A union allows different members to share the same memory location, an enumeration (enum) lets you create meaningful names for integer constants, and typedef gives an existing data type a simpler or more readable name. In this chapter, you will practice all three concepts through simple examples involving students, employees, menus, days, status values, and real-world data. Unions Enumerations and typedef in C practice questions with solutions to help you understand the concepts.
Q1. Create and Display a Union
Problem Statement
Create a union named Data containing an integer, a float, and a character. Store and display an integer value.
C Program
#include <stdio.h>
union Data
{
int number;
float price;
char letter;
};
int main()
{
union Data data;
data.number = 100;
printf("Number = %d", data.number);
return 0;
}
Sample Output
Number = 100
Explanation
We create a union:
union Data
{
int number;
float price;
char letter;
};
A union can contain multiple members, but all members share the same memory location.
We store:
data.number = 100;
and then display:
printf("%d", data.number);
At this point, number contains the value we stored.
Concepts Covered
union- Union members
- Union variable
- Accessing union members
Q2. Understand Shared Memory in a Union
Problem Statement
Create a union containing an integer and a float. Store values in both members one after another and observe the result.
C Program
#include <stdio.h>
union Data
{
int number;
float value;
};
int main()
{
union Data data;
data.number = 100;
printf("Number = %d\n", data.number);
data.value = 25.5;
printf("Value = %.2f\n", data.value);
printf("Number after storing float = %d", data.number);
return 0;
}
Sample Output
The final integer value is implementation-dependent because the same memory is being interpreted as different data types. A typical output may look like:
Number = 100
Value = 25.50
Number after storing float = 1103626240
Explanation
Initially:
data.number = 100;
The union’s shared memory contains the representation of 100 as an integer.
Then:
data.value = 25.5;
uses the same memory location to store a floating-point value.
Therefore, you should not expect data.number to still represent the original 100.
The important idea is:
Union
┌───────────────┐
│ Shared Memory │
└───────────────┘
↑ ↑
int float
Only the member whose value was most recently stored should normally be read.
Concepts Covered
- Shared memory
- Union members
- Memory representation
- Union behavior
Q3. Find the Size of a Union
Problem Statement
Create a union containing an integer, float, and character array. Display the size of the union using sizeof().
C Program
#include <stdio.h>
union Data
{
int number;
float price;
char name[20];
};
int main()
{
union Data data;
printf("Size of union = %zu bytes", sizeof(data));
return 0;
}
Sample Output
The exact size depends on the C implementation, but it will be large enough to hold the largest member, subject to alignment requirements.
For example:
Size of union = 20 bytes
Explanation
The largest member is:
char name[20];
A union must have enough storage for its largest member.
Unlike a structure, union members do not generally have separate storage.
For example:
Structure:
int → separate memory
float → separate memory
char[] → separate memory
Union:
int
float → same shared memory
char[]
The exact size can also be affected by alignment requirements.
Concepts Covered
sizeof()- Union memory
- Largest union member
- Memory allocation
Q4. Create an Enum for Days of the Week
Problem Statement
Create an enumeration for the seven days of the week and display the value of a selected day.
C Program
#include <stdio.h>
enum Day
{
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};
int main()
{
enum Day today;
today = FRIDAY;
printf("Day value = %d", today);
return 0;
}
Sample Output
Day value = 4
Explanation
By default, enumeration values start from 0.
Therefore:
MONDAY → 0
TUESDAY → 1
WEDNESDAY → 2
THURSDAY → 3
FRIDAY → 4
SATURDAY → 5
SUNDAY → 6
When we write:
today = FRIDAY;
the value stored in today is 4.
The names make the program easier to understand than using unexplained numbers such as 4.
Concepts Covered
enum- Enumeration constants
- Default enum values
printf()
Q5. Create Custom Values Using enum
Problem Statement
Create an enumeration for traffic-light colors with custom integer values and display the selected value.
C Program
#include <stdio.h>
enum TrafficLight
{
RED = 1,
YELLOW = 2,
GREEN = 3
};
int main()
{
enum TrafficLight signal;
signal = GREEN;
printf("Traffic light value = %d", signal);
return 0;
}
Sample Output
Traffic light value = 3
Explanation
Unlike the previous example, we assign our own values:
RED = 1,
YELLOW = 2,
GREEN = 3
Therefore:
RED → 1
YELLOW → 2
GREEN → 3
Now:
signal = GREEN;
stores the enumeration value 3.
Using names such as RED, YELLOW, and GREEN makes the program easier to read.
Concepts Covered
- Custom enum values
- Enumeration constants
enumvariables- Named integer values
Q6. Use enum with switch
Problem Statement
Create an enumeration for days and use a switch statement to display the selected day.
C Program
#include <stdio.h>
enum Day
{
MONDAY = 1,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};
int main()
{
enum Day day;
day = FRIDAY;
switch (day)
{
case MONDAY:
printf("Monday");
break;
case TUESDAY:
printf("Tuesday");
break;
case WEDNESDAY:
printf("Wednesday");
break;
case THURSDAY:
printf("Thursday");
break;
case FRIDAY:
printf("Friday");
break;
case SATURDAY:
printf("Saturday");
break;
case SUNDAY:
printf("Sunday");
break;
}
return 0;
}
Sample Output
Friday
Explanation
The enumeration gives meaningful names to integer values:
MONDAY → 1
TUESDAY → 2
WEDNESDAY → 3
...
We set:
day = FRIDAY;
Then switch checks the value of day.
The matching case is:
case FRIDAY:
printf("Friday");
break;
This combination is useful for menus, states, categories, and other fixed choices.
Concepts Covered
enumswitch- Enumeration constants
break
Q7. Create a typedef for an Integer
Problem Statement
Use typedef to create a new name called Age for the int data type.
C Program
#include <stdio.h>
typedef int Age;
int main()
{
Age studentAge = 15;
printf("Student Age = %d", studentAge);
return 0;
}
Sample Output
Student Age = 15
Explanation
This statement:
typedef int Age;
creates Age as an alias for int.
Now instead of:
int studentAge;
we can write:
Age studentAge;
typedef does not create a completely new integer type. It creates another name for an existing type.
Concepts Covered
typedef- Type aliases
- Integer variables
- Custom type names
Q8. Use typedef with a Structure
Problem Statement
Create a student structure using typedef so that the struct keyword is not required when declaring variables.
C Program
#include <stdio.h>
typedef struct
{
int roll;
char name[50];
float marks;
} Student;
int main()
{
Student student = {101, "Rahul", 88.5};
printf("Roll = %d\n", student.roll);
printf("Name = %s\n", student.name);
printf("Marks = %.2f", student.marks);
return 0;
}
Sample Output
Roll = 101
Name = Rahul
Marks = 88.50
Explanation
Without typedef, we might write:
struct Student student;
With typedef:
Student student;
The definition:
typedef struct
{
int roll;
char name[50];
float marks;
} Student;
creates Student as an alias for that structure type.
This can make structure declarations shorter and easier to read.
Concepts Covered
typedef- Structures
- Type aliases
- Structure initialization
Q9. Use typedef with a Structure Pointer
Problem Statement
Create a student structure using typedef and use a pointer to modify the student’s marks.
C Program
#include <stdio.h>
typedef struct
{
int roll;
char name[50];
float marks;
} Student;
int main()
{
Student student = {101, "Aman", 75.5};
Student *ptr = &student;
printf("Before Update = %.2f\n", ptr->marks);
ptr->marks = 90.0;
printf("After Update = %.2f", ptr->marks);
return 0;
}
Sample Output
Before Update = 75.50
After Update = 90.00
Explanation
Because Student is created using typedef, we can write:
Student student;
and:
Student *ptr;
The pointer stores the address of the structure:
Student *ptr = &student;
The marks are accessed using:
ptr->marks
and modified using:
ptr->marks = 90.0;
Concepts Covered
typedef- Structure pointer
->operator- Modifying structure data
Q10. Combine union, enum, and typedef
Problem Statement
Create a simple product record using typedef, an enum for product type, and a union for product-specific information.
C Program
#include <stdio.h>
typedef enum
{
BOOK = 1,
ELECTRONIC = 2
} ProductType;
typedef union
{
int pages;
float warranty;
} ProductInfo;
typedef struct
{
char name[50];
ProductType type;
ProductInfo info;
} Product;
int main()
{
Product product;
printf("Enter product name: ");
scanf("%49s", product.name);
product.type = BOOK;
product.info.pages = 250;
printf("\nProduct Details\n");
printf("Name = %s\n", product.name);
if (product.type == BOOK)
{
printf("Type = Book\n");
printf("Pages = %d", product.info.pages);
}
else if (product.type == ELECTRONIC)
{
printf("Type = Electronic\n");
printf("Warranty = %.1f years", product.info.warranty);
}
return 0;
}
Sample Output
Enter product name: CProgramming
Product Details
Name = CProgramming
Type = Book
Pages = 250
Explanation
This program combines all three concepts.
First:
typedef enum
{
BOOK = 1,
ELECTRONIC = 2
} ProductType;
creates a convenient name for the enumeration.
Next:
typedef union
{
int pages;
float warranty;
} ProductInfo;
creates a union for product-specific information.
Finally:
typedef struct
{
char name[50];
ProductType type;
ProductInfo info;
} Product;
creates the complete product structure.
The union is useful here because a book needs:
pages
while an electronic product might need:
warranty
Both pieces of information do not need to be stored at the same time.
Concepts Covered
typedefenumunion- Structures
- Nested custom types
- Structure members
switch/conditional logic
Key Takeaways
- A
unionallows multiple members to share the same memory. - A union is useful when only one of several possible data values needs to be stored at a time.
- A union’s size is sufficient for its largest member, subject to alignment requirements.
- An
enumgives meaningful names to integer constants. - Enumeration values start at
0by default unless explicitly assigned. - You can assign custom values to enumeration constants.
enumis useful for fixed choices such as days, colors, status values, and menu options.typedefcreates an alias for an existing data type.typedefis commonly used with structures and enumerations.typedefcan make structure declarations shorter and easier to read.union,enum, andtypedefcan be combined in larger C programs.- These concepts become especially useful when designing organized and memory-conscious C programs.
FAQs
1. What is a union in C?
A union is a user-defined data type whose members share the same memory location. Normally, only one member’s stored value should be treated as active at a time.
2. What is the difference between a structure and a union?
A structure gives its members separate storage, allowing all members to hold values simultaneously. A union shares storage among its members, so storing one member can overwrite the representation of another.
3. What is an enum in C?
An enum is an enumeration type used to create named integer constants.
For example:
enum Color
{
RED,
GREEN,
BLUE
};
4. What is the default value of the first enum constant?
The first enumeration constant has the value 0 by default.
For example:
enum Day
{
MONDAY,
TUESDAY,
WEDNESDAY
};
has:
MONDAY = 0
TUESDAY = 1
WEDNESDAY = 2
5. What is typedef in C?
typedef creates an alias for an existing type.
For example:
typedef int Age;
allows:
Age age = 15;
instead of:
int age = 15;
6. Can typedef be used with structures?
Yes. A common pattern is:
typedef struct
{
int id;
char name[50];
} Student;
Then you can declare:
Student student;
7. Can enum, union, and typedef be used together?
Yes. They can be combined to create organized data types for larger programs. For example, typedef can give a simple name to an enum or union, while a structure can contain those types as members.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
