Handout 4a

Logical Operators in C/C++*


Logical Operators

Logical operators in C++, as with other computer languages, are used to evaluate expressions which may be true or false. Expressions which involve logical operations are evaluated and found to be one of two values: true or false.

Operator

Meaning

Example of Use

Truth Value

&& AND (exp 1) && (exp 2) True if exp 1 and exp 2 are BOTH true.
|| OR (exp 1) || (exp 2) True if EITHER (or BOTH) exp 1 or exp 2 are true.
! NOT ! (exp 1) Returns the opposite truth value of exp 1; if exp 1 is true, ! (exp 1) is false; if exp 1 is false, ! (exp 1) is true.

Examples of expressions which contain relational and logical operators

if ((bodyTemp > 100) && (tongue == red)) status = flu;
if ((numeratorDF == even) || (denominatorDF == even)) formula = 26;
if (((clock == 9.) && (sun != shining))&& (locatuion == US)) time = pm;

Truth Tables

The value of a boolean relation depends upon the values of the components. You can think of the expressions as asking a question. For example, P && Q asks, "Are P and Q (both) true?". P || Q asks, "Is (either) P or Q true?" Finally, ! P asks,"Is P not true?"

The tables below give the values for the each operator given possible values for P and Q. (These are called "truth tables".)

P && Q

 

P true

P false

Q true

true

false

Q false

false

false

P || Q

 

P true

P false

Q true

true

true

Q false

true

false

! P

P true

P false

false

true


* Sources here and here.