...
Code Block | ||
---|---|---|
| ||
\#define FALSE 0 if(foo() \!= FALSE) // Given convention (2), this will always yield the intended behavior. { return true; } |
Noncompliant Code Example
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. Also, when quickly reviewed, the code could easily appear to test for inequality.
Code Block | ||
---|---|---|
| ||
char *a, *b; if(\!strcmp(a,b)) { return "strings are equal"; } |
However, doing so would produce incorrect behavior. As a result, such a result should never be defaulted. Instead, the
Compliant Solution
The following approach to using a comparison function for this purpose is preferred.
Code Block | ||
---|---|---|
| ||
\#define STREQ(str1, str2) (strcmp((str1), (str2)) == 0) |
...
char *inputstring, *somestring; if ( STREQ( inputstring, somestring |
...
))
{
return "strings are equal";
}
|
By defining a macro to adapt the comparison function to have a return value compliant with convention (3), the code clearly illustrates its intent and agrees with implied behavior.