While working on AstraKernel I was thinking about how to design a more intuitive way to implement kernel panic handling. When an error occurs in the kernel, I wanted to use an error code that would be more descriptive of the specific error, avoiding hard-coded reasons, and giving developers a clearer way to identify the problem. This led me to implement an enumeration, starting from code 0, which represents no kernel error (AKA status code OK), and proceeding downward in negative values.
The design led me to think about the best way to use enumeration, and while researching it, I learned there are many ways to use the enum keyword. Here, I am trying to compile all the possible methods for using it.
What are enums?
An enum is short for enumeration, which is an enumerated type that defines a set of named integer constants, called enumerators. Each name inside the enumeration becomes an integer constant.
A minimal enum looks like this:
enum
{
KERR_OK,
KERR_NOMEM
};In this example, you have the keyword enum that declares an anonymous enumeration, followed by a list of enumerators. KERR_OK, as the first enumeration constant, will by default receive the integer value 0. KERR_NOMEM will receive the next value 1. Any additional enumerators without explicitly assigned values continue to increment by 1 from the previous value.
Explicitly assigning a value to an enumerator constant will break the default sequence. For instance, take this example:
enum
{
RED,
BLUE,
BLACK = 5,
BROWN,
YELLOW
};RED starts at 0, BLUE receives 1, and now BLACK is explicitly assigned the integer value 5. BROWN then follows the auto-increment rule and receives the value 6, YELLOW receives 7, and so on, until an enumerator is explicitly assigned a different value.
TODO
- Introduce named enums.
- Add explicit values.
- Introduce typedef versions.
- Handle advanced styles (bit flags, forward declarations).
- Add practical examples and real-world usage patterns.