bool foo( int* p )
{
return false;
}
int* bar ( )
{
int* p;
return p;
}
int main() {
if ( int* p = bar() && foo( p ) )
//if ( ((int* p = bar()) != NULL ) && (foo( p )) ) // another variant
{
}
return 0;
}
I get error: cannot convert ‘bool’ to ‘int*’ in initialization with GCC 4.3.4 and VS 2008. If there is only if ( int* p = bar()) everything works fine.
I know i can initialize p before if-statement, but i’m interested in the variant i shown.
The syntax of an
ifrequires a condition in the parentheses. Acondition can be either an expression, or a declaration (of a
type with an implicit conversion to
bool); it cannot be a combinationof these. In the case of
, the condition is “
int* p = bar() && foo( p )“, which is a simpledeclaration of a type
int*initialized withbar() && foo( p ); sincethe type of
bar() && foo( p )isn’tint*, and can’t be implicitlyconverted into an
int*, you have an error.If you write:
, the opening parentheses mean that this cannot be a declaration (simple
or no), and
int* p = bar()isn’t a legal (sub-)expression.The critical point to remember is that you can have a declaration, or
you can have an expression, but that you can’t combine them, and the C++
doesn’t allow declarations as part of an expression. (Also: the
declaration must have copy initialization:
, direct initialization is not allowed.)