开发者

Multiple Pointer Test in If Statement

开发者 https://www.devze.com 2022-12-17 16:43 出处:网络
considering a pointer to a struct struct a_struct { int A; }; Is it ok to do : struct a_struct *ptr; //...

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

精彩评论

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

关注公众号