In a && b , this returns true if both a and b are equal to 1. If a=-1 and b=-1 then also the expression returns true.Similar is the case with a||b,where a=-1 and b=0,it returns true. Can anybody please explain the reason.
The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0 . The type of the result is int . Both operands must have an arithmetic or pointer type.
& is bitwise operator and, && is logical for example if you use two number and you want to use bitwise operator you can write & . if you want to use to phrase and you want to treat them logically you can use && .
In C programming language, there are three logical operators Logical AND (&&), Logical OR (||) and Logician NOT (!).
&& is used to perform and operation means if anyone of the expression/condition evaluates to false whole thing is false. || is used to perform or operation if anyone of the expression/condition evaluates to true whole thing becomes true. so it continues till the end to check atleast one condition to become true.
a && b
returns 1 when both a
and b
are nonzero, not just when they're equal to 1. Otherwise it returns 0.
a || b
returns 1 when at least one of a
or b
is nonzero, not just when one of them is equal to 1. Otherwise it returns 0.
To give some examples:
0 && 0 -> 0
1 && 0 -> 0
1 && 1 -> 1
2 && 1 -> 1
-1 && -1 -> 1
-100 && 0 -> 0
0 || 0 -> 0
1 || 0 -> 1
0 || 1 -> 1
-1 || 0 -> 1
-100 || 20 -> 1
C11 (n1570) §6.5.13 al 3 p 99 say :
The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0.
-1 is a nonzero value, so -1 && -1
is 1
.
On the MSDN page for &&:
The logical-AND operator produces the value 1 if both operands have nonzero values.
Clearly both operands are -1 in your example so they will produce 1.
On the same page, listed for ||
If either operand has a nonzero value, the result is 1.
In your case one operand is -1, therefore the result is 1
AND returns 1 if both operands have non-zero values. OR returns 1 if either operand has a non-zero value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With