Hello.
In an inventory of weapons, when I want to equip one, I search for it inside of an array.
If found, return a pointer to the weapon itself.
If not found, return nullptr
I’m testing the case where the weapon isn’t found:
void AMyCharacter::EquipWeapon(EWeaponType toEquip)
{
AWeapon* theWeapon = FindWeapon(toEquip);
if (!theWeapon)
if (GEngine) GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Blue, FString::Printf(TEXT("Sorry, I was not able to find the weapon")));
else
if (GEngine) GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Blue, FString::Printf(TEXT("I found it: it's of type %d"), (uint8)theWeapon->GetWeaponType()));
}
This prints Sorry, I was not able to find the weapon as expected
Now, look at this code:
void AMyCharacter::EquipWeapon(EWeaponType toEquip)
{
AWeapon* theWeapon = FindWeapon(toEquip);
if ( theWeapon && theWeapon->GetIsEnabled() )
{
}
else
{
if (!theWeapon)
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("ERROR: Cannot EquipWeapon() -> theWeapon is nullptr")));
if(!theWeapon->GetIsEnabled())
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("ERROR: Cannot EquipWeapon() -> theWeapon is not enabled, pick it up!")));
else
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("ERROR: Cannot EquipWeapon() -> theWeapon is out of ammo")));
}
}
This code crashes giving this output:
I didn’t expect this to crash.
The if-statement here has two conditions chained with a binary operator &&.
The first is to check whether theWeapon is a valid pointer or not. In this case it’s not, so it should quickly stop going on checking the other conditions: since it’s false and the operator is an AND it has no sense to go ahead.
This is called short evaluation
Here, it seems not to work. From the crash output log I see an access violation in the GetIsEnabled() function.
What does that have to do with it?
That function shouldn’t even have been called since the first condition is false!