Managing error strings in C

Dan Bernstein brnstnd at kramden.acf.nyu.edu
Fri Jan 11 17:10:49 AEST 1991


In article <636 at caslon.cs.arizona.edu> dave at cs.arizona.edu (Dave P. Schaumann) writes:
> In some .h file, I have an enum type:
> typedef enum { NO_MEM, FOO_BARRED, BAR_FOOED, CODE_SPAMMED } error_t ;
> Then, I can just say something like 'error( NO_MEM, <helpful strings> )'
> and the routine error will have a switch on every name in 'error_t'.

While this does let you add errors easily, it doesn't handle
user-defined error messages. This version does, and is portable to
compilers without enum:

#define NO_MEM 1
#define NO_MEM_ERR "Out of memory"
#define CANT_OPEN 2
#define CANT_OPEN_ERR "Can't open"
..

struct { int n; char *s; } errors[] = {
{ NO_MEM, NO_MEM_ERR } ,
{ CANT_OPEN, CANT_OPEN_ERR } ,
..
}

(``const char'' would be better under ANSI.) The error checker can just
do a linear search. The only thing you have to make sure of is that all
the error numbers are different.

---Dan



More information about the Comp.lang.c mailing list