問題描述
這是怎么回事?
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 標(biāo)準(zhǔn)中的第 6.4.3 節(jié)解釋了在選擇語句條件中聲明的變量如何具有擴(kuò)展到由條件控制的子語句末尾的范圍.但我沒有看到它在哪里說明不能在聲明周圍加上括號,也沒有說明每個條件只有一個聲明.
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 設(shè)置為 false 的情況下進(jìn)入 'if'-body 范圍,則聲明需要括號(因?yàn)橘x值運(yùn)算符的優(yōu)先級低于邏輯 OR),但由于不能使用括號,因此需要聲明的 x 體外,將該聲明泄漏到比預(yù)期更大的范圍.顯然這個例子是微不足道的,但更現(xiàn)實(shí)的情況是 a 和 b 是返回需要測試的值的函數(shù)
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
那么我想做的事情不符合標(biāo)準(zhǔn),還是我的編譯器只是在破壞我的球(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.
}
注意使用;
而不是,
來分隔聲明和實(shí)際情況.
Note the use of ;
of instead of ,
to separate the declaration and the actual condition.
這篇關(guān)于C++,'if' 表達(dá)式中的變量聲明的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!