开发者

Multiple Pointer Test in If Statement

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  
}  开发者_如何学C   

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


Yes, that's ok.

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜