08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4 ■ Programs with Selection Logic

4.2.3 NOT, !

If p is some Boolean expression, then NOT p reverses the truth value of p. In others words, if p is

true then NOT p is false; if p is false then NOT p is true. In C, the symbol for NOT is the exclamation

mark, !. Using the example above, since

n >= 1 && n <= 12

tests for valid n, the condition NOT (n >=1 && n <= 12) tests for invalid n. This is written in C as

!(n >= 1 && n <= 12)

This is equivalent to n < 1 || n > 12. Those familiar with de Morgan’s laws will know that

not (a and b) = (not a) or (not b)

and

not(a or b) = (not a) and (not b)

In general, if p and q are Boolean expressions, we have the following:

• p && q is true when both p and q are true and false, otherwise;

• p || q is true when either p or q is true and false only when

both p and q are false;

• !p is true when p is false and false when p is true.

This is summarized in the following table (with T for true and F for false):

P q && || !p

T T T T F

T F F T F

F T F T T

F F F F T

Most of the programs in this book will use simple conditions. A few will use compound

conditions.

4.2.3.1 The data type bool in C99

The original C standard and the later ANSI C standard did not define a Boolean data type.

Traditionally, C has used the concept of the value of an expression to denote true/false. A numeric

expression can be used in any context where a true/false value is required. The expression is

considered true if its value is nonzero and false if its value is zero.

68

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!