Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is enumerated data type in C language?
An enumerated data type in C is a user-defined data type that allows programmers to create variables with a restricted set of named values. It provides a way to assign names to integer constants, making code more readable and maintainable.
The keyword is enum.
Syntax
enum tagname {
identifier1, identifier2, ..., identifier_n
};
Basic Example
Here's how to declare an enumeration for days of the week −
enum week {
mon, tue, wed, thu, fri, sat, sun
};
By default, identifier values are unsigned integers starting from 0. So mon refers to 0, tue refers to 1, and so on.
Example: Default Values
The following program demonstrates how enum values are assigned by default −
#include <stdio.h>
int main() {
enum week {mon, tue, wed, thu, fri, sat, sun};
printf("Monday = %d<br>", mon);
printf("Thursday = %d<br>", thu);
printf("Sunday = %d<br>", sun);
return 0;
}
Monday = 0 Thursday = 3 Sunday = 6
Example: Custom Initial Values
You can assign custom initial values to enum identifiers. Subsequent values increment from the assigned value −
#include <stdio.h>
int main() {
enum week {mon=1, tue, wed, thu, fri, sat, sun};
printf("Monday = %d<br>", mon);
printf("Thursday = %d<br>", thu);
printf("Sunday = %d<br>", sun);
return 0;
}
Monday = 1 Thursday = 4 Sunday = 7
Key Points
- Enum values are compile-time constants
- Multiple enum constants can have the same value if explicitly assigned
- Enums improve code readability by replacing magic numbers with meaningful names
- Enum variables can be used in switch statements and comparisons
Conclusion
Enumerated data types in C provide a clean way to define named constants, making code more readable and less error-prone. They are particularly useful for representing fixed sets of related values like days, months, or status codes.
