Printing Errors

From C

Jump to: navigation, search

Code Sample #1

The following code sample associates the error message with the error code by using the index of an array, which makes it appropriate only for non-negative error codes, and with a maximum range that's suited for the length of an array.

#include <stdio.h>

enum errors {
    ERROR1,
    ERROR2,
    ERROR3
};

char *errors[] = { 
    [ERROR1] = "ERROR1: ...",
    [ERROR2] = "ERROR2: ...",
    [ERROR3] = "ERROR3: ..."
};

int main(void) {
    printf("%s", errors[ERROR2]);
    
    return 0;
}

Code Sample #2

The following code sample associates the error message with the error code by using a function that searches the error code, and therefore it doesn't share the concerns mentioned for the previous code sample.

#include <stdio.h>

enum error_e {
    ERROR1 = 10000,
    ERROR2,
    ERROR3
};

struct error_s {
    enum error_e error;
    char *s;
};

struct error_s errors[] = {
    { ERROR1, "ERROR1: ..." },
    { ERROR2, "ERROR2: ..." },
    { ERROR2, "ERROR3: ..." }
};

#define array_len(a) (sizeof a / sizeof *a)

char *get_error(enum error_e error) {
    for (size_t i = 0; i < array_len(errors); i++) {
        if (errors[i].error == error)
            return errors[i].s;
    }
    
    return "Unknown error code.";
}

int main(void) {
    printf("sizeof errors (array): %zu\n", sizeof errors);
    printf("%s\n", get_error(ERROR2));
    
    return 0;
}

.

Personal tools