Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating and verifying a pointer into "if" statement

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.

like image 747
fogbit Avatar asked Dec 01 '22 01:12

fogbit


2 Answers

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

  • p2 is dereferenced without ever doing something with it
  • p2 is incremented without ever doing something with it,

but I guess that's just the sample code? In case it isn't obvious, *p2++ is equivalent to *p2; p2++;)

like image 157
sehe Avatar answered Dec 05 '22 02:12

sehe


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 a switch statement is the value of the declared variable implicitly converted to type bool.

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.

like image 22
Gnawme Avatar answered Dec 05 '22 01:12

Gnawme