Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ffcccc
void login(char *usr, char *pw)
{
  User user = find_User(usr);
  if (!strcmp((user->password),pw_given)) {
    grantAccess();
  }
  denyAccess("Incorrect Password");
}

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. He/she might do so in the following way.

Code Block
bgColor#ffcccc
int check_password(charUser *usruser, char *pw_given)
{
  User user = find_User(usr);
  if (!strcmp((user->password),pw_given)) {
    return 1;
  }
  return 0;
}

void login(char *usr, char *pw)
{
  User user = find_User(usr);
  if (!check_password(usruser, pw)) {
    grantAccess();
  }
  denyAccess("Incorrect Password");
}

In an attempt to leave the previous logic intact, he just replaced the strcmp with a call to his new function. However, doing so would produce incorrect behavior. As a result. In the case above, any user which inputs an incorrect password is granted access. Again, two conventions conflict and produce code that is easily corrupted when modified. To make code maintainable and to avoid these conflicts, such a result should never be defaulted.

...

The following approach to using a comparison function for this purpose is preferred. By performing an explicit test, any programmer that wishes to modify the equality test can clearly see the implied behavior and convention that is being followed.

Code Block
bgColor#CCCCFF#ffcccc
void login(char *str1;usr, 
char *str2;

pw)
{
  User user = find_User(usr);
  if (strcmp((str1, str2user->password),pw_given) == 0) {
     return "strings are equal"grantAccess();
  }
  denyAccess("Incorrect Password");
}

References

[1] "Should I return TRUE / FALSE values from a C function?"

...