Logical Operators
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
}The shortcut
Read left to right and stop at the deciding value: for && stop at the first false, for || stop at the first true.
The values
ammois 0,overheatedis false. Evaluateammo > 0 && !overheated.
A frequent slip is writing & when you meant &&. The single & is a bitwise operator (next lesson); it does not short-circuit, so the guard above would divide by zero.
Drills
Answer fast — trust the rule.
With health = 0 and hasShield = true, what is health > 0 or hasShield?
What is !(3 > 5)?
In rounds > 0 && total / rounds > 50, what happens when rounds is 0?
What is true or false and false?
Which expression always means the same as !(ready && fuelled)?
Remember
&&needs both,||needs one,!flips, and both&&and||stop early.- Shortcut: read left to right and stop at the deciding value.
- Trap:
&is not&&; only the double form short-circuits.
