João Sacramento
João Sacramento

Reputation: 83

strncmp() function vs !(strncmp()) function

I'm programming a lock where to unlock it you have to insert a PIN code in a Keypad. I have the following variables:

char password_init[4] = {'1', '2', '3', '4'}; //initial password
char password[4];

When the user press a key in the keypad, that digit will be stored in the variable password and after the user press 4 digits both variables will be compared in order to give, or not, acess to the lock.

I found that one solution to do this would be using strncmp() function as:

if (!(strncmp(password, password_init, 4))){
Serial.println("PIN Code correct");
}

This works but I don't understand why I should use !(strncmo()) instead of strncmo(). If I use if (strncmp(password, password_init, 4)) the outcome will be an incorrect PIN code.

The strncmp() function compares two strings, character by character, so can someone explain me why I have to use it in a negative way in orther to the initial password and the passaword pressed by the user in the keypad match?

Upvotes: -2

Views: 883

Answers (2)

chux
chux

Reputation: 154218

int strncmp(const char *s1, const char *s2, size_t n); not only compares for equality, it also check for order. So it needs at least 3 different return values.

The strncmp function returns an integer greater than, equal to, or less than zero, accordingly as the possibly null-terminated array pointed to by s1 is greater than, equal to, or less than the possibly null-terminated array pointed to by s2. C17dr § 7.24.4.4 3

  • Return some positive int: s1 is "greater than" s2
  • Return some negative int: s1 is "less than" s2
  • Return 0: s1 is "equal to" s2

!(strncmp(password, password_init, 4)) implies they are equal (up to the first 4 characters of the strings).


I find the below easier to read as a test for string equality.

if (strncmp(password, password_init, 4) == 0) {

Upvotes: 3

MikeCAT
MikeCAT

Reputation: 75062

strncmp() function returns zero when the two strings are same and non-zero when they are different.

Using ! (logical not) operator, the result will be true (1) when the strings are same and false (0) when they are different.

Upvotes: 5

Related Questions