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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: