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?

  1. A2 0
  2. B2 1
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. Which of the following is the output when the switch statement above, which contains a case without break, is executed?
  2. Which of the following is the output when the program above is executed?
  3. When the function f above is called three times in a row, which of the following is the return value of the third call?
  4. In C, which of the following correctly pairs the lifetimes of (1) a local variable declared inside a function without static, (2) a region allocated with malloc, and (3) a variable declared outside any function?
  5. int is 32 bits (maximum 2147483647). Which of the following is the largest n for which the function fact(n) above returns the factorial of n correctly, without overflow?