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

enum tag_name {member1, member2, member3, ..., memberN} variable1, variable2, ..., variableN;

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

enum week {Mon, Tue, Wed, Thu, Fri, Sat}; enum week day;

OR

enum week {Mon, Tue, Wed, Thu, Fri, Sat} day;

📌 Example Program (Default Values)

#include <stdio.h> enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday}; int main() { enum day d = thursday; printf("The day number stored in d is %d", d); return 0; }

Output

The day number stored in d is 4

(Counting starts from 0)


📌 Assigning Explicit Values

We can manually assign integer values to enum members.

✔ Example

#include <stdio.h> enum State {Working = 1, Failed = 0, Freezed = 0}; int main() { printf("%d, %d, %d", Working, Failed, Freezed); return 0; }

Output

1, 0, 0

👉 Two enum names can share the same value.


📌 Mixed Assignment of Values

  • You may assign values to some members

  • Remaining members automatically get:

(previous value + 1)

✔ Example

#include <stdio.h> enum day {sunday = 1, monday, tuesday = 5, wednesday, thursday = 10, friday, saturday}; int main() { printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday, thursday, friday, saturday); return 0; }

Output

1 2 5 6 10 11 12

📌 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 state {working, failed}; enum result {failed, passed}; // Error: duplicate name 'failed'

📌 Enum vs Macro

We can also define named constants using macros:

#define Working 0 #define Failed 1 #define Freezed 2

✔ Advantages of enum Over Macros

  1. Enums follow scope rules (macros do not)

  2. Enum values are automatically assigned

  3. Cleaner and easier for related constants

✔ Simpler Using Enum

enum state {Working, Failed, Freezed};

Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays