Formally correct (in C ++, but not in C). Resolution definition as a condition added with dynamic_cast
to support things like:
if ( Derived* p = dynamic_cast<Derived*>( ptrToBase ) ) {
The argument was that there would never have been a moment when p
was in scope but not null. After if
, p
no longer in scope.
The argument does not contain water, because, on the one hand, if you add else
, in the else
block p
is in scope and null. And the justification for limiting the volume is really not very strong anyway, because if the function is long enough for it to matter, the function is too long and too complicated. This design supports things like:
if ( Derived1* p = dynamic_cast<Derived1*>( ptrToBase ) ) {
But this is really not what you want to do in good code.
In general, I would avoid the construct by replacing it with something like:
int* p2 = p; if ( p2 != NULL ) {
It is more explicit and readable. This means that p2
is in scope outside of if
, but I would say that if this causes any problems, the function itself needs to be refactored because it is too long and too complex.
EDIT:
As for the warning: this is complete idiocy by the compiler. There are no assignments in the conditional expression: there is no assignment, period, and there is no conditional expression "the condition in the original is an announcement, not an expression. If the compiler wanted to warn something (in style because he agrees with me that this is a bad style), then this should warn of implicit conversion to bool
. (And, of course, whether this warning should be emitted should be controlled by the option. The compiler should compile the language, and not impose a style, if only one asks it to explicitly warn about special style problems.)