C Enumerations
In this page:
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?
#include <stdio.h>
enum Status { ACTIVE, INACTIVE };
int main() {
enum Status status = ACTIVE;
if (status == ACTIVE) {
printf("Active");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
enum Color { RED, GREEN, BLUE };
int main() {
enum Color c = GREEN;
printf("%d", c);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
enum Color { RED, GREEN, BLUE };
int main() {
printf("%d %d %d", RED, GREEN, BLUE);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
enum Status { ACTIVE = 1, PENDING, CLOSED };
int main() {
printf("%d %d %d", ACTIVE, PENDING, CLOSED);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: