Reputation: 41
I found a function which performs the same as strcmp
but I was unable to see where the comparison s1 == s2
is happening. I need help. Thanks.
int MyStrcmp (const char *s1, const char *s2)
{
int i;
for (i = 0; s1[i] != 0 && s2[i] != 0; i++)
{
if (s1[i] > s2[i])
return +1;
if (s1[i] < s2[i])
return -1;
}
if (s1[i] != 0)
return +1;
if (s2[i] != 0)
return -1;
return 0;
}
Upvotes: 3
Views: 175
Reputation: 221
We can not see '==' indeed, because the function use exclusion method, this function trys to filter all the inequality situations.
The first half of this function: compare each char between s1 and s2, if any of char is not equal, the function finish and return corresponding comparison result.
The second half of this function: compare whether s1 and s2 have same length, if their length are not equal, then return corresponding comparison result.
At last, after it tried to exclude all inequality situations, its judgement is 'equal'.
Upvotes: 3
Reputation: 856
If s1 == s2
, it also means that the length of the two strings are equal. Keeping this in mind, going through the for loop, none of the if statements in the loop are ever true. Therefore, we escape the for loop as s1[i] = s2[i] = 0
, with i
set to the length of the strings given. Now for the remaining two if statements, none of the conditions are true as s1[i] = s2[i] = 0
. The code thus returns 0
.
Upvotes: 5