C Enums

C Enums (Enumerations): Making Code Readable

An enum (enumeration) is a user-defined data type in C that consists of integral constants. Enums are primarily used to assign names to integer constants, making a program easier to read, maintain, and debug.

Instead of using raw numbers (like 0 for Monday, 1 for Tuesday), you can use descriptive names!


1. Defining and Using an Enum

By default, the first item in an enum has the value 0, the second has 1, and so on.

Basic Enum Example:

#include <stdio.h>

// Define the enum enum Weekday { MONDAY, // 0 TUESDAY, // 1 WEDNESDAY, // 2 THURSDAY, // 3 FRIDAY, // 4 SATURDAY, // 5 SUNDAY // 6 };

int main() { // Create an enum variable enum Weekday today = WEDNESDAY; printf("Day number: %d\n", today); // Outputs 2 return 0; }


2. Changing Default Values

You are not forced to start at 0. You can explicitly assign integer values to enum constants. Unassigned items will automatically increment from the previous item's value.

Custom Enum Values:

#include <stdio.h>

enum Status { SUCCESS = 200, NOT_FOUND = 404, SERVER_ERROR = 500, UNKNOWN_ERROR // Automatically becomes 501 };

int main() { enum Status currentStatus = UNKNOWN_ERROR; printf("Status Code: %d\n", currentStatus); // Outputs 501 return 0; }


Exercise

?

What is the default integer value of the first item in a C enum?