What does strcmp() exactly return in C?
Solution 1:
From the cppreference.com documentation
int strcmp( const char *lhs, const char *rhs );
Return value
Negative value if lhs appears before rhs in lexicographical order.
Zero if lhs and rhs compare equal.
Positive value if lhs appears after rhs in lexicographical order.
As you can see it just says negative, zero or positive. You can't count on anything else.
The site you linked isn't incorrect. It tells you that the return value is < 0
, == 0
or > 0
and it gives an example and shows it's output. It doesn't tell the output should be 111
.
Solution 2:
To quote the man page:
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 other words, you should never rely on the exact return value of strcmp
(other than 0
, of course). The only guarantee is that the return value will be negative if the first string is "smaller", positive if the first string is "bigger" or 0
if they are equal. The same inputs may generate different results on different platforms with different implementations of strcmp
.
Solution 3:
The output depends on the implementation. A decent implementation of the strcmp
function would be:
int strcmp (const char * s1, const char * s2)
{
for(; *s1 == *s2; ++s1, ++s2)
if(*s1 == 0)
return 0;
return *(unsigned char *)s1 < *(unsigned char *)s2 ? -1 : 1;
}
The above implementation returns -1 if s1 < s2, 1 if s1 > s2 and 0 if s1 = s2.
But usually, there is a faster version which is implemented for actual use:
int strcmp (const char * s1, const char * s2)
{
for(; *s1 == *s2; ++s1, ++s2)
if(*s1 == 0)
return 0;
return *(const unsigned char *)s1 - *(const unsigned char *)s2;
}
Note that this is faster because it skips the branching which was being done previously. Therefore, we usually have the convention that a negative return value means that s1
is lexicographically smaller than s2
, and a positive value means vice-versa.
Solution 4:
strcmp
returns 'a value lesser than 0' if the string1 is alphabetically lesser than string2; zero
, if they are equal; and a 'value greater than 0' if string 1 is alphabetically greater than string 2.
Solution 5:
int strcmp(const char *str1, const char *str2)
will return a value less, equal or greater than 0. If it returns 0 it means that the two strings are equal, if it returns a value minor than 0 it indicates that str1 is less than str2. If it returns a value > 0 it means that str2 is less than str1.
Your return value is 1 because "Heloooo" is one character more then "Helloo". In fact the word Helloo has 6 characters and Heloooo has 7 characters. Exactly one more char.