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?
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.int:s1is "greater than"s2int:s1is "less than"s2s1is "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.