Search code examples
c++stringstring-concatenationconditional-operator

Two cases of string concatenation using conditional operator in C++


The first function works perfectly fine:

string createurl(string protocol, string siteName, string domain, bool www = true)
{
    return protocol + "://" + (www ? "www." : "") + siteName + "." + domain;
}

But the second one results in a compiler error:

string greeting(string name, string gender)
{
    return "Hello " + ((gender == "Male") ? "Mr" : "Miss") + name;
}

Error: C2110 '+': cannot add two pointers.

What is the difference between the two functions to give me this error, and what is the solution?


Solution

  • That's because the "Hello " + ((gender == "Male") ? "Mr" : "Miss") operation tries to concatenate two literal strings, which isn't possible (the literal strings will decay to pointers, and two pointers doesn't make sense).

    The quick solution is to make the first string an std::string object:

    using namespace std::literals
    // ...
    return "Hello "s + ((gender == "Male") ? "Mr" : "Miss") + name;
    

    The trailing s in "Hello "s turns it into a std::string object.