“如果"没有花括号的块会生成后续的“else

时间:2023-03-21
本文介绍了“如果"没有花括号的块会生成后续的“else if"嵌套的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AFAIK,如果没有为if"块提供大括号,则只考虑其中的 1 条语句.例如

AFAIK, if an "if" block is not provided the curly braces then only 1 statement is considered inside it. e.g.

if(..)
  statement_1;
  statement_2;

不考虑选项卡,在 if 块中只考虑 statement_1.

Irrespective of tabs, only statement_1 is considered inside the if block.

以下代码与此不符:

int main ()
{
  if(false)  // outer - if
    if(false)  // nested - if
      cout << "false false
";
  else if(true)
    cout << "true
";
}

以上代码不打印任何内容.它应该打印 "true".
它出现在 else if 自动嵌套在 outer if 块内.g++ -Wall 发出警告,但这不是这里的问题.放入花括号后,一切都会按预期进行.

Above code doesn't print anything. It should have printed "true".
It appears as of the else if is automatically nested inside the outer if block. g++ -Wall issues warning, but that is not the question here. Once you put the curly braces, everything goes fine as expected.

为什么会有如此不同的行为?
[GCC 演示:不带大括号和带大括号].

Why such different behavior ?
[GCC demo: without braces and with braces].

推荐答案

行为实际上并没有什么不同,它完全一致:整个内部 if 块 – 包括 else if – 被视为一个块.

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

这是解析中的经典歧义,称为dangling-else 问题":当语法写在正常的BNF中时,有两种有效的解析方式:

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:

尾随的 else 要么是外部块的一部分,要么是内部块的一部分.

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

大多数语言通过(任意)决定块被解析器贪婪地匹配来解决歧义 - 即 else [if] 被分配给最接近的 如果.

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.

这篇关于“如果"没有花括号的块会生成后续的“else if"嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!