“if”中的变量声明表达追踪
这是 C++,'if' 表达式中的变量声明规则的后续内容
if( int x = 3 && true && 12 > 11 )
x = 1;
(据我所知)是:
- 每个表达式只能声明 1 个变量
- 变量声明必须首先出现在表达式中
- 必须使用复制初始化语法 不 直接初始化语法
- 不能有声明 1 周围的括号
和2 根据这个答案有意义,但我不能看看 3 和 4 有什么理由吗?还有其他人吗?
This is a follow-up to C++, variable declaration in 'if' expression
if( int x = 3 && true && 12 > 11 )
x = 1;
The rules (so far as I can tell) are:
- can only have 1 variable declared per expression
- variable declaration must occur first in the expression
- must use copy initialization syntax not direct initialization syntax
- cannot have parenthesis around declaration
1 and 2 make sense according to this answer but I can't see any reason for 3 and 4. Can anyone else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C++03 标准将选择语句定义为:
C++11 还添加了以下规则:
一般来说,这意味着您可能放在条件中的声明实际上只不过是保留命名的条件表达式的值以供进一步使用,即对于以下代码:
x
计算为:3 &&真&& (12>11)
。回到您的问题:
3) C++11 现在允许您在这种情况下使用直接初始化(带大括号初始化程序),例如:
4) 以下内容:
if ((int x = 1) && true )
根据上面的定义没有意义,因为它不符合条件
的“表达式或声明”规则。C++03 standard defines selection statement as:
C++11 additionally adds the following rule:
Generally it means that the declaration you might put inside the condition is in fact nothing more than keeping the value of the condition expression named for further use, i.e. for the following code:
x
is evaluated as:3 && true && (12 > 11)
.Back to your questions:
3) C++11 allows you now to use direct initialization (with brace initializer) in such case, e.g:
4) The following:
if ((int x = 1) && true)
does not make sense according to the definition above as it does not fit the: "either expression or declaration" rule for thecondition
.