Please explain this block of code:
void main()
{
int t,
a = 5,
b = 10,
c = 15;
t = (++a && ++b, ++a), ++a || ++c; // need explanation for this line
printf("%d %d %d %d", t, a, b, c);
}
The comma operator returns the result of its second operand, and the ||
operator will short circuit. So what happens in this case is:
++a
is evaluated, a
is now 6
.
Since the result of (1) was non-zero, the right side of the &&
is evaluated. That means ++b
, so b
becomes 11
.
(1) and (2) are the left side of a comma operator, so the result of the &&
is discarded. (it's 1
, if that matters to you).
The ++a
on the right side of the first ,
is evaluated. a
is now 7
.
the assignment to t
takes place - t
is now 7
, the result of the first comma operator.
All of that was the left side of another comma operator, so the result (7
) is discarded. Next ++a
is evaluated. a
is now 8
.
Since a
is not 0, the ||
short circuits, and the ++c
isn't evaluated. c
stays 15
.
Results: t
is 7
, a
is 8
, b
is 11
, and c
is 15
. The printf
statement outputs:
7 8 11 15
Overall, this code would be easier to understand if you just wrote:
++a;
++b;
t = ++a;
++a;
Which has precisely the same behaviour.
Execution ->
t = (++a && ++b, ++a), ++a || ++c; // () Priority
^
t = (++a && ++b, ++a), ++a || ++c; // ++a -> a = 6
^
t = ( 6 && ++b, ++a), ++a || ++c; // ++b -> b = 11
^
t = ( 6 && 11 , ++a), ++a || ++c; // 6 && 11 -> 1
^
t = ( 1 , ++a), ++a || ++c; // ++a -> a = 7
^
t = ( 1 , 7), ++a || ++c; // (1,7) -> 7 ... Comma operator has less priority
^
t = 7, ++a || ++c; // (t = 7), ++a || ++c; ...Assigned value to t... Comma operator has less priority
^
++a || ++c; // ++a -> a = 8
^
8 || ++c; // 8 || ++c -> 1 ...as 1 || exp -> 1...Logical OR skip next part if 1st exp is true
^
Finally ->
t = 7
a = 8
b = 11
c = 15
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