An error enum in C
Named error codes read better than magic numbers, and map to messages.
typedef enum {
ERR_OK = 0,
ERR_NULL_ARGUMENT,
ERR_OUT_OF_RANGE,
ERR_OUT_OF_MEMORY,
ERR_COUNT
} Error;
static const char *messages[ERR_COUNT] = {
"ok",
"null argument",
"value out of range",
"out of memory",
};
const char *error_message(Error e) {
if (e < 0 || e >= ERR_COUNT) {
return "unknown error";
}
return messages[e];
}
Error set_stars(int stars, int *out) {
if (out == NULL) {
return ERR_NULL_ARGUMENT;
}
if (stars < 0 || stars > 3) {
return ERR_OUT_OF_RANGE;
}
*out = stars;
return ERR_OK;
}
How it works
- The enum starts at zero for success.
- A parallel table of strings turns a code into a message.
- The count member keeps the table and the enum in step.
Keywords and builtins used here
NULLcharconstenumerror_messageifintreturnset_starsstatictypedef
The run, in numbers
- Lines
- 32
- Characters to type
- 502
- Tokens
- 128
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 73 seconds.
Step 1 of 2 in Errors & cleanup, step 8 of 11 in APIs, errors & testing.