Re: return value conventions in c

From: Thad Smith (thadsmith_at_acm.org)
Date: 07/29/04


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



Relevant Pages

  • Re: boolean annoyance
    ... This is in my opinion a matter of convention. ... return 0 on success, a nonzero error code on failure, and pass a valid result ... and throw an exception on severe failure. ...
    (comp.lang.ruby)
  • Re: Complaint about return code convention in queue_work() etc.
    ... return false for failure, ... the function should return a "succeeded" boolean. ... queue_workand friends flagrantly violate this convention. ...
    (Linux-Kernel)
  • Re: Exception vs Boolean
    ... An enum or boolean to indicate success or failure *is* a "return ...
    (microsoft.public.dotnet.general)
  • Re: A Queue implementation of doubly linked list in C
    ... success and non-zero values for failure; ... typically that a non-zero failure code can represent different kinds ... (That's probably more a Unix convention than a C ...
    (comp.lang.c)
  • Re: return from main
    ... convention of using exitto indicate success. ... failure, and returning an odd number indicates success. ...
    (comp.lang.c)