If I have the following setup:

Point* MyPoint = Object->GetMyPoint();

if(MyPoint->GetValue() != 2)
  do something;
else
  do something else;

If MyPoint is NULL or invalid, the MyPoint->GetValue() will cause a segfault.

This should fix it:

Point* MyPoint = Object->GetMyPoint();
if(MyPoint)
{
  if(MyPoint->GetValue() != 2)
    do A;
  else
    do B;
}
else
  do B;

But that is quite awkward, as it makes me repeat B and it adds an extra nested layer.

Is there a better way to do this?

Thanks,

Dave

If I have the following setup:

Point* MyPoint = Object->GetMyPoint();

if(MyPoint->GetValue() != 2)
  do something;
else
  do something else;

If MyPoint is NULL or invalid, the MyPoint->GetValue() will cause a segfault.

This should fix it:

Point* MyPoint = Object->GetMyPoint();
if(MyPoint)
{
  if(MyPoint->GetValue() != 2)
    do A;
  else
    do B;
}
else
  do B;

But that is quite awkward, as it makes me repeat B and it adds an extra nested layer.

Is there a better way to do this?

Thanks,

Dave

This would be the simplest way of doing it:

Point* MyPoint = Object->GetMyPoint();
if(MyPoint && MyPoint->GetValue() != 2)
    do A;
else
    do B;

Cheers for now,
Jas.

If memory serves, if the left hand condition fails it won't bother evaluating the right hand one.
(depending on how the AND is evaluated...I think it gets evaluated left to right, so I'm pretty certain that if the first condition fails, it will ignore the 2nd condition and just return false! However if it is evaluated right to left, then you could simply swap the conditions over!)

Alternatively if your code is in a function you could do this:

Point* MyPoint = Object->GetMyPoint();

// if pointer is not valid, return...
if(!MyPoint)
    return with an error condition/value;

// if we get this far, the pointer is valid
if(MyPoint->GetValue() != 2)
    call function A;
else
    call function B;

return success condition/value;

Cheers for now,
Jas.

Edited 7 Years Ago by JasonHippy: smelling pistakes and tpyos

Yup, as suspected; logical AND is evaluated left to right, so if the 1st condition fails / is false, then the 2nd condition is ignored and the logical AND operation returns false. The 2nd condition is only evaluated if the 1st condition is true.

So my original post should be fine!

Cheers for now,
Jas.

Edited 7 Years Ago by JasonHippy: n/a

This article has been dead for over six months. Start a new discussion instead.