Linking error text to error codes in C

I am going to write a function that should translate an error message into an error code. So I have an array of error messages

const char *arr_error_message[] = 
{
    "Critical error",
    "Unexpected error",
    ...
}

      

and listing the error codes:

typedef enum error_code
{
    FIRST = 0,
    CRITICAL_ERROR = FIRST,
    UNEXPECTER_ERROR,
    ...
    LAST,
    NOT_FOUND_ERROR
} error_code_t;

      

and the function will be

error_code_t translate_error_code(const char *err)
{
error_code_t e = FIRST;
do
{
        if ( strcmp(arr_error_message[e], err) == 0 ) return e;
} while (++e != LAST);

return NOT_FOUND_ERROR;
}

      

What is a more efficient way to implement the function, is there any way (trick) to implement the function with O (1) complexity?

+3


source to share


3 answers


I think it is just a matter of getting the correct data structure. If you want to be able to map error codes directly to the string representation, you can simply return the error code stored in the corresponding array index:

return arr_error_message[err];

      



On the other hand, if you want to map error messages to error codes, you might want to consider using a hash table. Since your set of error codes will (probably) be relatively constant, you can use the tool gperf

to create the perfect hash table
that will map error messages to error codes extremely quickly.

Hope this helps!

0


source


If you plan on getting error strings from the error code, a simple array is sufficient to produce an O (1) algorithm.



But since you want the error code from the error string, the best I know is to use a hash table to store and retrieve the node. Use gnu gperf.

0


source







All Articles