C ++,“if”表达式中的变量声明 [英] C++, variable declaration in 'if' expression

查看:668
本文介绍了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 expains 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)
{

}

如果我想输入'if'-body范围,其中x设置为false,那么声明需要括号(因为赋值运算符的优先级低于逻辑或),但是由于括号不能使用它需要在体外​​声明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)?

语句可以是表达式或单个变量声明(带初始化)。

The condition in an if or while statement can be either an expression, or a single variable declaration (with initialisation).

示例既不是有效表达式也不是有效声明,因为声明不能形成表达式的一部分。虽然能够像第三个例子一样编写代码会很有用,但需要对语言语法进行重大更改。

Your second and third examples are neither valid expressions, nor valid declarations, since a declaration can't form part of an expression. While it would be useful to be able to write code like your third example, it would require a significant change to the language syntax.


我没有看到它说什么关于不能围绕声明的括号,也不说任何关于每个条件只有一个声明。

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.

6.4 / 1中的语法规范给出了以下条件:

The syntax specification in 6.4/1 gives the following for the condition:

condition:
    expression
    type-specifier-seq declarator = assignment-expression

指定单个声明,或其他装饰。

specifying a single declaration, with no parentheses or other adornments.

这篇关于C ++,“if”表达式中的变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆