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?
CodePudding user response:
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 is the character a
and therefore the final result that is appended to the string 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 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.
CodePudding user response:
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";
CodePudding user response:
Change it to this:
s = 'a';
s = 'b';
In simple terms, the std::string::operator =()
does not know how to convert and append 'a' 'b'
which is in the right hand side of the expression s = 'a' 'b';
. It assumes that it's an addition of two char
s which usually is a 1-byte integer under the hood.
So it's like you're trying to add two ASCII values and then append the result to s
. And std::string does not support that.