Using a comma in an expression and assigning it to a variable

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); } 
+4
source share
3 answers

The comma operator returns the result of its second operand, and the operator || - short circuit. So what happens in this case:

  • ++a , a now 6 .

  • Since the result (1) is nonzero, the right-hand side of && is evaluated. This means ++b , so b becomes 11 .

  • (1) and (2) are the left side of the operator with a comma, so the && result is discarded. (this is 1 if it is important to you).

  • ++a on the right side of the first , evaluated. a now 7 .

  • assignment t - t now 7 , the result of the first operator is a comma.

  • All this was the left side of another operator with a comma, so the result ( 7 ) is discarded. Further evaluated ++a . a now 8 .

  • Since a not equal to 0, short circuits || and ++c not evaluated. c remains 15 .

Results: t is 7 , a is 8 , b is 11 , and c is 15 . The printf statement outputs:

 7 8 11 15 

In general, this code will be easier to understand if you just wrote:

 ++a; ++b; t = ++a; ++a; 

Which has exactly the same behavior.

+8
source

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 
+6
source
 int t, a = 5, b = 10, c = 15; 

In C (and C ++), the comma operator evaluates its first operand, discards it and evaluates its second operand and returns it.

++a && ++b first evaluated, and now 6, b is now 11.

(++a && ++b, ++a) now the second operand is calculated to the right of the comma ( ++a ), and now 7. Also at this point t is assigned the value 7. This is because the assignment operator has a higher priority than the comma operator .

(++ a & ++ b, ++ a), ++ a now the second operand to the right of (++ a && ++ b, ++ a) is evaluated. The third is evaluated. The third ++ a` gives a value of 8.

Logical operator || evaluates its first operand, and if it is true , it does not evaluate the second operand. The first operand (++a && ++b, ++a), ++a is nonzero (true), and therefore ++ c is not evaluated. c stays at 15.

0
source

Source: https://habr.com/ru/post/1484560/


All Articles