Adding an int to a string c++

183 Views Asked by At

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?

2

There are 2 best solutions below

0
bipll On

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.

1
Davislor On

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.