views:

90

answers:

3

considering a pointer to a struct

struct a_struct  
{   
    int A; 
};  

Is it ok to do :

struct a_struct *ptr;  

//...

if( ptr != NULL && ptr->A == 1)  
{  
    //work with ptr struct  
}     

or should you Test if the pointer is valid before testing for on of its field.

if(ptr != NULL)
{
    if(ptr->A == 1)
    {
        //work with ptr struct
    }
}
+5  A: 

&& evaluates the second test only if the first was successful, so your code (one if statement) is perfectly fine.

Heinzi
+9  A: 

Yes, that's ok.

The && operator short-circuits in C, so ptr->A == 1 will only be evaluated if ptr is non-null.

Stephen Canon
+1  A: 

That will work, and is actually a fairly common idiom. If you write an else clause, you do have to worry about which check kicked you there, but that is no different from any other mult-condition if-check.

T.E.D.