You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

This recommendation is derived from and considers the implications of the following common conventions:

(1) Function failures are typically indicated by one of the following return values: 0, -1, an error number.

(2) Functions return 0 if false, but only non-zero if true.

(3) Comparison functions (such as the standard library function strcmp()) return 0 if the arguments are equal and non-zero otherwise.

In regards to (1):

Although failures are frequently indicated by a return value of zero (which C considers to be false), there are common conventions that may conflict in the future with code where the test for non-zero is not explicit.

Basically,

#define FAIL 0

if(foo()==FAIL)

is preferable for code maintenance to

if(foo())

In this case, defaulting the test for non-zero welcomes bugs if and when a developer modifies foo to return an error code or -1 rather than 0 to indicate a failure (all of which are common conventions). 

In regards to (2):

Though rare, the following is fairly common:

#define TRUE 1

if(foo() == TRUE)

However, because most functions only guarantee a return value of non-zero for "true," the code above is better written by checking for inequality with 0 ("false") as follows.

#define FALSE 0

if(foo() != FALSE)

In regards to (3):

Because comparison functions (like strcmp) return 0 for equality and non-zero for inequality, they can cause confusion when used to test for equality. If someone were to switch the following strcmp call with an equals function, they might instinctively just replace the function name.

if(!strcmp(a,b))

However, doing so would produce incorrect behavior. As a result, such a result should never be defaulted. Instead, the following approach to using a comparison function for this purpose is preferred.

#define STREQ(str1, str2) (strcmp((str1), (str2)) == 0)

If ( STREQ( inputstring, somestring ) ) ...

By defining a macro to adapt the comparison function, the code clearly illustrates its intent and agrees with implied behavior.

  • No labels