在if语句的条件部分定义一个变量? [英] Defining a variable in the condition part of an if-statement?
问题描述
我只是震惊,这是允许的:
I was just shocked, that this is allowed:
if( int* x = new int( 20 ) )
{
std::cout << *x << "!\n";
// delete x;
}
else
{
std::cout << *x << "!!!\n";
// delete x;
}
// std:cout << *x; // error - x is not defined in this scope
因此,这是标准允许的还是只是一个编译器扩展?
So, is this allowed by the standard or it's just a compiler extension?
PS由于对此有几个意见 - 请忽略此示例是坏或危险的。我知道什么。
P.S. As there were several comments about this - please ignore that this example is "bad" or dangerous. I know what. This is just the first thing, that came to my mind, as an example.
推荐答案
这是允许的
From Section 6.4 "Selection statements":
由条件中的声明引入的名称(由类型说明符seq或条件的声明者引入)在其声明点到由条件控制的子句结束之间的范围内。 / p>
A name introduced by a declaration in a condition (either introduced by the type-specifier-seq or the declarator of the condition) is in scope from its point of declaration until the end of the substatements controlled by the condition.
以下示例来自同一部分:
The following example is from the same section:
if (int x = f()) {
int x; // ill-formed, redeclaration of x
}
else {
int x; // ill-formed, redeclaration of x
}
这篇关于在if语句的条件部分定义一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!