[Solved] When does !strcmp(a,b) evaluate as true?


Think about what the numeric values actually mean. When you treat a number as a Boolean condition, 0 is evaluated as false; anything else is evaluated astrue. So !0 evaluates as true, while !n evaluates as false for all non-zero values of n.

Put differently, !strcmp(s,anotherVar[i]) is true when s and anotherVar[i] are the same (because strcmp returns 0), but false when they aren’t (because strcmp returns a non-zero value).

Here’s a live, online demo, using the following code:

#include <stdio.h>

int main(void) {
    char * a = "hello";
    char * b = "world";
    char * c = "hello";

    if (!strcmp(a,b)) {
        printf("true for a and b\n");
    } else {
        printf("false for a and b\n"); // this runs
    }

    if (!strcmp(a,c)) {
        printf("true for a and c\n"); // this runs
    } else {
        printf("false for a and c\n");
    }

    return 0;
}

The output is:

false for a and b
true for a and c

2

solved When does !strcmp(a,b) evaluate as true?