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?

user377299
  • 31
  • 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. – Bo Persson Feb 18 '18 at 03:45

2 Answers2

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.

bipll
  • 11,747
  • 1
  • 18
  • 32
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.

Davislor
  • 14,674
  • 2
  • 34
  • 49
  • 2
    [The type of a character literal in C++ is `char`](https://godbolt.org/g/wWb3Zq), 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. – Daniel H Feb 18 '18 at 04:23