是一个声明在if块中有效,没有实际块? [英] Is a declaration valid inside an if block with no actual block?

查看:80
本文介绍了是一个声明在if块中有效,没有实际块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码有效吗?如果是, 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 the else form of the if 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 ) statement else 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屋!

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