int main() {
int x = 6;
x = x+2, ++x, x-4, ++x, x+5;
std::cout << x;
}
// Output: 10
int main() {
int x = 6;
x = (x+2, ++x, x-4, ++x, x+5);
std::cout << x;
}
// Output: 13
Please explain.
In C or C++, the comma ‘,’ is used in different purposes. Here we will see how they can be used. Comma as an Operator. The comma operator is a binary operator, that evaluates its first operand, and then discards the result, then evaluates the second operand and returns the value. The comma operator has the lowest precedence in C or C++.
The comma operator is lower precedence than assignment. All expressions in a comma operator are evaluated, but only the last is used as the resulting value. So both assignments are performed. The result of the comma operator in your case would be the result of c = d. This result is not used. Can you show that how can the result be used?
3) Comma operator in place of a semicolon. We know that in C and C++, every statement is terminated with a semicolon but comma operator also used to terminate the statement after satisfying the following rules. The variable declaration statements must be terminated with semicolon.
In the OCaml and Ruby programming languages, the semicolon (";") is used for this purpose. JavaScript and Perl utilize the comma operator in the same way C/C++ does. In Java, the comma is a separator used to separate elements in a list in various contexts.
Because ,
has lower precedence than =
. In fact, ,
has the lowest precedence of all operators.
First case:
x=x+2,++x,x-4,++x,x+5;
This is equivalent to
(x=x+2),(++x),(x-4),(++x),(x+5);
So, x
becomes 6+2 = 8, then it is incremented and becomes 9. The next expression is a no-op, that is x-4
value is calculated and discarded, then increment again, now x
is 10, and finally, another no-op. x is 10.
Second case:
x=(x+2,++x,x-4,++x,x+5);
This is equivalent to
x=((x+2),(++x),(x-4),(++x),(x+5));
x+2
is calculated, then x
is incremented and becomes 7, then x - 4
is calculated, then x
is incremented again and becomes 8, and finally x+5
is calculated which is 13. This operand, being the rightmost one, is the taken as the result of the whole comma expression. This value is assigned to x
.
x is 13.
Hope it's clear.
And, as one of the comments suggests -
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