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?
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:
xis 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.