3

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;
}
fractals
  • 816
  • 8
  • 23
J Pi
  • 41
  • 3

2 Answers2

5

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.

fractals
  • 816
  • 8
  • 23
  • Thanks HSK for the explanation, now, what is the purpose of the last If statements: if (s1[i] != 0) and if (s2[i] != 0)? I thought the conditions for those are already set on the for loop... Thanks – J Pi Aug 21 '18 at 01:19
  • Consider a situation where `s1 = "edit"` and `s2 = "editor"`. Because the first four letters are same, the function does not return anything in the for loop, and when `i = 4`, `s1[i] = 0`, so the for loop is ended. But the two strings are not the same, and this is when the last two if statements come into play. (`s2[i] != 0`) – fractals Aug 21 '18 at 01:21
  • Thanks for the detail response, Appreciated! – J Pi Aug 21 '18 at 02:44
3

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'.

asdf
  • 221
  • 1
  • 10