Using array index wrapping
Sometimes, when you use arrays to store information, you may want to iterate it in both directions and be able to wrap the index so that it doesn’t go beyond the index limit and crash the game. An example of this is the previous/next weapon logic in shooter games, where you have an array of weapons and you want to be able to cycle through them in a particular direction, and when you reach the first or the last index, you want to loop back around to the last and first index, respectively. The typical way of doing this would be as follows:
AWeapon * APlayer::GetPreviousWeapon() { if(WeaponIndex - 1 < 0) { WeaponIndex = Weapons.Num() - 1; } else { WeaponIndex--; } return Weapons[WeaponIndex]; } AWeapon * APlayer::GetNextWeapon() { if(WeaponIndex + 1 > Weapons.Num() - 1) { ...