239 views

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

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.

by

in option c == should have higher precedence than || so wouldnt  b == --a be calculated first and since it will be 0==0 so true value. though it wouldnt effect the answer but i still wanted to know if i am thiking wrong.

@Godlike Yes grouping will be according to the precedence like $a ||b==--a$ will be equivalent to $(a || (b==(--a)))$ but don’t confuse precedence over order of execution. Logical operators guarantees that the execution will be from left to right.

Since a = 1 so it will evaluates to true and due to the presence of || it will short-circuit and the expression will return true. Right side of the || will never get executed.

$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.
by

1
2
3