I’m having an issue with solving a coding exercise and during debugging I’ve noticed that my strcmp() function doesn’t work as I expected. The strcmp() function returns the wrong value compared to what I would expect. Perhaps I’m lacking some crucial undertanding of how strcmp() really works.
My code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char string[] = "dogs";
char compare[] = "bark";
int result = strcmp(string, compare);
printf("int result = %d\n", result);
}
The return value of the program is:
int result = 2
which is unexpected for me since the documentation of strcmp() states that:
strcmp(string_A, string_B)
-
string_A>string_B==> return value >0 -
string_A<string_B==> return value <0 -
string_A==string_B==> return value =0
In my example strcmp(string, compare) or strcmp("dogs", "bark") the return value should be less than 0 since "dogs" < "bark" but it keeps returning 2 which I’m also not sure if it’s expected behaviour that it always prints out the same integer.
>Solution :
the return value should be less than 0 since "dogs" < "bark"
False.
Since ‘d’ comes after ‘b’, or more specifically since the character code for ‘d’ is greater than the character code for ‘b’, the former is considered greater, and therefore a value greater than 0 is returned.