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
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
