“if”没有花括号的块使得随后的“else if”嵌套 [英] "if" block without curly braces makes subsequent "else if" nested

查看:307
本文介绍了“if”没有花括号的块使得随后的“else if”嵌套的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AFAIK,如果没有提供if块,那么大括号中只有1个语句。例如

  if(..)
statement_1;
statement_2;

不考虑制表符,只考虑 statement_1



以下代码不符合:

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

上述代码不打印任何东西。它应该已经打印true

它显示为,如果嵌套在 如果块中。 g ++ -Wall 问题警告,但这不是这里的问题。



为什么会出现这种不同的行为?

[GCC demo:无大括号带大括号]。


<这个行为实际上并不一样,它是完全一致的:整个内部如果块 - 包括 else if - 被视为一个

块。



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



尾部 else



大多数语言通过(任意)决定块由解析器贪婪匹配来解决歧义 - 即 else 如果

,则 [ >

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;

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

Following code doesn't get along with that:

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

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.

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

解决方案

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.

这篇关于“if”没有花括号的块使得随后的“else if”嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆