Lesson 73: Constants
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Give numbers a name
- A constant is a named value that never changes while the program runs:
const int GREEN_PIN = 7; - A variable can change: a count, a reading, a score.
- Constants make a program maintainable: easy for you, or another programmer, to understand and change later.
| Feature | Why it helps |
|---|---|
| constants | change a value in one place; the name says what it means |
| meaningful names | GREEN_TIME says more than t2 |
| comments | explain what each part of the program does |
| procedures and functions | showLight does one job; the program is split into parts |
In the exam
- 0478/21/M/J/23 Q6: two features of a maintainable program, with a reason for each. Mark scheme: meaningful identifiers, so programmers can easily recognise each variable, constant or array; comments, so a programmer knows the purpose of each section; procedures and functions, to make the program modular and easier to update.
- 0478/22/F/M/23 Q4: describe how variables and constants are used. Mark scheme: both store data and are accessed by an identifier; the value of a variable may change while the program runs; the value of a constant stays the same.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
The traffic lights were moved to pins 5 (red), 6 (amber) and 7 (green). The sketch has the old numbers 11, 12 and 13 in nine places. Make three constants at the top, const int RED_PIN = 5; and so on, and use their names everywhere instead of the numbers.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
New timings: red for 2000 ms, green for 1500 ms, amber for 500 ms. Add three constants, RED_TIME, GREEN_TIME and AMBER_TIME, and use them in the delay calls.
Click Run to see the output here.