Search code examples
ccs50boolean-expressionstrcmp

The Exclamation Notation and `strcmp` Function in C programming


There is a question that makes me confused during learning with the Harvard University CS50 course. The following is the question that bothers me for a long time.

For the following code, it wants to compare the string called "EMMA" with the array called "names" which contains 4 names inside.

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    // An array of names
    string names[] = {"EMMA", "RODRIGO", "BRIAN", "DAVID"};

    // Search for EMMA
    for (int i = 0; i < 4; i++)
    {
        if (strcmp(names[i], "EMMA") == 0)
        {
            printf("Found\n");
            return 0;
        }
    }
    printf("Not found\n");
    return 1;
}

In the above codes, it uses if (strcmp(names[i], "EMMA") == 0) to check the name "EMMA".

However, it would also run if I write the code in another way like if I replace if (strcmp(names[i], "EMMA") == 0) with if (!strcmp(names[i], "EMMA")), and it turns out the same answer "Found".

If my memory serves me right that the exclamation ! in C means "NOT". In the first method, it uses two equal signs to express the value turns out the same with 0. But in the second method, it uses exclamation notation in front of the function strcmp. I am not familiar with the meaning of why it also gives the same output in the second method even though I have looked up the definition of function strcmp.

Moreover, it would be great if someone could tell me what value would the strcmp function gives and what is the proper expression in the plain words?


Solution

  • The ! operator is used for boolean negation.

    !0 is the same as 1 (true)

    !1 is the same as 0 (false)

    In fact, every non-zero integer is true in C and only 0 is false.

    So, if strcmp(names[i], "EMMA") == 0 is true

    Then !strcmp(names[i], "EMMA") is also true because !0 is true.

    Moreover, it would be great if someone could tell me what value would the strcmp function gives and what is the proper expression in the plain words?

    Check this link.

    In short,

    strcmp can return three possible values:

    0, if both the strings are equal

    a positive integer, if the first string is greater than the second string

    a negative integer, if the first string is smaller than the second string