Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Sep 3, 1999

Be Cautious with Equality Tests on Literal Strings

It is perfectly legal to use of the equality operator to compare literal strings. However, the results might be surprising:
 
bool eq;
eq = "Mungojerrie" == "Rumpleteazer"; //not what you expect

What does this code snippet do? Let's parse the following expression carefully:

 
"Mungojerrie" == "Rumpleteazer";

The literal strings "Mungojerrie"and "Rumpleteazer" are both of type const char *. Thus, the expression checks whether the two memory addresses of the literal strings are identical and returns a Boolean result accordingly. However, the strings themselves are not compared, to the bafflement of the programmer. The right way of comparing literal strings is by using the standard function strcmp(). Alternatively, you can wrap the literal strings in two std::string objects and compare them.

Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date