Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - strcmp related to an if statement [duplicate]

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.

like image 914
scugn1zz0 Avatar asked Dec 11 '22 12:12

scugn1zz0


2 Answers

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
like image 121
gsamaras Avatar answered Dec 25 '22 17:12

gsamaras


According to the C Standard (7.23.4.2 The strcmp function)

3 The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

So what you need is to write the if statement like

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

or

if ( !( strcmp(one, two) == 0 ) ) {
like image 38
Vlad from Moscow Avatar answered Dec 25 '22 17:12

Vlad from Moscow