Scoped enum limitations in C
What you'll learn: Why C enumerations share a single global space and how to prevent naming collisions in your code.
The Global Roommate Problem
Imagine you are moving into a shared house, but there are no private bedrooms—everyone has to put their belongings in one giant living room. If you bring a lamp and your roommate also brings a lamp, you can’t just yell, "Turn on the lamp!" because the house won't know which one you mean.
In languages like C++ or Java, "scoped enums" act like private bedrooms. You can have a Color.Red and a Alert.Red without any issues. However, standard C is like that crowded shared house. When you define an enum, the names of the constants (the "enumerators") are dumped directly into the surrounding scope—usually the global scope.
The Naming Collision
If you try to use the same name in two different enums, the C compiler will throw an error. It doesn't matter that they belong to different enum types; to C, a name is a name.
#include <stdio.h>
enum TrafficLight {
RED, // This takes the name 'RED'
YELLOW,
GREEN
};
enum Status {
OK,
RED, // ERROR! 'RED' is already taken by TrafficLight
FAILURE
};
int main() {
// The compiler is now confused.
// Does RED mean the light or the status?
return 0;
}
Because C lacks true namespacing for enums, the names RED, YELLOW, and OK become global constants. You cannot reuse them anywhere else in that scope.
The "Prefix" Solution
Since C won't provide the "bedrooms" for us, programmers have developed a convention to stay organized: Prefixing.
Instead of naming a constant RED, you include a short tag that identifies the group it belongs to. This mimics the behavior of scoped enums manually.
enum TrafficLight {
TL_RED,
TL_YELLOW,
TL_GREEN
};
enum Status {
ST_OK,
ST_RED,
ST_FAILURE
};
By adding TL_ and ST_, you’ve created unique names. Now the "living room" has a TL_RED lamp and an ST_RED lamp, and the compiler can easily tell them apart. When writing C, always assume your enum names will clash and prefix them accordingly.
Key takeaway
C enumerators share the same global namespace, so you must use unique prefixes to avoid naming conflicts between different enums.