recategorized by
677 views
4 votes
4 votes

Consider the following declaration of variables $a$ and $b.$

int a = 1, b = 0;

Which of the following is/are will evaluate to TRUE?

  1. b++ && b == a
  2. b++ && a == 0
  3. a || b == --a
  4. a || ++b == 0

 

recategorized by

3 Answers

0 votes
0 votes

Answer: C, D

int a = 1, b = 0

Option A: b++ && b == a

              First b && b == a will be evaluated then b++ will be done, since b is 0 i.e. false and false && anything evaluates to false.

 

Option B: b++ && a==0, same as explained above this expression will also evaluates to false.

 

Option C: a || b == --a, since a is true and true || anything is true so this expression evaluates to true.

 

Option D: a || ++b == 0, here also a is 1 and true || anything is true so this expression will also evaluates to true.

0 votes
0 votes
$b++$ is postfix increment operator. The old value of b will be used (and then b will be incremented by 1).

$b++ = 0$ which is false when used in logical operation. False && anything is false.

Hence, both option A and B are false.

$a = 1$ which is true when used in logical operation. True || anything is true.

Hence, both C and D are true.
0 votes
0 votes

ANSWER: C,D

1.b++ && b == a evaluates to FALSE because b is incremented after its value is used, resulting in 0 && 1, which is 0.

2.b++ && a == 0 also evaluates to FALSE because b becomes 1, and a is not 0, resulting in 1 && 0, which is 0.

3.a || b == --a evaluates to TRUE because a is 1 and --a decrements a to 0, resulting in 1 || 0, which is 1.

4.a || ++b == 0 evaluates to TRUE because a is 1 and ++b increments b to 2, resulting in 1 || 0, which is 1.

Short-circuit evaluation skips evaluating the right operand of && or || if the result can be determined by the left operand, optimizing execution.

Answer:

Related questions