Any difference between if (HitActor) and if (HitActor != nullptr)?

I swear we learned this earlier in the course but I can’t remember if there is meaningful difference where I wouldn’t want to do the first one.

I wondered the same thing.
So I did a test.

No meaningful difference.

This was with the PhysicsHandle, but the same
if (!PhysicsHandle)
if (PhysicsHandle == nullptr)

I erased the PhysicsHandle from the actor in UE4.
The same error message in the log was generated both time.

Also, changing the header file from
UPhysicsHandleComponent* PhysicsHandle = nullptr;
UPhysicsHandleComponent* PhysicsHandle;
changed nothing.

I could still have the cpp code doing if (!PhysicsHandle) or if (PhysicsHandle == nullptr) and even if I didn’t explicitly give that variable a nullptr in the header file, everything would still work.

1 Like

Pointers are convertible to bool. From the C++ standard:

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.

Personally I find if (Pointer) and if (!Pointer) far more readable as

if (Pointer != nullptr)

is a double negative (!= + nullptr) which I find harder to parse and often have to double take that I read that correctly. Whereas testing the pointer directly reads naturally in English “if I have a thing, do something with it”.

1 Like

I agree completely yeah. That’s how I read it in my mind too.

Thanks for the responses guys, helps a ton.

Opposite for me as when I see !Pointer I have to figure out of its really a boolean or something else. If you don’t have any other code in there for Pointer then you would have to figure out what it is or assume its of boolean.

Whereas with != null, that doesn’t happen as I know its not.

So there’s plus and minus. Do what you want. Just another instance where either way someone won’t like your code lol :wink:

You could probably get around that by naming all booleans a certain way like BoolSomething or BSomething. Or whatever. Or just deal with it lol.

I’m not sure why that would matter for a condition in an if? And typically you can just hover over it if it does (though I can’t think of a situation where it would).

If you are adhering to Unreal’s coding standards then that’s bSomething

1 Like

Its just an extra thing. I like to be able to look at the code and nothing else (no mouse hovers, no finding, etc) as much as possible. A lot of times its always something more you know. Always something lol.

But yeah, it can be argued both ways possibly to infinity. I’m stopping here :wink:

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

Privacy & Terms