int mystery( const char *s1, const char *s2 ) {
for( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) {
if( *s1 != *s2 ) {
return 0;
} //end if
} //end for
return 1;
}
I know it has typing errors but this is exactly how it was.
int mystery( const char *s1, const char *s2 ) {
for( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) {
if( *s1 != *s2 ) {
return 0;
} //end if
} //end for
return 1;
}
I know it has typing errors but this is exactly how it was.
It compares two strings, returning 1
if string one starts with string two, or vice-versa and 0
if not.
Looks like this function returns 1 when the two strings are equal and 0 when they are not.
At least, this may have been the intention.
It returns 0 if the shorter of (s1, s2) is not the same as the beginning of the longer one. The strings can be different lengths, but one must be a substring starting at the beginning of the other.
Edit. Oops sharth beat me to it. Vote him up before me.
Is it worth explaining?
for( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) {
The first element in a for loop, before the first ';' does the initial setup, here none is required.
So the for loop runs while either of the characters pointed at by s1 and s2 are not zero. Zero marks the end of string in c and c++.
The last part of the for loop is what extra to do on each loop - in this case moves the pointers s1 and s2 to point to the next character in each of the strings.
if( *s1 != *s2 ) {
return 0;
If the characters pointed at by s1 and s2 aren't the same - ie we have found the first different character in the two strings, return 0 ie false
return 1;
If we get to the end of one of the strings and we haven't found any characters that were different return 1 - ie true.
So the function returns true if the strings are identical or one string begins with the other, and false is the strings have and different characters.