quot;ifquot; block without curly braces makes subsequent quot;else ifquot; nested(“如果没有花括号的块会生成后续的“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"嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“如果"没有花括号的块会生成后续的“else


基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01