这是 C++ 的后续,'if' 表达式中的变量声明
if( int x = 3 && true && 12 > 11 )
x = 1;
规则(据我所知)是:
- 每个表达式只能声明 1 个变量
- 变量声明必须首先出现在表达式中
- 必须使用复制初始化语法 而不是 直接初始化语法
- 声明周围不能有括号
根据这个答案,1 和 2 是有意义的,但我看不出 3 和 4 的任何理由。其他人可以吗?
这是 C++ 的后续,'if' 表达式中的变量声明
if( int x = 3 && true && 12 > 11 )
x = 1;
规则(据我所知)是:
根据这个答案,1 和 2 是有意义的,但我看不出 3 和 4 的任何理由。其他人可以吗?
C++03 标准将选择语句定义为:
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condituion ) statement
condition:
expression
type-specifier-seq attribute-specifieropt declarator = initializer-clause
C++11 还添加了以下规则:
condition:
type-specifier-seq attribute-specifieropt declarator braced-init-list
通常,这意味着您可能放在条件中的声明实际上只不过是保留条件表达式的值以供进一步使用,即以下代码:
if (int x = 3 && true && 12 > 11) {
// x == 1 here...
x
被评估为:3 && true && (12 > 11)
。
回到你的问题:
3) C++11 现在允许您在这种情况下使用直接初始化(使用大括号初始化器),例如:
if (int x { 3 && true && 12 > 11 }) {
4)以下:if ((int x = 1) && true)
根据上面的定义没有意义,因为它不符合:“表达式或声明”规则condition
。