【问题标题】:if statement without the inner scope?没有内部范围的 if 语句?
【发布时间】:2015-04-29 07:24:08
【问题描述】:

Afaik,代码中的每一对 { } 都会创建一个新范围。即使它只是为了它而使用,没有任何iffor、函数或其他需要它的语句:

void myFun(void)
{
    int a;
    {
        int local;
    }
}

我开始怀疑 - 当 if 语句在不使用大括号(只有 1 行正文)的情况下编写时,它是否仍会创建一个新范围?

voidmyFun(int a)
{
    int b;
    if (a == 1)
        int tmp;   // is this one local to if?
    else
        int tmp2;   // or this one?
    b = 2;   // could I use tmp here?
}

【问题讨论】:

  • 是的,他们是本地的 if 部分
  • "//我可以在这里使用 tmp" - 你尝试了吗?发生了什么,它是否支持或压制了您对前两次询问的想法?
  • 不,我没有。一,因为现在我什至没有可以测试它的环境,二,因为这样的测试并不能说明全部真相 - 它可能适用于我的情况,而不适用于其他人,并且不会给我原因。另外,我认为这对于 SO 的其他用户来说可能是一个有用的问题。

标签: c++ variables if-statement scope


【解决方案1】:

N4140 [stmt.select]/1 读取:

selection-statement 中的子语句(每个子语句,在if 语句的else 形式中)隐式定义块范围

所以,代码

if (a == 1)
    int tmp;   // is this one local to if?
else
    int tmp2;   // or this one?

等价于

if (a == 1)
{
    int tmp;   // yes, this one is local to if
}
else
{
    int tmp2;   // and this one as well
}

【讨论】:

  • 这句话可能来自语言标准吗?您标记了它,但它似乎有一个类型-o。
  • @NPS 是的,它来自 N4140。在以前的标准中,它或多或少是相同的。而且我在这里没有看到任何拼写错误。
  • 我以为它是某种 SO 标签,但猜不是。 :P Nvm。
【解决方案2】:

简而言之 - 是的。这是一个单行范围。

换句话说,写作:

if (someCondition) 
    int i = 7;

在范围方面与写作相同:

if (someCondition) 
{
    int i = 7;
}

【讨论】:

    【解决方案3】:

    是的! tmpif 的本地,tmp2else 的本地。如果您尝试在外部使用tmptemp2,您应该得到变量未定义错误。这是因为,

    if(<condition>) <my-statment> 
    if(<condition>) 
    { 
      <my-statment> 
    }
    

    对于编译器来说,两者是相等的。

    【讨论】:

    • 不错:测试变量是否已定义将一劳永逸地结束整个讨论。
    【解决方案4】:

    是的,即使 if 和 for 没有 {},其中声明的变量也是它的本地变量。

    所以,如果你尝试类似的东西

    if ( something )
        int a = 3;
    std::cout << a;  // there is no other identifier called a in your program
    

    它不会编译,因为它和

    if ( something )
    {
        int a = 3;
    }
    std::cout << a;
    

    你会得到一个未在此范围内声明的变量错误。

    所以,

    voidmyFun(int a)
    {
        int b;
        if (a == 1)
            int tmp;   // is this one local to if?   Ans:-  Yes
        else
            int tmp2;   // or this one?          Ans:- It is local to else block
        b = 2;   // could I use tmp here?      Ans:-  No
    }
    

    因此,else (tmp2) 中的变量是 else 的本地变量,而不是 if 的本地变量。

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      相关资源
      最近更新 更多