Enumerated Data Type
Enumeration (enum) in C
📌 Definition
Enumeration (or enum) is a user-defined data type in C.
-
Used to assign names to integral constants
-
Makes programs easier to read and maintain
-
Each symbolic name represents an integer constant
-
Declared using the keyword
enum
📌 General Syntax
Notes:
-
Either tag_name or variables may be omitted
-
Both can also be present
-
But at least one must exist
📌 Default Values of Enum Members
-
Members are assigned integer values automatically
-
First member →
0 -
Second →
1 -
Third →
2 -
And so on…
📌 Example Declaration
OR
📌 Example Program (Default Values)
Output
(Counting starts from 0)
📌 Assigning Explicit Values
We can manually assign integer values to enum members.
✔ Example
Output
👉 Two enum names can share the same value.
📌 Mixed Assignment of Values
-
You may assign values to some members
-
Remaining members automatically get:
✔ Example
Output
📌 Important Rules for Enum
✅ Enum values must be integral constants
✅ Must lie within integer range
✅ Enum constants must be unique within the same scope
❌ Invalid Example
📌 Enum vs Macro
We can also define named constants using macros:
✔ Advantages of enum Over Macros
-
Enums follow scope rules (macros do not)
-
Enum values are automatically assigned
-
Cleaner and easier for related constants
✔ Simpler Using Enum
Comments
Post a Comment