Search code examples
cpointersstring-comparison

why does while(*s++ == *t++) not work to compare two strings


I'm implementing strcmp(char *s, char *t) which returns <0 if s<t, 0 if s==t, and >0 if s>t by comparing the fist value that is different between the two strings.

implementing by separating the postfix increment and relational equals operators works:

for (; *s==*t; s++, t++)
    if (*s=='\0')
        return 0;
return *s - *t;

however, grouping the postfix increment and relational equals operators doesn't work (like so):

while (*s++ == *t++)
    if (*s=='\0')
        return 0;
return *s - *t;

The latter always returns 0. I thought this could be because we're incrementing the pointers too soon, but even with a difference in the two string occurring at index 5 out of 10 still produces the same result.

Example input: strcomp("hello world", "hello xorld");

return value: 0

My hunch is this is because of operator precedence but I'm not positive and if so, I cannot exactly pinpoint why.

Thank you for your time!


Solution

  • Because in the for loop, the increment (s++, t++ in your case) is not called if the condition (*s==*t in your case) is false. But in your while loop, the increment is called in that case too, so for strcomp("hello world", "hello xorld"), both pointers end up pointing at os in the strings.