Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C For Dummies 2nd Ed 2004.pdf
Скачиваний:
43
Добавлен:
17.08.2013
Размер:
8.34 Mб
Скачать
/* use fpurge(stdin) in unix */

Chapter 14: Iffy C Logic 183

A logical AND program for you

The following source code demonstrates how a logical AND operation works. It’s another — the final — modification to the BLOWUP series of programs:

#include <stdio.h>

int main()

{

char c,d;

printf(“Enter the character code for self-destruct?”); c=getchar();

fflush(stdin);

printf(“Input number code to confirm self-destruct?”); d=getchar();

if(c==’G’ && d==’0’)

{

printf(“AUTO DESTRUCT ENABLED!\n”); printf(“Bye!\n”);

}

else

{

printf(“Okay. Whew!\n”);

}

return(0);

}

Start editing with the source code from BLOWUP3.C if you like, or just enter this code on a blank slate. Save the final result to disk as BLOWUP4.C.

Compile. Fix any errors. Run.

You know the codes from entering the source code: Big G and Zero. Both must be typed at the keyboard to properly authorize the computer to blow up. Cinchy.

This program uses the fflush(stdin) command (in Line 9) to clear input from the first getchar() function. Refer to Chapter 13 for more information on why this command is needed.

If you’re using a Unix-like operating system, substitute fpurge(stdin) for Line 9. Again, refer to Chapter 13.

The logical AND operator && ensures that both variables c and d must equal the proper values for that part of the if statement to be true.

184 Part III: Giving Your Programs the Ability to Run Amok

You can also test for a little G by making the following change to Line 14 in your editor:

if(c==’G’ || c==’g’ && d==’0’)

First, variable c is compared with either G or g — either one can be true. Then, that result is compared with d==0, which must be true. If either of the first comparisons is false, or if the last comparison is false by itself, the entire statement is false. Funky.