1

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:

  1. can only have 1 variable declared per expression
  2. variable declaration must occur first in the expression
  3. must use copy initialization syntax not direct initialization syntax
  4. 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?

Community
  • 1
  • 1
David
  • 27,652
  • 18
  • 89
  • 138

1 Answers1

1

C++03 standard defines selection statement as:

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 additionally adds the following rule:

condition:
    type-specifier-seq attribute-specifieropt declarator braced-init-list

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:

if (int x = 3 && true && 12 > 11) {
    // x == 1 here...

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:

if (int x { 3 && true && 12 > 11 }) {

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 the condition.

MichalR
  • 263
  • 1
  • 6
  • #3 is interesting but that doesn't explain why they prohibit the regular syntax. Also can you elaborate on #4. Why do `()`s stop it from being a declaration? What is it if not a declaration? – David Oct 21 '11 at 13:49