2

Using + is a valid way to append a char to a string in C++ like so:

string s = "";
s += 'a';

However,

string s = "";
s += 'a' + 'b';

gives a warning: implicit conversion from 'int' to 'char' changes value and does not append a and b characters.

Why does the first example append the char and the second does not?

5
  • 4
    Because the latter works like s = s + ('a'+'b'). You're adding the two char together first before appending them. Commented Nov 19, 2021 at 16:44
  • 1
    hint: 'a'+'b' is an integer 195. Try s += "ab". Commented Nov 19, 2021 at 16:44
  • 1
    chars are an integer type with special display rules that allow you to see them as characters. Unfortunately, in this case, this means when you add two chars you don't append them, you sum the two numeric values of character's encoding. Commented Nov 19, 2021 at 16:51
  • 1
    Should be (s +='a') +='b';, isn't it? Commented Nov 19, 2021 at 16:53
  • No. think of += as a function and you won't be far wrong. The parameters of the function are resolved before the call. Oh wait. Are you suggesting a code change, @康桓瑋 ? Commented Nov 19, 2021 at 16:55

3 Answers 3

3

This has to do with operator precedence. Let's take for example the expression:

string s = "";
s += '0' + '1';//here + has higher precedence than +=

Here + has higher precedence than += so the characters '0' and '1' are group together as ('0' + '1'). So the above is equivalent to writing:

s+=('0' + '1');

Next, there is implicit conversion from char to int of both '0' and '1'. So '0' becomes the decimal 48 while the character '1' becomes decimal 49.

So essentially the above reduces to:

s+=(48 + 49);

or

s+=(97);

Now 97 corresponds to the character a and therefore the final result that is appended to the string variable named s is the character a.

Now lets apply this to your example:

string s = "";
s += 'a' + 'b';

First due to precedence:

s+=('a' + 'b');

Second implicit conversion from char to int happens:

s+=(97 + 98);

So

s+=195;

So the character corresponding to decimal 195 will be appended to string s.

You can try out adding and subtracting different characters to confirm that this is happening.

Why does the first example append the char and the second does not?

So the fundamental reason is operator precedence.

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

1 Comment

I'd upvote if you mention that the decimal equivalents are contingent on the near-ubiquitous but by no means required ASCII encoding.
1

That's a drawback with operator overloading; one needs to remember it is little more than a syntactic sugar and a nice way of calling functions.

s += 'a' + 'b';

is grouped as it would be for a simple expression like

a += 1 + 2;

for an int type a.

In other words 'a' + 'b' is evaluated first. And that has an int type due to argument promotion rules. A std::string has no specific overload for += for an int, only one that is normally a narrowing conversion, so the compiler issues a warning.

If you want to append "ab" to the string s, then use

s += "ab";

Comments

-1

Change it to this:

s += 'a';
s += 'b';

In simple terms, the std::string::operator+=() does not work as you wish because in the statement s += 'a' + 'b';, the priority/precedence of the + is greater than the assignment = operator. This means that the compiler will first evaluate 'a' + 'b' and will then evaluate the assignment =. Thus it will assume that it's an addition of two chars which usually is a 1-byte integer under the hood.

Adding the ASCII values of a and b will return 97+98 == 195 but the max value of char is 255. So this will cause an overflow and then wrap around and will eventually result in 195-256 == -61 and -61 is not part of ASCII so what you will see depends on your specific terminal.

s += 'a' + 'b'; is like you're trying to add two ASCII values and then append the resulting char (which is terminal-specific) to s. And that's why you are not seeing your desired characters being printed.

When I run this code:

#include <iostream>


int main()
{
    std::string str( "" );
    str += 'a' + 'b';
    std::cout << "The char is: " << str[ 0 ]
              << " and its ASCII value is: " << +str[ 0 ] << '\n';

    return 0;
}

in the Windows command prompt I see the following:

The char is: ├ and its ASCII value is: -61

Hopefully, this helps.

3 Comments

It is not that "std::string::operator+=() doesn't know how to convert and append 'a' + 'b'. The fundamental reason is operator precedence. Even if it knows how to convert and append 'a' + 'b' it will still not do so due to operator precedence.
This is an ingenious explanation but is sadly not correct.
@Bathsheba True. I updated the answer. Please cast an upvote if it's good enough.

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.