In programming we use logical operators ( && and || ) for AND and OR respectively with relational operators. These are binary operators and take two operands. These operators use logical expressions as operands, which return TRUE or FALSE.
The following table (called truth table) can be used to get the result of the && operator and || operator with possible values of their operands. It is used to explain the result obtained by the && and || operators.
Expression 1 | Expression 2 | Expression 1 && Expression 2 | Expression 1 || Expression 2 |
True | False | false | True |
True | True | true | True |
False | False | false | False |
False | True | false | True |
The && operator has a higher precedence than the || operator. Both operators associate from left to right. An expressions containing && or || is evaluated only until truth or falsehood is known. Thus evaluation of the expression (age > 18) && (height > 6) will stop immediately if age > 18 is false (i.e. the entire expression is false) and continue if age > 18 is true (i.e. the entire expression could still be true if the condition height > 6 is true ).
There is another logical operator that is called logical negation. The sign ! is used for this operator. This operand enables a programmer to ‘reverse’ the meaning of a condition. This is a unary operator that has only a single condition as an operand. The operator ! is placed before a condition. If the original condition (without the ! operator) is false then the ! operator before it converts it to true and the statements attached to this are executed.
Look at the following expression
Here the cout statement will be executed if the original condition (age > 18) is false because the ! operator before it reverses this false to true.
The truth table for the logical negation operator ( ! ) is given below.
Expression | ! Expression |
true | false |
false | true |
For previous lesson click here: If/else Structure
For next lesson click here: if/else Sample Program
the easiest way to learn programming
introduction to programming
Logical Operators
0 comments:
Post a Comment