6.3 How Not to Use std::strcmp
The function
std::strcmp compares two C-style strings and
returns zero if they are equal and nonzero if they are different. To
check whether two C-style strings are equal, we use code like the
following:
// Check for equal
if (std::strcmp(string1, string2) == 0)
std::cout << "Strings equal\n";
else
std::cout << "Strings not equal\n";
Some programmers omit the comment and the == 0
clause, leading to the following, confusing code:
if (std::strcmp(string1, string2))
std::cout << "......";
At first glance, this program obviously compares two strings and
executes the std::cout statement if they are
equal. Unfortunately, the obvious is wrong. If the strings are equal,
std::strcmp returns zero, and the
std::cout is not executed. Because of this
backwards behavior, you should be very careful in your use of
strcmp and always comment its use.
(The problem with std::strcmp is another reason
that C++ style strings are easier to use than the old C-style
strings.)
|