How to Use Simple Logical Operators in C++

By Stephen R. Davis

C++ programs have to make decisions. A program that can’t make decisions is of limited use. Invariably a computer program gets to the point where it has to figure out situations such as “Do this if the a variable is less than some value; do that other thing if it’s not.”

The ability to make decisions is what makes a computer appear to be intelligent. (By the same token, that same property makes a computer look really stupid when the program makes the wrong decision.) Making decisions, right or wrong, requires the use of logical operators.

The simple logical operators, shown in the table, evaluate to true or false.

Simple Operators Representing Daily Logic
Operator What It Does
== Equality; true if the left-hand
argument has the same value as the right
!= Inequality; opposite of equality
>, < Greater than, less than; true if the
left-hand argument is greater than or less than the right-hand
argument
>=, <= Greater than or equal to, less than or equal to; true if either >
or == is true,
or either < or == is true
&& AND; true if both the left- and
right-hand arguments are true
|| OR; true if either the left- or
right-hand argument is true
! NOT; true if its argument is false; otherwise, false

The first six entries in the table are comparison operators. The equality operator is used to compare two numbers. For example, the following is true if the value of n is 0, and is false otherwise:

n == 0;

Looks can be deceiving. Don’t confuse the equality operator (==) with the assignment operator (=). Not only is this a common mistake, but it’s a mistake that the C++ compiler generally cannot catch — that makes it more than twice as bad.

The following statement does not initialize n to 0; it compares the current value of n with 0 and then does nothing with the results of that comparison:

n == 0;   // programmer meant to say n = 0

The greater-than (>) and less-than (<) operators are similarly common in everyday life. The following logical comparison is true:

int n1 = 1;
int n2 = 2;
n1 < n2;

The greater-than-or-equal-to operator (>=) and the less-than-or-equal-to operator (<=) are similar to the less-than and greater-than operators, with one major exception. They include equality; the other operators don’t.

The && (AND) and || (OR) work in combination with the other logic operators to build more complex logical expressions, like this:

// the following is true if n2 is greater than n1
// AND n2 is smaller than n3 
// (this is the most common way determining that n2 is in
// the range of n1 to n3, exclusive)
(n1 < n2) && (n2 < n3);