Variable-Length Character Strings 205
return areEqual;
}
int main (void)
{
bool equalStrings (const char s1[], const char s2[]);
const char stra[] = "string compare test";
const char strb[] = "string";
printf ("%i\n", equalStrings (stra, strb));
printf ("%i\n", equalStrings (stra, stra));
printf ("%i\n", equalStrings (strb, "string"));
return 0;
}
Program 10.4 Output
0
1
1
The equalStringsfunction uses a whileloop to sequence through the character strings
s1and s2.The loop is executed so long as the two character strings are equal (s1[i] ==
s2[i]) and so long as the end of either string is not reached (s1[i] != '\0' && s2[i]
!= '\0').The variable i, which is used as the index number for both arrays, is incre-
mented each time through the whileloop.
The ifstatement that executes after the whileloop has terminated determines if you
have simultaneously reached the end of both strings s1and s2.You could have used the
statement
if ( s1[i] == s2[i] )
...
instead to achieve the same results. If you areat the end of both strings, the strings must
be identical, in which case areEqualis set to trueand returned to the calling routine.
Otherwise, the strings are not identical and areEqualis set to falseand returned.
In main,two character arrays straand strbare set up and assigned the indicated ini-
tial values.The first call to the equalStringsfunction passes these two character arrays
as arguments. Because these two strings are not equal, the function correctly returns a
val ue of false,or 0.
Program 10.4 Continued