2

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
    }
}

3 Answers 3

9

Yes, that's ok.

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

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.