【问题标题】:Variable declaration in 'if' expression follow-up'if' 表达式后续中的变量声明
【发布时间】:2011-12-12 06:33:23
【问题描述】:

这是C++, variable declaration in 'if' expression的后续行动

if( int x = 3 && true && 12 > 11 )
    x = 1;

规则(据我所知)是:

  1. 每个表达式只能声明 1 个变量
  2. 变量声明必须首先出现在表达式中
  3. 必须使用复制初始化语法 不能 直接初始化语法
  4. 声明周围不能有括号

根据this answer,1 和 2 是有道理的,但我看不出 3 和 4 的任何原因。其他人可以吗?

【问题讨论】:

  • 戴夫 - 你为什么要做这么愚蠢的事情?
  • @EdHeal 我不是。这只是一种好奇心。

标签: c++ if-statement variable-declaration


【解决方案1】:

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 的“表达式或声明”规则。

【讨论】:

  • #3 很有趣,但这并不能解释为什么他们禁止使用常规语法。您还可以详细说明#4。为什么()s 阻止它成为声明?如果不是声明,那是什么?
猜你喜欢
  • 2011-12-11
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多