Explicitly assigning enum values
What you'll learn: How to manually control the underlying numbers assigned to your enumeration constants instead of relying on C's default counting.
Taking the driver's seat
By default, C treats an enum like a simple counter. If you define enum Colors {RED, GREEN, BLUE};, the compiler assigns 0 to RED, 1 to GREEN, and 2 to BLUE. While this automatic numbering is convenient, there are times when you need your constants to represent specific, meaningful numbers.
Think of it like a restaurant menu. If you let a computer assign ID numbers to your dishes, "Burger" might be #1 and "Fries" might be #2. But if your kitchen software already uses #101 for Mains and #201 for Sides, you need to tell the computer exactly which numbers to use so the systems can talk to each other.
How to assign values
You can use the assignment operator (=) directly inside the enum declaration. You can assign a value to one, some, or all of the items.
#include <stdio.h>
enum StatusCode {
SUCCESS = 200,
NOT_FOUND = 404,
SERVER_ERROR = 500,
UNKNOWN // This will be 501
};
int main() {
enum StatusCode result = NOT_FOUND;
printf("Status code is: %d\n", result);
printf("Next code is: %d\n", UNKNOWN);
return 0;
}
The "Auto-Increment" rule
When you explicitly assign a value, C doesn't stop its automatic counting; it just resets the starting point for the next item. In the example above, because SERVER_ERROR was set to 500, the compiler automatically assigned UNKNOWN the next integer in sequence: 501.
This behavior allows for "gaps" in your numbering. You might set the first item of a category to a high number, and let the following items fill in the sequence automatically until you reach a new category.
Why do this?
Explicit values are crucial when your code interacts with the outside world. If you are writing a program to control hardware, a specific bit pattern might trigger a motor. If you are reading a file format created by someone else, you must match their specific numeric definitions. Using explicit enums makes your code much more readable than using "magic numbers" (raw integers) scattered throughout your logic.
Key takeaway
You can override C's default zero-based indexing in an enum by using the = operator, and any unassigned items will simply follow the previous value by incrementing by one.