Const and if statement with initializers

I’m currious about some best practices
I have this method:

bool UMainMenu::Initialize()
{
	bool Success = Super::Initialize();
	if (!Success) return false;

	// TODO: setup

	return true;
}

But Success can be written a little differently:

const bool Success = Super::Initialize(); // added const

or:

if (const bool Success = Super::Initialize(); !Success) return false; // if-init

I’m calling the above style an if-init. What is the Unreal Engine’s best practice? I rarely see const vars or if-inits within UE code(maybe I’m just looking at older code). It makes sense to me that if a var is not modified, then make it const. Additionally, limit the scope of a var with the if-init.

The example above maybe isn’t the best, there’s no reason to save the var if all I’m doing is an early return. What I do see quite often is:

var* Foo = GetFoo();
if (Foo != nullptr)
{
    // do stuff with Foo
}
// other logic

I see code more this way than using an early return. This seems like a perfect setup for if-init to me, and I see this all the time. Is there any reason I don’t typically see it this way:

if (const var* Foo = GetFoo(); Foo != nullptr)
{
    // do stuff with Foo
}
// other logic

Ok. Of the 2 success bool statements, the second is absolutely something that should never be done. Assigning inside an if actually hides what is being done. The scope is limited and that may be desirable but again readability is a factor.

C++ does let you do this that are so wrong and it is important that you avoid these practices.

Compound statements in an if statement is definitely one of these things.

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

Privacy & Terms