Relational and Logical Operators
Within Relational Operators, the word relational refers to the relationships in which the values could have with one another. It is Depending on the relations, the values can be compared. This comparison output either in true or false.
Example:
10 > 20 (false)
10 < 20 (true)
Operators such as >, < used to compare values are known as relational operators. C language supports six relational operators.
The operators and their meaning are listed in the tables which are given below: -
In Logical Operators, the word logical refers to the ways relationships can be connected together using the rules of formal logic. C++ has three logical operators: -
exp1 && exp2 evaluates to true only if both the expressions are true
x= 10; y = 12;
x < 12 && y > 10 evaluates to true since the individual expression is true
x < 5 && y = = 12 evaluates to false since the first expression is false.
exp0 || exp1 evaluates to true if either of the expression is true
x= 10; y= 12;
x > 12 || y > 10 evaluates to true since at least one expression is true
x = = 20 || y != 12 evaluates to false since neither expression is true.
! exp evaluates to true if its value is not equal to the expression
!x = 10 false since x is 10
!x = 12 true since x is not 12
&& and | | these are used when we want to test more than one condition and make decisions.
Example:
a > b && c = 12
evaluates to true only if both expressions evaluate to true.
Within C++, a true value is any value other than 0. A false value is 0.
Expressions using relational or logical operators' return 0 for false and 1 for true. thus, the following code fragment is not only true, but also prints the integer value of true that is 1.
#include <iostream.h>
main()
{
int x;
x=100;
cout<<(x = =100);
}
The output is: 1
Compare to the Arithmetic operators Relational and Logical operators are lower in precedence. This means that whenever arithmetic expressions are used on either side of the relational operators, an arithmetic expression is evaluated first after that the results are compared. For instance, 10 > 1+ 12 is evaluated only after evaluating 1+12 that is, 13. Now, the resultant 10 > 13 is evaluated, that comes out to be false.