Wednesday, May 20, 2009

Logical operators

Logical operators in C++

The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand.

For example

!(6 == 6) // evaluates to false because the expression at its right (6 == 6) is true.

!(8 <= 4) // evaluates to true because (8 <= 4) would be false.

!true // evaluates to false

!false // evaluates to true.


The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true, and false otherwise. The following panel shows the result of operator && evaluating the expression a && b:
&& OPERATOR

a b a&b
true true true
true false false
false true false
false false false


The operator || corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves. Here are the possible results of a || b:
a b a || b
true true true
true false true
false true true
false false false

For example

( (6 == 6) && (3 > 8) ) // evaluates to false ( true && false ).

( (6 == 6) || (3 > 8) ) // evaluates to true ( true || false ).

No comments:

Post a Comment