In C++, data type bool
is
used to represent Boolean data. Each bool
constant or variable contains one of
two values:true
or false
.
true
and false
are two C++ constants.
true
has the value 1.
false
has the value 0.
If a testing expression is not of bool
type,
it is coerced to bool
type automaticaly when it is
evaluated.
A nonzero value is coerced to true
and a zero value is coerced to false
.
Relational Operators | |
---|---|
C++ Symbol | Description |
== | equal to |
!= | not equal to |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
number1 < number2is evaluated to
true
if the value stored in number1
is
less than the value stored in number2
, and evaluated to
false
otherwise.
When a relational operator is applied between variables of type char
,
the assertion is in terms of where the two operands fall in the collating
sequence of a particular character set.
For example,
character1 < character2is evaluated to
true
if the value stored in character1
comes
before the character stored in character2
in the collating sequence
of the machine on which the expression is being evaluated. You can think of
collating sequence as being in alphabetic order to help you understand it.
The ASCII character set is widely used as a collating sequence.
A simple Boolean expression is either a Boolean variable or a Boolean constant or an expression involving the relational operators that evaluates to either true or false. These simple Boolean expressions can be combined using logical operations defined on Boolean values. There are three Boolean operators: AND, OR and NOT. Here is a table showing how they are used in C++.
Logical Operators | |
---|---|
C++ Symbol | Description |
&& |
The and Boolean operator:
|
|| |
The or Boolean operator:
|
! |
The not Boolean operator.
|
If relational operators and Boolean operators are combined in the same
expression in C++, the Boolean operator NOT !
has the highest precedence,
the relational operators have the next highest precedence, and the Boolean
operators AND &&
and OR ||
have the lowest. Expressions in parentheses
are always evaluated first.
The following table summarizes the precedence of all the C++ operators we have seen so far.
Highest Precedence | ( ) | | ++x --x | | ! Unary + Unary - | | * / % | | + - | | << >> | | < <= > >= | | == != | | && | | || | | = | | x++ x-- | V Lowest Precedence
Operators in the same line in the table have the same precedence. If an expression contains several operators with the same precedence, most of the operators group from left to right. Some operators have different precedence based on where variables are in relation to them, for these an x represents the variable.
© Department of Computer Science, University of Regina.