← Back to C Course | Chapter 8: Structures & Unions | Lesson 6 of 7

C Enumerations

What is an Enumeration?

Writing status instead of magic numbers like 0, 1, 2 makes code far easier to read and maintain -- comparing if (status == ACTIVE) is immediately clear, unlike if (status == 1) which requires you to remember what 1 means.

Example: What is an Enumeration?

c
#include <stdio.h>
enum Status { ACTIVE, INACTIVE };
int main() {
	enum Status status = ACTIVE;
	if (status == ACTIVE) {
		printf("Active");
	}
	return 0;
}

Defining an Enum

This declares a new type alongside a set of named integer constants belonging to it, similar in spirit to how struct introduces a new composite type -- both use the same curly-brace-and-semicolon syntax.

Example: Defining an Enum

c
#include <stdio.h>
enum Color { RED, GREEN, BLUE };
int main() {
	enum Color c = GREEN;
	printf("%d", c);
	return 0;
}

Enum Constant Values

enum Color {RED, GREEN, BLUE} assigns RED=0, GREEN=1, BLUE=2 automatically -- this predictable numbering is why enums work seamlessly as array indices or switch-case values.

Example: Enum Constant Values

c
#include <stdio.h>
enum Color { RED, GREEN, BLUE };
int main() {
	printf("%d %d %d", RED, GREEN, BLUE);
	return 0;
}

Custom Enum Values

enum Status {ACTIVE=1, PENDING, CLOSED} explicitly sets ACTIVE to 1, and since PENDING and CLOSED are unassigned, they automatically continue the sequence as 2 and 3.

Example: Custom Enum Values

c
#include <stdio.h>
enum Status { ACTIVE = 1, PENDING, CLOSED };
int main() {
	printf("%d %d %d", ACTIVE, PENDING, CLOSED);
	return 0;
}

Using Enums in switch Statements

Because switch requires constant integer expressions for its case labels, and enum constants are exactly that, they're one of the few types (besides plain integers and chars) that switch statements can branch on directly.

Example: Using Enums in switch Statements

c
#include <stdio.h>
enum Color { RED, GREEN, BLUE };
int main() {
	enum Color c = GREEN;
	switch (c) {
		case RED: printf("Red"); break;
		case GREEN: printf("Green"); break;
		case BLUE: printf("Blue"); break;
	}
	return 0;
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.