declaration as condition - adding parentheses caus

2019-07-11 17:36发布

问题:

Why is this ok:

if(int i = 1) {
}

...whereas the following produces errors?

if((int i = 1)) {
}

Under g++ (4.4.5) the latter gives:

test.cpp:7: error: expected primary-expression before ‘int’
test.cpp:7: error: expected ‘)’ before ‘int’
test.cpp:9: error: expected ‘)’ before ‘else’
test.cpp:13: error: expected primary-expression before ‘}’ token
test.cpp:13: error: expected ‘;’ before ‘}’ token

Incidentally, the reason I'm asking is because of this answer: Seeing what class an object is

I'm trying to find a way to make the condition more readable. Usually, I would prefer, for example:

if((x = y) != 0) {

to

if(x = y) {

...since it's more readable and silences compiler 'comments' suggesting I might have used the wrong operator. If I'm using a declaration as a condition, it doesn't produce the warning, but the readability still seems to suffer.

回答1:

It's because of the C++ standard, 6.4 p1.

Selection statements choose one of several flows of control.

selection-statement:

if ( condition ) statement
if ( condition ) statement else statement
switch ( condition ) statement

condition:

expression
type-specifier-seq declarator = assignment-expression


回答2:

This is not an assignment. It's a declaration. You can put declarations elsewhere as conditions, as in the following

if(int i = value) ...;
for(...; int i = value; ...) ...;
switch(int i = value) ...;
while(int i = value) ...;

This is a rarely used form, but it isn't an expression specified there. What you have done there is declaring a variable i which you can use in the body

// fire if get() returns non-null
if(weapon *w = get()) {
  w->fire();
}

And parentheses aren't allowed around such a declaration. I think that would make no sense.