On Sun, 16 Nov 2008 04:48:38 -0800 (PST),
=?GB2312?B?17/HvyBaaHVvLCBRaWFuZw==?= <zh********@gmail.com>
wrote:
>Hi,
I would like to have someone comments on what's the best practice
defining error codes in C.
Here's what I think:
solution A:
using enum
pros: type safe. better for debug (some debugger will show the name
not only the value)
cons: enum can not be forward declared which makes all error codes
couples together with the error code type ( enum )
Solution B:
using #define
pros: decouple, error codes could be defined in different .h file
cons: macro is bad. no type safe
Solution C:
typedef struct Error
{
int value;
} Error;
static Error const ERROR_OUT_OF_SPACE = { 123 };
pros: type safe. decouple, the error code type is no longer bound with
all the error definition
cons: I don't know any one doing it this way so I'm not sure if it has
some drawbacks or is it bad for (runtime/space) performance.
If using pure C, user could not compare the error value directly but
have to compare the inner "value" member which is not convenience.
All choices suffer from the same fundamental flaw; they use error
codes. The advantages of error codes are that they compact and
that they are testable, i.e, if a routine returns an error code
you can take appropriate action based on the error code. These
are advantages in the small.
So, if all you are concerned about is one module, you can use
error code definitions in the modules include file, and it
doesn't much matter whether you use enums or defines - the
decision is a religious one.
Using error codes in a larger scope is not a happy policy. If
you have several people working on a program or collection of
programs you end up with a lot of error codes, and version
control problems. The issue is that the definition of error
codes becomes a version control sensitive bottleneck. There are
various techniques for handling the problem; still you have to
know in advance that there is an issue. Otherwise you eventually
end up with a mess that has to be cleaned up - or lived with.
There is another issue with error codes when programming in the
large; they aren't a solution, they are a tool. Does your big
application have a coherent error management policy? Then error
codes are a detail; if not, then the tail is wagging the dog.
Richard Harter,
cr*@tiac.net http://home.tiac.net/~cri,
http://www.varinoma.com
Save the Earth now!!
It's the only planet with chocolate.