Reputation: 65
#include <stdio.h>
int main()
{
int i,j;
i=j=(22,23,24);
printf("i:%d",i);
printf("\nj:%d",j);
}
this is giving output of both i,j as 24.
#include <stdio.h>
int main()
{
int i,j;
i=j=22,23,24;
printf("i:%d",i);
printf("\nj:%d",j);
}
and this gives both i,j as 22. Can someone explain the terminlology behind. TIA
Upvotes: 2
Views: 93
Reputation:
A comma separated list of constant expressions does not make much sense. The main purpose of comma operator is to separate assignments - a transparent and conscious side-effect.
With parentheses and two more assignments it groups as:
i = j = (22,x=23,y=24);
Since an expression in parens (E)
is a primary expression, this can be hierarchically seen as
i = j = E;
This E
consists of three comma separated (sub-)expressions where the last one counts. This is assignment y=24
with result/evaluation 24
.
The 22
is thrown away, but x=23
has the obvious side effect.
Normally E
would be something like 2*n+1
that does not need parens. Until up to the i = j > 22 ? 23 : 24
(where it gets a bit confusing).
The second one groups:
i=j=22, x=23, y=24;
This starts to make sense now. It is just three assigments on one line. 23 and 24 are not "lost".
The assigment expression i=j=22
itself has one level of recursion; it works right-to-left, which is only natural.
But the examples are more about combining separating comma operators ,
and grouping parentheses (
)
.
Upvotes: 0
Reputation: 75062
An assignment operator =
has higher precedence than a comma operator ,
.
C Operator Precedence - cppreference.com
In this statement
i=j=(22,23,24);
(22,23,24)
is firstly calculated. The 22
and 23
are ignored by the comma operator and it is evaluated to 24
. Then, the result 24
is assigned to j
, and the value is also assigned to i
.
On the other hand, in this statement
i=j=22,23,24;
i=j=22
is firstly calculated. This assigns 22
to j
, then assign the value to i
. After that, the evaluation result of assignment operator 22
, and an integer literal 23
are ignored by the comma operator. Finally the expression is evaluated to the value 24
, which is also ignored.
Upvotes: 5