以下代码有效吗?如果有的话,范围是什么x
?
int main()
{
if (true) int x = 42;
}
我的直觉告诉我,没有创建任何范围if
因为没有实际的块({}
) 遵循它。
GCC 4.7.2 向我们展示了,虽然代码是valid, 的范围x仍然是简单的条件式 https://ideone.com/MOnO5C.
Scope
这是因为:
[C++11: 6.4/1]:
[..]a 中的子语句选择声明(每个子语句,在else
的形式if
语句)隐式定义了块作用域。[..]
因此,您的代码等效于以下内容:
int main()
{
if (true) {
int x = 42;
}
}
Validity
It's valid就语法而言,因为选择语句的产生式是这样的(通过[C++11: 6.4/1]
):
选择声明:
if
( 状况 ) 陈述
if
( 状况 ) 陈述 else
陈述
switch
( 状况 ) 陈述
and int x = 42;
is a 陈述 (by [C++11: 6/1]
):
statement:
labeled-statement
attribute-specifier-seqopt expression-statement
attribute-specifier-seqopt compound-statement
attribute-specifier-seqopt selection-statement
attribute-specifier-seqopt iteration-statement
attribute-specifier-seqopt jump-statement
declaration-statement
attribute-specifier-seqopt try-block
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)