The C++ operators that are used in logical conditions such as compound expressions are called logical operators. Two or more relational expressions are combined using these operators.
In C++, there are three logical operators:
|AND Operator||&&||double ampersand sign|
|OR Operator||||||double pipe sign|
|NOT Operator||!||exclamation sign|
What is AND Operator (&&)
The AND operator is used to evaluate two relational expressions or conditions. It returns true (1) if both conditions are true. If any one condition is false, it returns false.
What is OR Operator (||)
The OR operator is used to evaluate two conditions or relational expressions. It returns true if one of the condition is true. If both conditions are false it returns false (0).
What is NOT Operator (!)
It is used to reverse the result of the relational expression or condition. It returns true if condition is false and returns false if the given condition is true.
The combination of relational expressions joined together by using logical operators is called compound expression. It is also known as logical expression, like relational expression, it is also returns true (1) or false (0).
A few examples of logical expressions are given below:
- a && b
- c || d
- ! (a
Suppose a=20, b=10 and c=20 then the following image shows the output of the logical or compound expressions:
Example of C++ Logical Operators
Consider, there are four integer variables named “total”, “math”, “eng” and “computer”. The variable “total” stores the sum of the of other three variables.
- To find out if the value in variable “total” is greater than or equal to 1000 and the value in variable “computer” is greater than 120, the compound expression will be written as:
total >= 1000 && computer > 120
- To find out if the value of “total” is greater than 800 or value in “eng” is greater than 80, the compound expression will be written as:
total > 800 || eng > 80
- To find out if the value in the variable “computer” is not greater than 33, the expression is:
! (computer > 33)