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

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

Save the file back to disk.

Compile TAXES.C. Run the final result. The output is the same because the program hasn’t changed (and assuming that it hasn’t gotten any warmer and you haven’t grown any taller in the past few moments). What you have done is to create an if-else structure, which is another way to handle the decisionmaking process in your C programs.

The else keyword is a second, optional part of an if cluster of state­ ments. It groups together statements that are to be executed when the condition that if tests for isn’t true.

Or else what?

Alas, if you enter the same values as in the old program, you still owe the same bundle to Uncle Sam.

Covering all the possibilities with else

The if-else keyword combination allows you to write a program that can make either-or decisions. By itself, the if keyword can handle minor deci­ sions and execute special instructions if the conditions are just so. But when if is coupled with else, your program takes one of two directions, depend­ ing on the comparison if makes. Figure 12-2 illustrates how this can happen.

Program execution

printf("whatever");

?if(chins>3)

True {

printf("Where is your neck?");

 

}

 

else

False

{

printf("My, but what a slender neck.");

 

}

Figure 12-2:

printf("something else");

 

How if and else affect a program.

Chapter 12: C the Mighty if Command 159

If the comparison is true, the statements belonging to the if statement are executed. But, if the comparison is false, the statements belonging to the else are executed. The program goes one way or the other, as illustrated in Figure 12-2. Then, after going its own way, the statement following the else’s final curly brace is executed, like this: “You guys go around the left side of the barn, we’ll go around the right, and we’ll meet you on the other side.”

The if format with else

The else keyword is used in an if statement. The keyword holds its own group of statements to be executed (okay, “obeyed”) when the if compari­ son isn’t true. Here’s the format:

if(comparison)

{

statement(s);

}

else

{

statement(s);

}

The if keyword tests the comparison in parentheses. If it’s a true comparison — no foolin’ — the statements that appear in curly braces right after the if statement are executed. But, if the comparison is false, those statements following the else keyword and enclosed in curly braces are executed. One way or another, one group of statements is executed and the other isn’t.

The else keyword, like all words in the C language, is in lowercase. It isn’t followed by a semicolon. Instead, a set of curly braces follows the else. The curly braces enclose one or more statements to be run when the comparison that if makes isn’t true. Notice that those statements each must end in a semicolon, obeying the laws of C first etched in stone by the ancient Palo Altoites.

The statements belonging to the else keyword are executed when the condi­ tion that the if keyword evaluates is false. Table 12-2 illustrates how it works, showing you the opposite conditions for the comparisons that an if keyword would make.

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

Table 12-2

if Comparisons and Their Opposites

if Comparison

else Statement Executed By This Condition

<

>=

(Greater than or equal to)

 

 

 

==

!=

(Not equal to)

 

 

 

>

<=

(Less than or equal to)

 

 

 

<=

>

(Greater than)

 

 

 

>=

<

(Less than)

 

 

 

!=

==

(Is equal to)

 

 

 

I don’t know about you, but I think that all those symbols in Table 12-2 would certainly make an interesting rug pattern.

The else keyword is used only with if.

Both if and else can have more than one statement enclosed in their curly braces. if’s statements are executed when the comparison is true; else’s statements are executed when the comparison is false.

To execute means to run. C programs execute, or run, statements from

the top of the source code (the first line) to the bottom. Each line is executed one after the other unless statements like if and else are encountered. In that case, the program executes different statements, depending on the comparison that if makes.

When your program doesn’t require an either-or decision, you don’t have to use else. For example, the TAXES program has an either-or deci­ sion. But, suppose that you’re writing a program that displays an error message when something doesn’t work. In that case, you don’t need else; if an error doesn’t occur, the program should continue as normal.

If you’re the speaker of another programming tongue, notice that the C

language has no end-else word in it. This isn’t smelly old Pascal, for goodness’ sake. The final curly brace signals the end of the else state­ ment, just as it does with if.

The strange case of else-if and even more decisions

The C language is rich with decision making. The if keyword helps if you need to test for only one condition. True or false, if handles it. And, if it’s true, a group of statements is executed. Otherwise, it’s skipped over. (After the if’s group of statements is executed, the program continues as before.)

Chapter 12: C the Mighty if Command 161

Silly formatting trivia

The if-else structure need not be heavyladen with curly braces. Just as you can abbre­ viate an if statement to one line, you can also abbreviate else. I don’t recommend it, which is why I’m terribly brief and don’t ever show a program that illustrates examples this crudely:

if(tax1>tax2)

{

printf(“You owe $%i in taxes.\n”,tax1*10);

}

else

{

printf(“You owe $%i in taxes.\n”,tax2*10);

}

In this example, you see the meat and potatoes of the TAXES.C program: the if-else struc­ ture. Because both if and else have only one statement belonging to them, you can abbrevi­ ate the source code this way:

if(tax1>tax2)

printf(“You owe $%i in taxes.\n”,tax1*10);

else

printf(“You owe $%i in taxes.\n”,tax2*10);

This format keeps the indenting intact, which is one way to see what belongs to what (and also to easily identify the if-else structure). The following format is also possible, though it makes the program hard to read:

if(tax1>tax2) printf(“You owe $%i in taxes.\n”,tax1*10);

else printf(“You owe $%i in taxes.\n”,tax2*10);

Everything is scrunched up on two lines; the if statement has its own line, and the else has its own line. Both lines end with a semicolon, which is how this works as two statements in the C language. But, look-it. It’s gross! Please don’t write your programs this way.

You can do this trick — eliminating the curly braces — whenever only one statement appears with an if or else keyword. If multi­ ple statements must be executed, you’re required by law to use the curly braces. That’s why I recommend them all the time: No sense risking prison over brevity. To wit:

if(tax1>tax2)

printf(“You owe $%i in taxes.\n”,tax1*10);

else

{

printf(“You owe $%i in taxes.\n”,tax2*10); printf(“It pays to live where it’s cold!\n”);

}

Because two printf statements belong to the preceding else, the curly braces are required.

Either-or conditions are the daily bread of the if-else duo. Either way, one set of statements is executed and not the other, depending on the compari­ son made by if.

What about “one, two, or the third” types of decisions? For them, you need the miraculous and overly versatile else-if combination. It really drives you batty, but it’s handy.

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

The following program is a modification of the GENIE1.C source code, as shown earlier in this chapter. This time, the else-if combination is used to allow the computer genie to accurately report whether the number is less than 5, equal to 5, or greater than 5:

#include <stdio.h> #include <stdlib.h>

int main()

{

char num[2]; int number;

printf(“I am your computer genie!\n”);

printf(“Enter a number from 0 to 9:”); gets(num);

number=atoi(num);

if(number<5)

{

printf(“That number is less than 5!\n”);

}

else if(number==5)

{

printf(“You typed in 5!\n”);

}

else

{

printf(“That number is more than 5!\n”);

}

printf(“The genie knows all, sees all!\n”); return(0);

}

Start working on this source code by loading the GENIE1.C source code I show you how to create earlier in this chapter. Make modifications so that the latter part of the program looks like the new, GENIE2.C source code that was just listed.

Watch your indenting. Pay attention to everything; two equal signs are in the else-if comparison. Pay attention to where semicolons go and where they don’t go.

After inserting the new lines, save the file to disk as GENIE2.C.

Compile GENIE2.C. If the error monster rears its ugly head, reedit the source code and then recompile.