简体   繁体   中英

Associating error text with error codes in C

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

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

and enumeration of 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 the more efficient way of the function implementation, is there any way(trick) to implement the function with the complexity O(1) ?

I think this is just a question of getting the right data structure. If you want to be able to map from error codes directly to the string representation, you can just return the error code stored in the appropriate array index:

return arr_error_message[err];

On the other hand, if you want to map from error messages to error codes, you could consider using a hash table. Since your set of error codes (probably) will be relatively constant, you could consider using the gperf tool to generate a perfect hash table , which would make it possible to extremely quickly map error messages to error codes.

Hope this helps!

If you were planning to get error strings from error code, a simple array would suffice to get O(1) algorithm.

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

This just begs to be a radix tree structure. C doesn't really have strings, so all the string comparisons are going to be loops comparing single characters anyway. And the strings are all constants. So you might as well split the strings up into their composite characters and hand-construct the tree from them, then walk the tree one character at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM