Please consider following code,
int i;
i = 1,2,3,4,5;
printf("First time i = %d\n",i);
i = (1,2,3,4,5);
printf("Second time i = %d\n",i);
Output:
First time i = 1
Second time i = 5
Why do the parentheses make the comma operator take last value and without parentheses it takes first value?
Thanks in advance.
First one is equivalent to (i = 1),2,3,4,5;
which means the commas have no effect. When used with parentheses it returns the last value in the "comma delimited list"
This is all due to operator precedence, which you can view a table about here
This is due to the operator precedence and the order of evaluation. =
binds harder than ,
and from that we can figure out that the below two expressions are the same:
i = 1,2,3,4,5 /* <- same as -> */ (i = 1),(2),(3),(4),(5)
side-note: the comma operator is the "weakest" operator of them all
Why does the comma operator yield the last value of our list?
To put it simple this operator evaluate the first operand only to discard it and move on to the next one, it binds left-to-right which means that it will start from the left, and continue walking towards the right.
Where can I read more about this topic?
Assignment has higher precedence than comma , hence the result you get in the first case. You can find the entire operator precedence table here .
Why parenthesis makes comma operator to take last value and without parenthesis it takes first value?
Because parenthesis is used to override the precedence. The first case is implicitly equivalent to :
(i = 1),2,3,4,5;
Comma evaluates from left to right and the rightmost value is the value of the entire expression. Read the documentation here.
The comma operator has left-to-right associativity. Two expressions separated by a comma are evaluated left to right. The left operand is always evaluated, and all side effects are completed before the right operand is evaluated.
Because =
has a higher precedence than ,
(which has the lowest), the first is the same as
(i = 1),2,3,4,5;
which assigns 1
to i
(i = 1
) then evaluating the expressions 2
, 3
, 4
, and 5
through the comma operators (the whole expression actually results in 5
, which is not used). In the second one,
(1,2,3,4,5)
is parenthesized, therefore it will be first evaluated before =
. It results in 5
(the right-most expression; this is the behavior of the comma operator) which is then assigned to i
.
i = (1,2,3,4,5);
| |
\---------\--- results in 5 then is assigned to i
See operator precedence Wikipedia article.
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