The following
#include <iostream>
unsigned short int stringCompare ( char * s1, char * s2 )
{
// returns 1 if the character arrays s1 and s2 are equal;
// returns 0 otherwise
while (*s1 && (*s1++ == *s2++));
return (!(*s1) && !(*s2));
}
int main ()
{
char str1 [] = "americano";
char str2 [] = "americana";
std::cout << stringCompare(str1,str2);
return 0;
}
prints 1
, meaning my function's logic is incorrect. I'd like to understand why. Let me explain my logic:
while (*s1 && (*s1++ == *s2++))
simultaneously increments pointers s1
and s2
so long as s1 is not equal to '\0'
and the value s1
points to is the same as the value s2
points to. It is supposed to be a shorter way of writing
while (*s1 && *s2)
{
if (*s1 != *s2) break;
++s1; ++s2;
}
and relies on fancy operator precedence to shorten it.
The statement
return (!(*s1) && !(*s2))
means
"If s1 and s2 are both the null character, return true; otherwise return false"
because if the strings are equal then s1
and s2
will both be the null character after the while
loop.
Where am I wrong?
The flaw is that the ++
is done in the loop even on the last character, when they don't match. If the following character matches (which it does in this case, the null terminator) then they compare as true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With