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
}
}
Yes, that's ok.
The && operator short-circuits in C, so ptr->A == 1 will only be evaluated if ptr is non-null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With