4

I believe all of you, when learning C, have learned this syntax:

if (condition 1) {
    statements
} else if (condition 2) {
    statements
} ...
else {
    statements
}

But after reading N1570, ยง 6.8.4.1 The if statement, I find absolutely nothing talking about the chained else if statements, unlike other languages that provide keywords like ElseIf or elif for this purpose.

According to my understanding, the whole if(...){...}else{...} is one single statement (the else clause may not be existent, which is irrelevant). So when it comes to parsing, as shown in below codes,

if (condition) {}
else
    one_statement;
if (condition) {}
else
    if (something else) {} else {}

The indented if statement in the second block is equivalent to the indented one_statement; in the first block, in terms of "a syntactic 'statement' unit".

Then, as C allows flexible spacing, any combination of an aggregate positive number of spaces, tabs and newlines are equivalent. So after re-spacing the above code, it turns into

if (condition) {
} else if (something else) {
} else {
}

Is my understanding correct?

iBug
  • 35,554
  • 7
  • 89
  • 134

1 Answers1

2

I find absolutely nothing talking about the chained else if statements

That's because there is nothing special about chaining if statements specifically, as opposed to chaining, say, an if and a loop. Whatever is chained to the end of the else clause becomes part of that else clause in its entirety:

if (x)
    ...
else if (y)
         ...
     else if (z)
             ...
          else
             ...

Above, if (y) belongs to the else branch of if (x), along with the entire chain of statements in its branch. Whitespace does not matter, so the chain can be re-formatted the way you show at the bottom of your question.

Note: C does have to deal with a special case of dangling else, but it happens when ifs are nested, not when they are chained.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523