Mar*_*n G 3 c++ scope if-statement declaration
有没有办法在if构造中声明,赋值和比较变量到表达式,使得它只在if构造的范围内定义?
这是有效的(声明和赋值,但当然条件只是函数f的返回值等于或等于零):
int main()
{
if(int i = f())
{
printf("%d", i);
// i is defined here!
}
else
{
// Here too!
}
// But not here!
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试将i的值与实际表达式进行比较时,我遇到了麻烦:
int main()
{
// Does not compile because "int i = f()" is not a primary expression?
if((int i = f()) == 3)
{
printf("%d", i);
}
}
Run Code Online (Sandbox Code Playgroud)
从行为的角度来看,如果构造类型可以创建整个范围,但在我看来它看起来很难看:
int main()
{
{
int i = f();
if(i == 3)
{
printf("%d", i);
// i is defined here!
}
// here too!
}
// i is not defined here!
}
Run Code Online (Sandbox Code Playgroud)
我正在比较for循环和开关的外观和感觉,它是如此简洁地声明和分配变量,所以它只在相关范围内定义.当然变量的值与那里的任何东西都没有比较,我不是说它是同一个东西:
for(int i = 0;;)
{
break;
}
// i is not defined here
switch(int i = f())
{
default: break;
}
// i is not defined here!
Run Code Online (Sandbox Code Playgroud)
总而言之,有没有办法将变量的定义与"if"的范围联系起来,因为它通常与for和(也许不常见)开关的范围相关联,并且实际上你在哪里将变量的值与表达式进行比较作为if语句的条件?
据我所知,在if语句的条件下无法同时具有声明和表达式.如果我们查看草案C++标准部分Selection语句,if的语法如下:6.4
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condition ) statement
condition:
expression
attribute-specifier-seqopt decl-specifier-seq declarator = initializer-clause
attribute-specifier-seqopt decl-specifier-seq declarator braced-init-list
Run Code Online (Sandbox Code Playgroud)
因此,您可以使用表达式或声明,但我没有看到任何明显的方法.
您在替代方案中提出的建议,i在if语句之前声明似乎是最佳选择.虽然使用封闭块似乎没有必要:
int i = f();
if(i == 3)
Run Code Online (Sandbox Code Playgroud)