user13951969
user13951969

Reputation:

Regarding logical AND operator

int a=8, b=10,c=2,d;
d= ++a && ++b || ++b; 

In the above code , how do I know if (++a), (++b) are true or false . I know true is 1 and false is 0. But I can’t understand how to determine if these expressions are true or false . Please help.

Upvotes: 0

Views: 93

Answers (4)

H.S.
H.S.

Reputation: 12679

In C, logical operators (&&, ||, !, etc.) assume that zero is false and all other values are true.

Based on the operator precedence (operator && precedence is higher than || operator), the expression will be evaluated as:

d = (++a && ++b) || ++b; 

Note that logical AND operation expr1 && expr2 employs short-circuiting behaviour. With logical short-circuiting, the second operand, expr2, is evaluated only when the result is not fully determined by the first operand, expr1. That is, expr2 is not evaluated if expr1 is logical 0 (false).

++a will result in 9, a non zero value, hence, results in true, so right hand side operand of && operator, which is ++b, will be evaluated.
++b will result in 11, a non zero value, hence, results in true.

true && true will result in true.

Logical OR operation expr1 || expr2 employs short-circuiting behaviour. That is, expr2 is not evaluated if expr1 is logical 1 (true).

So, in the given expression, the left hand side of || is evaluated as true hence the right hand side operand of || operator, which is ++b, will not be evaluated and the result of whole expression will be true. Hence, the value of d will be 1.

Upvotes: 3

Manish Tambe
Manish Tambe

Reputation: 11

In 'C' we know that the true is '1' and false is '0' so above expression will be true because both the expressions are non zero. and if you want to print actual values like true and false i think you should try out printf("%s", x?"true":"false");

Upvotes: 0

Barmar
Barmar

Reputation: 782315

0 is false, any non-zero value is true. So you just need to determine whether ++a and ++b are zero or not zero.

Since a is initially 8, ++a is 9, which is non-zero, so it's true.

Since b is initially 10, ++b is 11, which is non-zero, so it's true.

9 && 11 is true because both the operands are true.

|| only evaluates the second operand if the first operand is false. So the second ++b ie never executed. The value of true || anything is true.

Therefore, d will be set to true, which is 1.

Upvotes: 4

SR810
SR810

Reputation: 228

In C, C++ and many other programming languages, for integers, 0 is considered false and any other integer (including negative numbers) is true. So here d will be evaluated to true

Upvotes: 1

Related Questions