C++ basics

Hello, help a newbie understand the basics. I display the number on the screen in two ways.
Option 1.
MyPawn.h

UCLASS()
class VOPROS_API AMyPawn : public APawn
{
	GENERATED_BODY()

public:
	// Sets default values for this pawns properties
	AMyPawn();

	int var;
	void F1();
	void F2();

MyPawn.cpp

// Called when the game starts or when spawned
void AMyPawn::BeginPlay()
{
	Super::BeginPlay();
	F1();
}
	
void AMyPawn::F1()
{
	var = 10;
	F2();
}

void AMyPawn::F2()
{
	GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Cyan, FString::FromInt(var));
}

Option 2.
MyPawn.h

UCLASS()
class VOPROS_API AMyPawn : public APawn
{
	GENERATED_BODY()

public:
	// Sets default values for this pawns properties
	AMyPawn();

	void F1();
	void F2(int value);

MyPawn.cpp

// Called when the game starts or when spawned
void AMyPawn::BeginPlay()
{
	Super::BeginPlay();
	F1();
}
	
void AMyPawn::F1()
{
	int var = 10;
	F2(var);
}

void AMyPawn::F2(int value)
{
	GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Cyan, FString::FromInt(value));
}

Which option is better, and which option is more correct?

Hi @Starik_AC -

The question regarding correctness is subjective and likely to prompt any number of responses based on the developer’s personal experience and background.

Syntactically, both options are fine. However, it is important to note that while the debug output is the same in both cases, you are doing something fundamentally different between the two implementations. It comes down to scope.

In the first example, you are declaring the variable on the class itself. This means that the variable essentially belongs to the class and can be accessed on the instance of that class for the entire duration of its lifetime.

In the second example, the variable is declared within your F1 function, so as soon as that function completes, the variable goes away.

Keeping that in mind, it ultimately just depends on what your objective is. I will say though, that since the variable falls out of scope in the second option the F1 function seems redundant. It’s functionally the same as doing the following.

void AMyPawn::BeginPlay()
{
     Super::BeginPlay();
     F2(10);
}

I hope that helps and good luck in your programming adventures.

1 Like

I read that passing parameters to a function as in the second option slows down the program. And creating a global variable as in the first option increases the amount of memory required for the program to run. This is where this question arose.