#include <stdio.h> int main(void) { int a = 0, b = 0, x; x = (0 && (a = (b = 777))); /* originally: x = 0 && (a = b = 777) */ printf("%d %d %d\n", a, b, x); x = (777 || (a = +(+b))); /* originally: x = 777 || (a = ++b) */ printf("%d %d %d\n", a, b, x); return 0; }
![]() | This is a solution to exercise 20 on page 118 of C by Dissection. |
![]() | x = (0 && (a = (b = 777))); /* originally: x = 0 && (a = b = 777) */ |
We have added a number of parentheses to clarify the evaluations of the expressions. The short circuited && is first calculated. The left operand is false (0), and therefore the right operand (a = (b = 777)) is not executed. The reason is that the value of the expression (0 && (a = (b = 777))) cannot be affected by the value of (a = (b = 777)). This is crucial because the assigments of a and b to 777 are not carried out! Both a and b remain to be 0. x becomes 0 due to the outer assignment operator. |
![]() | printf("%d %d %d\n", a, b, x); |
The value of the variables a, b, and x are printed. As argued above, they are all 0, so '0 0 0' is printed. Try it yourself! |
![]() | x = (777 || (a = +(+b))); /* originally: x = 777 || (a = ++b) */ |
The short circuited or || is evaluated. The first operand is true (777), and therefore the value of the next operand (a = +(+b)) is not needed. Thus, the assignment of a and the incrementing of b do not take place. In the outer assignment x becomes 1 (meaning true). |
![]() | printf("%d %d %d\n", a, b, x); |
The values of the variables a, b and x are printed. This is '0 0 1'. |