bryan sammon
bryan sammon

Reputation: 7441

String concatenation, why does this compile?

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;
}

Upvotes: 10

Views: 478

Answers (4)

nklauza
nklauza

Reputation: 1621

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

Upvotes: 3

Yu Hao
Yu Hao

Reputation: 122383

x += '|' + b, x;

This is a comma operator, which has the lowest precedence. It takes two operands, , evaluates them left to right. Both of its operands are perfectly legal in this example:

Note that comma operator has a value of the right operand, but it's usually useless, like in this example. So it's the same with:

x += '|' + b;
x;  // no effect

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361302

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.

Upvotes: 21

Mahesh
Mahesh

Reputation: 34615

x += '|' + b, x;

It's because the the expression before the , operator takes to effect. For example -

std::string y("Hello");
x += '|' + b, y;

The above would still give the result |Bryan in your program.

Upvotes: 2

Related Questions