C Programming Basics
int a = 0, b = 0;
if (a++ && b++) { }
if (a++ || b++) { }
printf("%d %d\n", a, b);Which of the following is the output when the code above, with b++ on the right side of && and ||, is executed?
- A2 0
- B2 1
- C2 2
Show answer and explanation
Answer: A. 2 0
&& does not evaluate its right side if the left side is false, and || does not if the left side is true (short-circuit evaluation). In the first if, the value of a++ is 0, the value before the increment, which is false, so b++ is not executed and only a becomes 1. In the second if, the value of a++ is 1, which is true, so again b++ is not executed and a becomes 2. Note that when the right side contains an expression with side effects, such as ++ or a function call, whether it runs depends on the value of the left side.
- A. Correct. In neither if is b++ on the right side executed.
- B. This is the value obtained if b++ is executed once in one of the ifs. In both, the left side decides the result, so it is not evaluated.
- C. This is the value obtained if both b++ are executed. In both, the left side decides the result, so they are not evaluated.