...
In particular, do not default the test for non-zero. For instance, suppose a foo()
function returns 0 to indicate failure, or a non-zero value to indicate success. Testing for inequality with zero:
Code Block | ||
---|---|---|
| ||
if (foo() != 0) ... |
...
Function status can typically be indicated by returning -1
on failure, or any nonnegative number on success. While this is a common convention in the standard C library, it is discouraged in guideline ERR02-C. Avoid in-band error indicators.
...
The following code sample is preferable for improved maintenance. By defining what constitutes a failure and explicitly testing for it, the behavior is clearly implied and future modifications are more likely to preserve it. If there is a future modification, like the one above, it is immediately obvious that the if
statement in processRequest()
does not utilize the specification of validateUser()
correctly.
...
The code above works correctly. However, in order to simplify the login code or to facilitate checking a user's password more than once, a programmer might separate the password checking code from the login function. they They might do so in the following way.:
Code Block | ||
---|---|---|
| ||
int check_password(User *user, char *pw_given) { if (!strcmp((user->password),pw_given)) { return 1; } return 0; } void login(char *usr, char *pw) { User user = find_user(usr); if (!check_password(user, pw)) { grantAccess(); } denyAccess("Incorrect Password"); } |
...
Bibliography
Wiki Markup |
---|
[\[StackOvflw 09\]2009|AA. References#StackOvflw 09]\] "Should I return TRUE / FALSE values from a C function? \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] |
...