Versions Compared

Key

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

...

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
bgColor#ffcccc
char *str1;
char *str2;

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

int check_password(char *usr, char *pw_given)
{
  User user = find_User(usr);
  if (!strcmp((user->password),pw_given)) {
    return 1;
  }
  return 0;
}

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

However, doing so would produce incorrect behavior. As a result, such a result should never be defaulted.

...

Code Block
bgColor#CCCCFF
char *str1; 
char *str2;

if (strcmp(str1, str2) == 0) {
  return "strings are equal";
}

...

References

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

...