Question about Protecting from a Null Pointer

Hi,
I would appreciate some clarification on lecture 109, “Protecting from a Null Pointer”:
I am struggling to understand how adding in the pointer “PressurePlate” in the if statement and then following with && for the rest of the condition, will protect against a null pointer?

My understanding is:
The pointer “PressurePlate” has a value saved as an address. So if I add this into the if statement and stating that this address should be the same as the PressurePlate->IsOverlappingActor(ActorThatOpen)

In order for the if statement to execute, how would this be true?
The way I see it, the if statement would require an address value and a bool to be both TRUE to execute, which does not make sense?

Thanks in advance for any help.

Kind Regards
Tiaan Adlem

You can change that statement into:

if(PressurePlate)
{
      if(PresurePlate->IsOverlappingActor(ActorThatOpens)
      {
                  OpenDoor(DeltaTime);
       }
}

It means the same and perhaps it is a little easier to understand.

The first if (or the first part of the if) asks if that PressurePlate exists. if(PressurePlate) doesn’t mean PressurePlate has to be a boolean, only if it exists or not. So, if we haven’t put it in, it would be false, or in other words, the pointer wouldn’t point anywhere ( a null pointer). If there was an address, returns true.

1 Like

It’s due to short-circuit evaluation.

For a logical AND expression if the left hand side is false the right hand side won’t be evaluated because the result is already known to be false, it doesn’t matter what the right hand side is. e.g.

LHS && RHS == Result
LHS RHS Result
false true false
false false false

The same goes for logical OR and true.

LHS || RHS == Result
LHS RHS Result
true true true
true false true

So it protects it by not evaluating - thus dereferencing the pointer - PressurePlate if it is nullptr.

1 Like

Hi @Munsa,

Thanks so much, that makes more sense now.

Kind Regards
Tiaan Adlem

Thanks @DanM for responding,

I understood the & operator, it was just the pressureplate returning a false when it is a nullpointer, which I did not understand. Munsa helped me to understand.

Kind Regards
Tiaan Adlem

Ah right, yes. There are implicit conversions to bool

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer-to-member type can be converted to a prvalue of type bool.
A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.

- https://eel.is/c++draft/conv.bool

1 Like

Thanks DanM :smiley:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms