Is this code correct?
void foo ( int* p )
{
if ( int* p2 = p ) // single "="
{
*p2++;
}
}
I always been thinking it's not, but recently i've saw such code in a colleague's of mine sources.
What if "p" is NULL? MS VS 2008 works correct but shows "warning C4706: assignment within conditional expression".
Thank you.
The warning assignment within conditional expression
is usually issued by compilers to prevent cases where you write
if (a = b)
{
where you meant
if (a == b) // big difference!
{
In your sample, the 'assignment warning' is actually bogus, since it is, in fact, not an assignment, but rather an intialization:
{
int *p2 = p;
if (p2)
{
}
}
and there is no risk that you'd actually wanted the syntax error (int *p2 == p
?!) instead :)
The rest of your post is perfectly valid C++03 (and later) and just does what it says1.
1 (which in terms of lasting effect, isn't much because
but I guess that's just the sample code? In case it isn't obvious, *p2++
is equivalent to *p2; p2++;
)
By raising warning C4706, the compiler is simply questioning whether you actually meant to write if ( int* p2 == p )
instead of if ( int* p2 = p )
as shown.
Per 6.4 of the 2003 C++ Standard, if ( int* p2 = p )
is legal:
The value of a condition [
if (condition)
] that is an initialized declaration in a statement other than aswitch
statement is the value of the declared variable implicitly converted to typebool
.
If p
is NULL
, condition (int* p2 = p
) fails because the value of p2
is 0, and thus implicitly false
, and *p2
is not incremented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With