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?
source to share
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!
source to share
It simply asks to become the structure of the base of the tree. C doesn't really have strings, so all string collations will be loops comparing single characters. And strings are all constants. So, you can also split the strings into your compound characters and manually build a tree from them, and then walk the tree one character at a time.
source to share