Comparisons
and Logic
Six operators in C are for making
logical comparisons. The relevance of these operators will quickly become clear
in the next chapter, which is about decisions and comparisons. The six
operators which compare values are:
==
is equal to
!=
is not equal to
>
is greater than
<
is less than
>=
is greater than or equal to
<=
is less than or equal to
These operators belong to the second
group according to the scheme above but they do actually result in values so
that they could be thought of as being a part of the first group of operators
too. The values which they produce are called true and false. As words,
"true" and "false" are not defined normally in C, but it is
easy to define them as macros and they may well be defined in a library file:
#define
TRUE 1
#define
FALSE 0
Falsity is assumed to have the value
zero in C and truth is represented by any non-zero value. These comparison
operators are used for making decisions, but they are themselves operators and
expressions can be built up with them.
1
== 1
has the value "true"
(which could be anything except zero). The statement:
int
i;
i
= (1 == 2);
would be false, so i
would be false. In other words, i would be zero.
Comparisons are often made in pairs
or even in groups and linked together with words like OR and AND. For instance,
some test might want to find out whether:
(A is greater than B) AND (A is greater
than C)
C does not have words for these
operations but gives symbols instead. The logical operators, as they are
called, are as follows:
&&
logical AND
||
logical OR inclusive
!
logical NOT
The statement which was written in
words above could be translated as:
(A > B) && (A > C)
The statement:
(A
is greater than B) AND (A is not greater than C)
translates to:
(A > B) && !(A > C)
Shakespeare might have been
disappointed to learn that, whatever the value of a variable tobe
the result of
thequestion = tobe || !tobe
must always be true. The NOT
operator always creates the logical opposite: !true is false and !false
is true. On or the other of these must be true. thequestion is
therefore always true. Fortunately this is not a matter of life or death!
0 comments:
Post a Comment