Logical operations

What is a logical operation

A logical operation is an operation for which the result can only be either true or false. Basically, that is an operation that returns a boolean.

Is equal operation ==

The logical operator used to test if two things have the same value is ==. It returns true (1) if the two operands are equal, false (0) otherwise.

Example:

bool isItTrue; isItTrue = 5 == 5; // isItTrue equals true (1). isItTrue = 5 == 2; // isItTrue equals false (0).

Here is an other example:

int n1 = 53; int n2 = 34; bool isEqual = n1 == n2; // isEqual equals false (0).

The variable receiving the result of a logical operation does not have to be of type bool. Any variable that can hold numbers can be used:

int n1 = 4; int n2 = 4; int isEqual = n1 == n2; // isEqual equals true (1).

The other logical operations

Here is a table with the logical operators:

SymbolThe result is true if
!=The value of both operands is different.
==Both operands are equal.
<The value of the left operand is smaller than the right operand.
>The value of the left operand is bigger than the right operand.
<=The value of the left operand is smaller or equal to the right operand.
>=The value of the left operand is bigger or equal to the right operand.
&&Both operands equal true (1).
||At least one of the operands equal true (1).
!Inverts the value of the boolean as right operand (true (1) becomes false (0) and false (0) becomes true (1)). That operator only takes one operand.

Examples

Here is some examples of logical operations:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main() { bool b = true || false; // b is assigned with the value 1 (true). bool b2 = 5 <= 8; // b2 is assigned with the value 1 (true). bool b3 = 5 == 5 && 2 >= 8; // b3 is assigned with the value 0 (false). bool b4 = !true; // b4 is assigned with the value 0 (false). bool b5 = 9 != 9; // b5 is assigned with the value 0 (false). double n1 = 9.54; double n2 = 60.3; bool b6 = (n1*2) >= n2; //b6 is assigned with the value 0 (false). return 0; }