Be Cautious with Equality Tests on Literal Strings

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.

See also  What Are International Payments, And How Do They Work?

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist