Search code examples
cstringfunctionif-statementstrcmp

C - strcmp related to an if statement


In the code below I use strcmp to compare two strings and make this comparison the condition of an if statement. With the code below, the output will be hello world, because string "one" is equal to string "two".

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

char one[4] = "abc";
char two[4] = "abc";

int main() {

    if (strcmp(one, two) == 0) {
        printf("hello world\n");
    }
}

Now I want to change the program, and make it print hello world if the two string are different so I change the program that way:

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

char one[4] = "abc";
char two[4] = "xyz";

int main() {

    if (strcmp(one, two) == 1) {
        printf("hello world\n");
    }
}

I dont understand the reason why it does not print out anything.


Solution

  • Because strcmp() will return a negative integer in this case.

    So change this:

    if (strcmp(one, two) == 1) {
    

    to this:

    if (strcmp(one, two) != 0) {
    

    to take into account all the cases that the strings differ.

    Notice that you could have spotted that yourself by either reading the ref or by printing what the functions returns, like this:

    printf("%d\n", strcmp(one, two));
    // prints -23