Managing error strings in C

Dave P. Schaumann dave at cs.arizona.edu
Fri Jan 11 08:54:33 AEST 1991


In article <1991Jan10.122227 at lotus.lotus.com> blambert at lotus.lotus.com (Brian Lambert) writes:
>Hi:
>
>I was wondering if anyone out there had any clever ways of handling
>error messages in C. [...]
>
> [ method deleted ]
>
>I'm sure there are a zillion ways to do this.  I have used this method
>in the past, but was never very happy with it.  (It's not very elegant,
>and is difficult to maintain as one must be sure to use the proper
>number in the #define.)
>
>Got a better idea?

Sure do.  I don't know how 'clever' it is, but it's worked well for me in
the past.  Really, it's just a variation on what you had, but I think a bit
cleaner.

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'.

Additionally, for a large program, it may be helpful to catagorize the
errors.  For example, last spring I wrote a small compiler for a class, and
I had syntax_error(), semantic_error(), and system_error().  Each one of
these dealt with an error condition in a different way (besides just printing
a message): syntax_error() also dealt with token skipping, semantic_error()
dealt with manipulating the symbol table, and system_error() called exit(1). :)

The main advantage of this method over what you had is that it is easily
expandable.  If I want to add a new error name, I just add it to the enum list,
and add a new entry in the switch.  The way you had it, you would also have to
make sure the value of the error name corresponded with the position of the
error text in your array.

>Thanks!

De nada.

>Brian Lambert
>Lotus Development Corporation
>blambert at lotus.com


Dave Schaumann		| You are in a twisty maze of little
dave at cs.arizona.edu	| C statements, all different.



More information about the Comp.lang.c mailing list