0

I was just curious about the else if statement in C so I looked at the C99 standard and found nothing. Then I looked at the grammar but again no else if

selection_statement
    : IF '(' expression ')' statement
    | IF '(' expression ')' statement ELSE statement
    | SWITCH '(' expression ')' statement
    ;

How is the else if declared in C. By reading the standard, how can I notice it is part of it?

nowox
  • 25,978
  • 39
  • 143
  • 293

2 Answers2

3

C 2018 6.8.4 says a selection-statement may be “if ( expression ) statement else statement”. C 2018 6.8 says that latter statement may be “selection-statement”, and so it may be an if or if … else statement, which results in a statement containing else if.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • It might help to point out that this would be different in a language where subclauses of control flow constructs had to be blocks. Nobody wants to write a long if-else chain like `if (expression) { statements; } else { if (expression2) { statements; } else { if (expression3) { statements; } else { ... } } }`. – zwol Aug 27 '20 at 18:52
2

The else if statement is officially defined as byproduct of the if statement in §6.8.4/1, C18 by declaring the syntax:

Syntax

1 selection-statement:

if ( expression ) statement

if ( expression ) statement else statement

Source: C18, §6.8.4/1

The last "statement" in the latter form describes that another if statement can be followed after an else.


Beside that, you can find an, of course non-normative, example of its use in the C standard in normative appendix G in the code example at G.5.1/8:

if (isnan(x) && isnan(y)) { ... }
else if ((isinf(a) ||isinf(b)) && isfinite(c) && isfinite(d)) { ... }
else if ((logbw == INFINITY) && isfinite(a) && isfinite(b)) { ... } 

This is the only place where an else if statement appears as it is in the C18 standard.

So regarding:

By reading the standard, how can I notice it is part of it?

There at least although examples are non-normative it is part of it.