This (note the comma operator):
#include <iostream> int main() { int x; x = 2, 3; std::cout << x << "\n"; return 0; }
outputs 2.
However, if you use return
with the comma operator, this:
#include <iostream> int f() { return 2, 3; } int main() { int x; x = f(); std::cout << x << "\n"; return 0; }
outputs 3.
Why is the comma operator behaving differently with return
?
The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.
A comma expression contains two operands of any type separated by a comma and has left-to-right associativity. The left operand is fully evaluated, possibly producing side effects, and its value, if there is one, is discarded. The right operand is then evaluated.
The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.
The comma operator (,) allows you to evaluate multiple expressions wherever a single expression is allowed. The comma operator evaluates the left operand, then the right operand, and then returns the result of the right operand.
According to the Operator Precedence, comma operator has lower precedence than operator=
, so x = 2,3;
is equivalent to (x = 2),3;
. (Operator precedence determines how operator will be bound to its arguments, tighter or looser than other operators according to their precedences.)
Note the comma expression is (x = 2),3
here, not 2,3
. x = 2
is evaluated at first (and its side effects are completed), then the result is discarded, then 3
is evaluated (it does nothing in fact). That's why the value of x
is 2
. Note that 3
is the result of the whole comma expression (i.e. x = 2,3
), it won't be used to assign to x
. (Change it to x = (2,3);
, x
will be assigned with 3
.)
For return 2,3;
, the comma expression is 2,3
, 2
is evaluated then its result is discarded, and then 3
is evaluated and returned as the result of the whole comma expression, which is returned by the return statement later.
Additional informations about Expressions and Statements
An expression is a sequence of operators and their operands, that specifies a computation.
x = 2,3;
is expression statement, x = 2,3
is the expression here.
An expression followed by a semicolon is a statement.
Syntax:
attr(optional) expression(optional) ; (1)
return 2,3;
is jump statement (return statement), 2,3
is the expression here.
Syntax:
attr(optional) return expression(optional) ; (1)
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