Search code examples
carduinostrncmp

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?


Solution

  • 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) {