“if” block without curly braces makes subsequent “else if” nested

时光总嘲笑我的痴心妄想 提交于 2019-11-30 06:14:56

The behaviour isn’t actually different, it’s entirely consistent: the whole inner if block – including else if – is considered as one block.

This is a classical ambiguity in parsing, known as the “dangling-else problem”: there are two valid ways of parsing this when the grammar is written down in the normal BNF:

Either the trailing else is part of the outer block, or of the inner block.

Most languages resolve the ambiguity by (arbitrarily) deciding that blocks are matched greedily by the parser – i.e. the else [if] is assigned to the closest if.

BenW

Because the else is actually being grouped with the inner if, not the outer one. It's actually being parsed as

int main ()
{
  if(false)  // outer - if (never gets executed)
  { 
    if(false)  // nested - if
    {
        cout << "false false\n";
    } else if(true) {
        cout << "true\n";
    }
  }
}

You can solve the problem by explicitly putting the braces where you want them.

It shouldn't print anything. It is the equivalent to this, since the second if/else if is one block that belongs to the first if:

  if(false) {
    if(false)  // nested - if
      cout << "false false\n";
    else if(true)
      cout << "true\n";
  } 

It is quite natural from the C parser viepoint.

The parser, while parsing if-statement, parses the condition expression first, then parses the first statement after condition, then looks for else keyword and, if the else presents, parses the second (alternative) statement.

However, the first statement is an if-statement too, so the parser calls the "if-parser" recursively (before testing for else keyword!). This recursive call parses the inner if-else statement completely (including else), and moves token position "past the end" of the whole code fragment.

Any attempt to implement alternative behaviour should involve some additional communication between "outer" and "inner" if-parsers: the outer parser should inform the "inner" not to be greedy(i.e. not to eat the else statement). This would add additional complexity to the language syntax.

else statement always attaches to nearest if. Without branches nested if itself does not form meaningful statement, so parser goes on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!