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;
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With