40
Chapter 2
Logical Operators
Logical operators evaluate Boolean logic on
bool
types. You characterize
operators by how many operands they take. A
unary operator takes
a single
operand, a
binary operator takes two, a
ternary operator takes three, and so on.
You categorize operators further by describing the types of their operands.
The unary
negation operator (
!
) takes a single operand and returns its
opposite.
In other words,
!true
yields
false
, and
!false
yields
true
.
The logical operators AND (
&&
) and OR (
||
) are binary. Logical AND
returns
true
only if both of its operands are
true
.
Logical OR returns
true
if
either or both of its operands are
true
.
N O T E
When you’re reading a Boolean expression, the
!
is pronounced “not,” as in “a and
not b” for the expression
a && !b
.
Logical operators might seem confusing at first, but they quickly
become intuitive. Listing 2-7 showcases the logical operators.
#include
int main() {
bool t = true;
bool f = false;
printf("!true: %d\n", !t);
u
printf("true && false: %d\n", t && f);
v
printf("true && !false: %d\n", t && !f);
w
printf("true || false: %d\n", t || f);
x
printf("false || false: %d\n", f || f);
y
}
!true: 0
u
true && false: 0
v
true && !false: 1
w
true || false: 1
x
false || false: 0
y
Listing 2-7: A program that illustrates the use of logical operators
Here, you see the negation operator
u
, the logical AND operator
vw
,
and the logical OR operator
xy
.
The std::byte Type
System programmers sometimes work directly with raw memory, which is a
collection of bits without a type. Employ the
std::byte
type, available in the
header, in such situations. The
std::byte
Yüklə 7 Mb.