enum
- C course
- Intermediate
- Lesson 37/116
- 5 min
Learn to define named constants with enum.
enum
An enum lists named integer constants. It's the basic way to replace magic numbers with meaningful names; it improves code readability.
Example: enum Color { RED, GREEN, BLUE };. Here RED = 0, GREEN = 1, BLUE = 2. By default the first constant is 0 and each next one increments. Usage: enum Color c = GREEN; printf("%d\n", c); prints 1. enum constants are substituted at compile time; they take no memory at runtime. That's why they're efficient and common.
Explicit values
You can give enum constants explicit values beyond the default. This is useful to define custom code lists.
Example: enum Level { LOW = 10, MEDIUM = 20, HIGH = 30 };. Now LOW is 10. Or partial explicit: enum Code { A = 1, B, C = 10, D };. Here B = 2 (increments from A), C = 10 (explicit), D = 11 (increments from C). This flexibility is handy when defining protocol codes and error numbers. Still, avoid complex value layouts to keep readability.
Practice Pick a color with enum and print
Define enum Color with RED, GREEN, BLUE. In main, write enum Color c = GREEN; and print with printf("%d\n", c);.
Starter code
#include <stdio.h>
// Define enum Color (RED, GREEN, BLUE)
// In main assign GREEN to c and print
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
enum Color { RED, GREEN, BLUE };
int main(void) {
enum Color c = GREEN;
printf("%d\n", c);
return 0;
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match enum constants to values
| Term | Meaning |
|---|---|
enum Color |
Enum type |
RED |
0 (default) |
GREEN |
1 |
BLUE |
2 |
2 What's the default first value of an enum?
- 1
- -1
- 0 Correct answer
- Unlimited
Explanation: The first enum constant defaults to 0.
3 Complete the enum constant
enum Color { RED, ____, BLUE };
enum Color { RED, GREEN, BLUE };
Explanation: GREEN increments from RED; its value is 1.