Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation, why does this compile?

Tags:

c++

I found this in my code, was a typo on my part, but it still compiled. Anyone know why? I have no idea.

#include <string>
#include <iostream>

int main()
{
  std::string x;
  std::string b = "Bryan";
  x += '|' + b, x;
  std::cout << x << std::endl;
}
like image 994
bryan sammon Avatar asked Aug 09 '13 17:08

bryan sammon


2 Answers

x += '|' + b, x;

Here , is basically an operator whose left operand is evaluated first, followed by right operand. It is that simple.

Since the precedence of += and + is higher than , operator, it becomes equivalent to this:

(x += '|' + b) ,  x;

Here:

left  operand => (x += '|' + b)
right operand =>  x

Try another example:

int f() { ... }
int g() { ... }

f(), g();

Here f() will be called first followed by g().

Hope that helps.

like image 160
Nawaz Avatar answered Oct 13 '22 06:10

Nawaz


x += '|' + b, x;

This compiles because the comma here is acting as an operator (instead of a separator) where the right-hand operand has no effect.

From Wikipedia:

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

...

The comma operator has the lowest precedence of any C operator...

In x += '|' + b, x;, operator += has a higher precedence than , and operator + has a higher precedence than +=, meaning that it's equivalent to (x += ('|' + b)), x;

Additionally, if you compile your code with warnings on, you will likely receive a warning similar to this:

warning: right-hand operand of comma has no effect
like image 33
nklauza Avatar answered Oct 13 '22 06:10

nklauza