|
|
HP C/HP-UX Reference Manual: Version A.05.55.02 > Chapter 6 Statements if |
|
The if statement tests one or more conditions and executes one or more statements according to the outcome of the tests. The if and switch statements are the two conditional branching statements in C. In the first form, if exp evaluates to true (any nonzero value), C executes statement. If exp is false (evaluates to 0), C falls through to the next line in the program. In the second form, if exp evaluates to true, C executes statement1, but if exp is false, statement2 is performed. A statement can be an if or if...else statement. You can test multiple conditions with a command that looks like this: if (exp1) /* multiple conditions */ The important thing to remember is that C executes at most only one statement in the if...else and if...else/if...else constructions. Several expressions may indeed be true, but only the statement associated with the first true expression is executed. Expressions subsequent to the first true expression are not evaluated. For example: /* determine reason the South lost the American Civil War */ All the expressions in the above code fragment could be evaluated to true, but the run-time system would only get as far as the first line and never even test the remaining expressions. Use curly braces ({ }) in a compound statement to indicate where the statement begins and ends. For example: if (x > y) { Braces also are important when you nest if statements. Since the else portion of the statement is optional, you may not have one for an inner if. However, C associates an else with the closest previous if statement unless you use braces to show that isn't what you want. For example: if (month == 12) { /* month = December */ Without the braces, the else would be associated with the inner if statement, and so the no-December message would be printed for any day in December except December 24. Nothing would be printed if month did not equal 12. Nested if statements create the problem of matching each else phrase to the right if statement. This is often called the dangling else problem; the general rule is:
Each if statement, however, can have only one else clause. It is important to format nested if statements correctly to avoid confusion. An else clause should always be at the same indentation level as its associated if. However, don't be misled by indentations that look right even though the syntax is incorrect. /* Program name is "if.else_example". */ If you execute this program, you get the following output: Enter an age: 15 |
|