8.3 - Constants & Variables
Understanding constants and variables
In programming, data values need to be stored and managed effectively. These values can be held as either constants or variables, each serving different purposes based on whether the value needs to remain fixed or can change during program execution.
Constants and variables are linked to specific memory locations in a computer's RAM. The amount of memory allocated depends on the data type of the value.
Key differences between constants and variables
- Constants - These are data values set at the design stage of a program and cannot be altered once the program is running. Attempting to change a constant will trigger an error from the interpreter or compiler.
- Variables - These hold data values that can be updated multiple times during program execution, making them essential for dynamic calculations and user interactions.
This distinction allows programmers to protect fixed values while enabling flexibility where needed.
Declaring and using variables
Variables are fundamental in programs because they allow data to change, supporting tasks like calculations or storing user input.
Declaring variables in different programming languages
The way variables are declared varies by language, but the goal is to assign a value and, in some cases, specify its data type.
Examples of variable declaration:
-
In languages like pseudocode (such as OCR Exam Reference Language), the data type is automatically inferred from the assigned value:
pressure = 45– Here,pressureis treated as an integer because 45 is a whole number.temperature = 28.3–temperaturebecomes a real data type due to the decimal part.
-
In statically-typed languages, such as Java, you must explicitly declare the data type before assigning a value:
int pressure = 45– Declarespressureas an integer and assigns 45.real temperature = 28.3– Declarestemperatureas a real number and assigns 28.3.
Failing to declare a variable when required leads to a syntax error, which is a mistake in the code's structure that prevents the program from running.
Initialising variables
It is good practice to initialise variables by giving them a starting value, often 0, to avoid unexpected behaviour.
Declaring and using constants
Constants ensure that certain values remain unchanged, which is useful for fixed quantities like mathematical constants or game rules.
How to declare constants
Constants are typically declared using a special keyword, and their value is set once at the beginning.
For example, in JavaScript-like syntax:
- Once declared, any attempt to reassign the value (e.g.,
distance = 80) will cause an error. - This protects the value from accidental changes during runtime.
Constants are assigned during the program's design phase, making them ideal for values that should stay consistent.
Naming conventions for constants and variables
Following standard naming rules helps make code readable and prevents errors. These conventions are common across many programming languages.
Rules for naming
- Start with a lowercase letter (e.g.,
totalScoreinstead ofTotalScore). - Use a mix of letters, numbers, and underscores (e.g.,
player_1_points). - Avoid spaces – use underscores or camelCase (e.g.,
numberOfWins). - Do not start with a number (e.g.,
2ndPlaceis invalid; usesecondPlaceinstead).
These guidelines improve code clarity and maintainability, allowing other programmers to understand the purpose of each constant or variable easily.
Identifying constants and variables in programs
Programs often combine constants and variables to perform tasks. Recognising them helps in debugging and improving code.
Example program: Calculating athletics points
Consider a program for a multi-event athletics competition where athletes earn 5 points for first place and 2 for second. Otherwise they get 0 points. The program calculates total points based on user input.
Original program (in Python-like syntax):
- Here,
firstsandsecondsare variables that store user input, which can change each time the program runs. - The numbers 5 and 2 are hardcoded values, but they could be made constants for better design.
Rewriting with initialisation
To make the program more robust, initialise variables to 0:
firstsandsecondsare variables, assumed to be integers based on the context.- Initialising them ensures they start with a known value.
Benefits of using constants for maintainability
Using constants for fixed values enhances program quality, especially for values that might need updating in the future.
Reasons to use constants
- They don't need to be changed during the running of the program - Constants like points values (e.g., 5 for first place) do not need to vary while the program runs, preventing unintended modifications.
- Easier updates - If the points awarded for each event was changed, you'd only need to change the value given when assigning the constant. This improves maintainability, which is the ease of updating and fixing programs.
For example, rewrite the athletics program with constants: