Programming in C

(Barry) #1
Boolean Variables 89

“off,” its value is 0. But in C, there is an even more convincing argument in favor of
these logic values. It has to do with the way the C language treats the concept of TRUE
and FALSE.
Recall from the beginning of this chapter that if the conditions specified inside the
ifstatement are “satisfied,” the program statement that immediately follows executes.
But what exactly does “satisfied” mean? In the C language, satisfied means nonzero, and
nothing more. So the statement


if ( 100 )
printf ("This will always be printed.\n");


results in execution of the printfstatement because the condition in the ifstatement
(in this case, simply the value 100 ) is nonzero and, therefore, is satisfied.
In each of the programs in this chapter, the notions of “nonzero means satisfied” and
“zero means not satisfied” are used.This is because whenever a relational expression is
evaluated in C, it is given the value 1 if the expression is satisfied and 0 if the expression
is not satisfied. So evaluation of the statement


if ( number < 0 )
number = -number;


actually proceeds as follows:



  1. The relational expression number < 0is evaluated. If the condition is satisfied, that
    is, if numberis less than zero, the value of the expression is 1 ; otherwise, its value
    is 0.

  2. The ifstatement tests the result of the expression evaluation. If the result is
    nonzero, the statement that immediately follows is executed; otherwise, the state-
    ment is skipped.
    The preceding discussion also applies to evaluation of conditions inside the for,
    while, and dostatements. Evaluation of compound relational expressions such as in the
    statement


while ( char != 'e' && count != 80 )


also proceeds as outlined previously. If both specified conditions are valid, the result is 1 ;
but if either condition is not valid, the result of the evaluation is 0 .The results of the
evaluation are then checked. If the result is 0 ,the whileloop terminates; otherwise it
continues.
Returning to Program 6.10 and the notion of flags, it is perfectly valid in C to test if
the value of a flag is TRUE by an expression such as


if ( isPrime )


rather than with the equivalent expression


if ( isPrime != 0 )

Free download pdf