Is "else if" a single keyword?

modeller picture modeller · Jun 23, 2014 · Viewed 10.4k times · Source

I am new to C++. I often see conditional statement like below:

if 
  statement_0;
else if
  statement_1;

Question:

Syntactically, shall I treat else if as a single keyword? Or is it actually an nested if statement within the outer else like below?

if 
  statement_0;
else 
  if
    statement_1;

Answer

Shafik Yaghmour picture Shafik Yaghmour · Jun 23, 2014

They are not a single keyword if we go to the draft C++ standard section 2.12 Keywords table 4 lists both if and else separately and there is no else if keyword. We can find a more accessible list of C++ keywords by going to cppreferences section on keywords.

The grammar in section 6.4 also makes this clear:

selection-statement:
 if ( condition ) statement
 if ( condition ) statement else statement

The if in else if is a statement following the else term. The section also says:

[...]The substatement in a selection-statement (each substatement, in the else form of the if statement) implicitly defines a block scope (3.3). If the substatement in a selection-statement is a single statement and not a compound-statement, it is as if it was rewritten to be a compound-statement containing the original substatement.

and provides the following example:

if (x)
 int i;

can be equivalently rewritten as

if (x) {  
  int i;
}

So how is your slightly extended example parsed?

if 
  statement_0;
else 
  if
    statement_1;
  else
    if
      statement_2 ;

will be parsed like this:

if 
{
  statement_0;
}
else
{ 
    if
    {
      statement_1;
    }
    else
    {
        if
        {
         statement_2 ;
        }
    }
}

Note

We can also determine that else if can not be one keyword by realizing that keywords are identifiers and we can see from the grammar for an identifier in my answer to Can you start a class name with a numeric digit? that spaces are not allowed in identifiers and so therefore else if can not be a single keyword but must be two separate keywords.