This question already has an answer here:
- What does the comma operator , do? 8 answers
#include<stdio.h>
int main(void) {
int a=(1, 2), 3;
printf("%d", a);
return 0;
}
output: 2
Can any one explain how output is 2?
Can any one explain how output is 2?
In the statement
a = (1, 2), 3;
,
used is a comma operator.
Due to higher operator precedence of =
operator than that of ,
operator, the expression operand (1, 2)
will bind to =
as
(a = (1, 2)), 3;
In case of comma operator, the left operand of a comma operator is evaluated to a void expression, then the right operand is evaluated and the result has the value and type of the right operand.
There are two comma operators here. For the first comma operator in the expression (1, 2)
, 1
will be evaluated to void expression and then 2
will be evaluated and will be assigned to a
.
Now side effect to a
has been taken place and therefore the right operand of second comma operator 3
will be evaluated and the value of the expression (a = (1, 2)), 3
will be 3
.
Can any one explain how output is 2?
Because the precedence of the assignment operator (=
) is higher than the comma operator (,
).
Therefore, the statement:
a = (1, 2), 3;
is equivalent to:
(a = (1, 2)), 3;
and the expression (1, 2)
evaluates to 2
.
the result of:
a = x, y => x
a = (i, j) => j
therefore, if we have:
x = (1 , 2)
a = (1 , 2) , 3 => 2
As said here:
The comma operator separates expressions (which have value) in a way analogous to how the semicolon terminates statements, and sequences of expressions are enclosed in parentheses analogously to how sequences of statements are enclosed in braces: (a, b, c) is a sequence of expressions, separated by commas, which evaluates to the last expression c while {a; b; c;} is a sequence of statements, and does not evaluate to any value. A comma can only occur between two expressions – commas separate expressions – unlike the semicolon, which occurs at the end of a (non-block) statement – semicolons terminate statements.
The comma operator has the lowest precedence of any C operator, and acts as a sequence point. In a combination of commas and semicolons, semicolons have lower precedence than commas, as semicolons separate statements but commas occur within statements, which accords with their use as ordinary punctuation: a, b; c, d is grouped as (a, b); (c, d) because these are two separate statements.
I hope this answers your question.
来源:https://stackoverflow.com/questions/46177275/comma-operator-in-c