3

If I have a string string foo and I write foo += 27, what gets appended to the string? Is it the character with the ASCII hex value 0x27 or with 0x1b?

Also, when I try foo += 0, I get a compilation error saying ambiguous overload of += operator with a string and int. How come I don't get a compilation error with adding non-zero numbers, but I do get an error with zero?

If I first say int z = 0 and then foo += z, I do not get an error. What causes the difference?

1
  • 2
    The value 0 used to be the way to say nullptr. Still causes confusion on whether you mean a value or a pointer. Commented Feb 18, 2018 at 3:45

2 Answers 2

3

Is it the character with the ASCII hex value 0x27 or with 0x1b?

Since you're not writing foo += 0x27, apparently it's 0x1b.

When you append 0, the compiler cannot distinguish between the two overloads, one appending a char and another a pointer-to-char. An overload appending an int would be the best match but it's not declared in the basic_string template.

Sign up to request clarification or add additional context in comments.

Comments

2

I originally erred when I wrote that the compiler treats foo + 27 the same as foo + '\033' or foo + '\x1b'. (Either of which would be a better way to write the expression.) The type of a character constant is int in C, but char in C++. However, because of the implicit conversion between char and int, and because there is no more specific std::basic_string<T>::operator+(int), the compiler ends up converting 27 to '\x1b' anyway.

C++ originally used 0 as the keyword for a null pointer, so foo + 0 could mean either foo + static_cast<const char*>(0) (more succinctly, foo + nullptr) or foo + '\0'. The first is undefined behavior and makes no logical sense, but the compiler doesn’t guess that you must have meant it the other way.

1 Comment

The type of a character literal in C++ is char, not int (see what the demangled name of the generated function is); implicit conversion (in both directions) means there isn't much backwards incompatibility with C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.