6.3 How Not to Use std::strcmp

I l @ ve RuBoard

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.)

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net