Maximillan
Maximillan

Reputation: 59

Confusion about logic when using strcmp() function

char string1[10];
char string2[10];

strcpy(string1, "hello");
strcat(string2, string1);

if(strcmp(string1, string2)){
   printf("Heellloww!!!);
} else {
   printf("Bye");
}

When I perform check on if(strcmp(string1, string2)) then what should strcmp() return? Should it always return positive 1 in order to execute statements in if?

Upvotes: 1

Views: 1167

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

The problem with your code is strcat: it causes undefined behavior.

In order for strcat to work, both strings passed to it must be null-terminated. However, the first string that you pass is not null-terminated - in fact, it is uninitialized.

Fixing this problem is simple - you can place zero into the initial position of string2 at declaration:

char string2[10] = { 0 };

Now the strings would compare as equal, meaning that strcmp would return zero. If you want Heellloww printed when two strings are the same, you need to add == 0 to your if statement.

Upvotes: 2

tdao
tdao

Reputation: 17668

Always check the manual:

int strcmp(const char *s1, const char *s2);

Return value: The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

In your case, strcmp returns zero if string1 and string2 are the same (or match). So in case they are the same, you would print Bye, and if they are different then you would print Heellloww.

Upvotes: 3

Related Questions