HP C A.06.05 Reference Manual

Statements
if
Chapter 6 171
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 */
if (day == 25)
printf("Today is Christmas.\n");
}
else
printf("It's not even December.\n");
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.
The Dangling else
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:
•Anelse is always associated with the nearest previous if.
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, do not be misled by indentations that look
right even though the syntax is incorrect.
Example
/* Program name is "if.else_example". */
#include <stdio.h>
int main(void)
{
int age, of_age;
char answer;
/* This if statement is an example of the second form (see
* "Description" section). */
printf("\nEnter an age: ");
scanf("%d", &age);
if (age > 17)
printf("You're an adult.\n");
else {
of_age = 18 - age;