Variables and constants
Storage with a name. Variable can change; constant cannot.
A variable is a named storage location whose value CAN CHANGE while the program runs. Use for things that may take different values over time — user input, counters, totals, current state.
A constant is a named storage location whose value DOES NOT CHANGE after it's set. Use for fixed values:
- Mathematical constants (π = 3.14159...).
- Configuration limits (MAX_USERS = 100, VAT_RATE = 0.20).
- Magic numbers (DAYS_IN_WEEK = 7) — replacing them with named constants makes code self-documenting.
Why prefer constants when possible.
- Self-documenting (
circumference ← 2 * PI * radiusreads better thancircumference ← 2 * 3.14159 * radius). - Single source of truth — change in one place if the value updates.
- Compiler / interpreter can prevent accidental modification.
Cambridge tip. Mark scheme expects the precise distinction: variable = changeable, constant = fixed. Don't say 'constants are like variables but...'.
- Variable: value changes.
- Constant: value stays fixed.
- Constants are self-documenting and safer.