是一个声明在if块中有效,没有实际块? [英] Is a declaration valid inside an if block with no actual block?
问题描述
以下代码有效吗?如果是, x
?
)
{
if(true)int x = 42;
}
我的直觉说,没有由
GCC 4.7.2向我们表明,虽然代码有效,范围 x
仍然只是条件。
范围
这是由于:
[C ++ 11:6.4 / 1]:
[..] 选择语句中的子句(每个子句在else
if
语句)隐式定义块范围。 [..]
因此,您的代码相当于以下内容:
int main()
{
if(true){
int x = 42;
}
}
有效性
根据语法,这是有效的,因为选择语句的生产因此是( [C ++ 11:6.4 / 1]
):
>
if
(条件)语句 if
( condition ) statement else
em> 切换
(条件)语句 b $ b 和 int x = 42;
是一个语句 code> [C ++ 11:6/1] ):
:
标记语句
attribute-specifier-seq sub> opt >复合语句
attribute-specifier-seq opt br>
< / em> ;
try-block
Is the following code valid? If so, what is the scope of x
?
int main()
{
if (true) int x = 42;
}
My intuition says that there is no scope created by the if
because no actual block ({}
) follows it.
GCC 4.7.2 shows us that, while the code is valid, the scope of x
is still simply the conditional.
Scope
This is due to:
[C++11: 6.4/1]:
[..] The substatement in a selection-statement (each substatement, in theelse
form of theif
statement) implicitly defines a block scope. [..]
Consequently, your code is equivalent to the following:
int main()
{
if (true) {
int x = 42;
}
}
Validity
It's valid in terms of the grammar because the production for selection statements is thus (by [C++11: 6.4/1]
):
selection-statement:
if
( condition ) statement
if
( condition ) statementelse
statement
switch
( condition ) statement
and int x = 42;
is a statement (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
这篇关于是一个声明在if块中有效,没有实际块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!