Mismatching if and else Statements

In nested if statements, each else is associated with the closest preceding if statement that does not have an else. Although indentation can make nested constructs more readable, it has no syntactical effect:

if( val > 5 )

if( count == 10 )

val = sample;

else

val = 0;

The indentation suggests that the else associates with the first if. In fact, the else is part of the second if, as shown more clearly here:

if( val > 5 )

if( count == 10 )

val = sample;

else

val = 0;

The else is part of the second if statement—the closest preceding if that doesn't have a matching else. To tie the else to the first if, you must use braces:

if( val > 5 )

{

if( count == 10 )

val = sample;

}

else

val = 0;

Now the else belongs with the outermost if. Remember, indentation is meaningful only to humans. The compiler relies strictly on punctuation when it translates the source file.