C++,'if' 表达式中的变量声明

这是怎么回事?

if(int a = Func1())
{
    // Works.
}

if((int a = Func1()))
{
    // Fails to compile.
}

if((int a = Func1())
    && (int b = Func2()))
)
{
    // Do stuff with a and b.
    // This is what I'd really like to be able to do.
}

2003 标准中的第 6.4.3 节解释了在选择语句条件中声明的变量如何具有扩展到由条件控制的子语句末尾的范围.但我没有看到它在哪里说明不能在声明周围加上括号,也没有说明每个条件只有一个声明.

Section 6.4.3 in the 2003 standard explains how variables declared in a selection statement condition have scope that extends to the end of the substatements controlled by the condition. But I don't see where it says anything about not being able to put parenthesis around the declaration, nor does it say anything about only one declaration per condition.

即使在条件中只需要一个声明的情况下,这个限制也很烦人.考虑一下.

This limitation is annoying even in cases where only one declaration in the condition is required. Consider this.

bool a = false, b = true;

if(bool x = a || b)
{

}

如果我想在 x 设置为 false 的情况下进入 'if'-body 范围,则声明需要括号(因为赋值运算符的优先级低于逻辑 OR),但由于不能使用括号,因此需要声明的 x 体外,将该声明泄漏到比预期更大的范围.显然这个例子是微不足道的,但更现实的情况是 a 和 b 是返回需要测试的值的函数

If I want to enter the 'if'-body scope with x set to false then the declaration needs parenthesis (since the assignment operator has lower precedence than the logical OR), but since parenthesis can't be used it requires declaration of x outside the body, leaking that declaration to a greater scope than is desired. Obviously this example is trivial but a more realistic case would be one where a and b are functions returning values that need to be tested

那么我想做的事情不符合标准,还是我的编译器只是在破坏我的球(VS2008)?

So is what I want to do non-conformant to the standard, or is my compiler just busting my balls (VS2008)?

推荐答案

从 C++17 开始,您想要做什么 终于有可能:

As of C++17 what you were trying to do is finally possible:

if (int a = Func1(), b = Func2(); a && b)
{
    // Do stuff with a and b.
}

注意使用;而不是来分隔声明和实际情况.

Note the use of ; of instead of , to separate the declaration and the actual condition.

相关文章