Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking null pointer && pointer->member value in the same if statement

This is a pretty basic question, but I could not find a clear answer: is it allowed to check that a pointer is not null and (&&) to also check one of its members value in the same if statement?

Rephrased: is the right part of the condition in the example below even evaluated if f is null?

I know this works in VS current version, but what I need to know is if this is allowed by the C++ standard (or if it's UB). Also, if I write it as 2 separate if to make it more readable, can I expect the compiler to optimize it into a single if?

struct foo 
{
   bool bar;
};

void main(){
   foo *f;
   // DO THINGS 
   if (f != null && f->bar == true)
   {
      // DO THINGS
   }
}

Edit: the question is different from this one because it's not obvious that it's simply a matter of order: the proof is I did not end on that SO answer when I googled my question.

like image 681
L.C. Avatar asked Feb 01 '26 19:02

L.C.


1 Answers

...is it allowed to check that a pointer is not null and (&&) to also check one of its members value in the same if statement?

It's perfectly valid, it is not UB, the expression is evaluated from left to right, if the left part of the expression evaluates to false the right part is not evaluated. This is usually called operator short circuit.

The rationale is that if the first part is false, there is no possibilty of the whole expression being true, false && false is false, false && true is also false.

...if I write it as 2 separate if to make it more readable, can I expect the compiler to optimize it into a single if?

In light of the above answer, you wouldn't need two ifs, I would argue that it will not make your code more readable, I prefer the way you have it right know, in any case this is only my opinion. About the compiler, I wouldn't think that there will be much difference either way, as sampled in this live demo.

like image 143
anastaciu Avatar answered Feb 03 '26 09:02

anastaciu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!