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.