Logical Operators in C++

A logical operator is used to compare or evaluate logical and relational expressions. There are three logical operators in C Plus Plus (C++) language. They are:

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

An expression involving && or || is sometimes called compound expressions, since the expression involves two other expressions, that is, each of these operators (&& and ||) takes two expressions, one to the left and another to the right.

Example of && operator:
Consider the following expression:

a > b && x == 10

The expression on the left is a > b and that on the right is x == 10. The above stated whole expression evaluates to true (1) only if both the expressions are true (i.e., if a is greater than b and the value of x is equal to 10).

Example of || operator:
Consider the following expression:

a < m || a < n

The above expression is true if one of the expression (either a < m or a < n) is true. That is, if the value of a is less than that of m or n then the whole expression evaluates to true. Needless to say, it evaluates to true in case a is less than both m and n.

Example of ! operator:
The ! (NOT) operator takes single expression and evaluates to true (1) if the expression is false (0), and evaluates to false (0) if the expression is true (1). In other words, it just reverses the value of the expression.

For example, consider the following expression:

!(x >= y)

The expression after the ! operator is x >= y. The above not expression evaluates to true only if the value of x is neither greater than nor equal to y (i.e., only if x is less than y). Therefore, the whole expression including the ! operator is the same as:

x < y

Precedence of Logical Operators:
Each of the logical operators falls into its own precedence group. All precedence groups are lower than the group containing the equality operators. The associativity is left to right.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *