Re: return value conventions in c
From: Thad Smith (thadsmith_at_acm.org)
Date: 07/29/04
- Next message: Thad Smith: "Re: Quicksorting a linked list"
- Previous message: Arthur J. O'Dwyer: "Re: return value conventions in c"
- In reply to: Darrell Grainger: "Re: return value conventions in c"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 29 Jul 2004 10:48:18 -0600
Darrell Grainger wrote:
>
> On Wed, 28 Jul 2004, John Hanley wrote:
>
> > When using int return values in C, is there a convention for
> > success/failure?
> There is no convention. Some people might have their own personal
> convention. If you equate success with TRUE and failure with FALSE then
> success == !0 and failure == 0.
I use the normal convention that all variables that are considered
boolean be named so that a non-zero value implies that the condition
named by the variable is true. So
int initialized; /* bool: routine has been initialized */
makes sense when used in the normal context of a boolean, e.g., if
(initialized) ...
Extending that to a function:
int initialize(int chan); /* initialize specified channel */
It seems natural to me that a true return value (non-zero) for a
function indicates that the requested option succeeded. If I do that, I
may use a user type for boolean, rather than an int (yes, I know that C
now has a boolean type, but I usually use old compilers).
Alas, if I want to return multiple failure codes (and a single success
code), that suggests that the opposite be used: 0 = success. For that
case I usually define an enumeration type for the return status. Then
the caller uses
typedef enum { /* result of initialize() */
IR_OK, /* success */
IR_NOMEM, /* insufficient memory */
...
} eInitRes;
eInitRes r; /* initialization result */
...
if ((r = initialize(chan)) != IR_OK) {
switch (r) {
case IR_NOMEM: ...
case IR_BADCHAN: ...
}
Thad
- Next message: Thad Smith: "Re: Quicksorting a linked list"
- Previous message: Arthur J. O'Dwyer: "Re: return value conventions in c"
- In reply to: Darrell Grainger: "Re: return value conventions in c"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|