Logical Operators
The logical operators AND, OR and NOT combine true-or-false conditions, and AND and OR stop evaluating as soon as the answer is certain.
Trace short-circuit conditions and the expressions they skip.
The rocket may fire only if it has ammo and is not overheated. The shield activates if the player picked up a shield or has a shield power-up. Conditions like these are built from three small operators, and one of their habits, stopping early, is a safety feature you will lean on constantly.
The rule
&& needs both, || needs one, ! flips — and both stop early.
a && bis true only if both are true. (You may also writeand.)a || bis true if at least one is true. (You may also writeor.)!aflips true to false and false to true. (You may also writenot.)
Comparisons such as >, == and != produce a bool, so they plug straight in:
bool canFire = ammo > 0 && !overheated;
bool shielded = hasShieldPickup || shieldTimer > 0;Precedence: ! binds tightest, then &&, then ||. So a || b && c means a || (b && c). Add parentheses whenever you mix them; the next reader will thank you.
Short-circuiting: evaluation goes left to right and stops the moment the answer is known. false && anything is false, so the right side is skipped. true || anything is true, so the right side is skipped. That lets the left side guard the right:
if (rounds > 0 && total / rounds > 50) {
// safe: the division only runs when rounds is not zero
}