Constants and Variables
Kenneth Leroy Busbee and Dave Braunschweig
Overview
A constant is a value that cannot be altered by the program during normal execution, i.e., the value is constant. When associated with an identifier, a constant is said to be “named,” although the terms “constant” and “named constant” are often used interchangeably. This is contrasted with a variable, which is an identifier with a value that can be changed during normal execution, i.e., the value is variable.[1]
Discussion
Understanding Constants
A constant is a data item whose value cannot change during the program’s execution. Thus, as its name implies – the value is constant.
A variable is a data item whose value can change during the program’s execution. Thus, as its name implies – the value can vary.
Constants are used in two ways. They are:
- literal constant
- defined constant
A literal constant is a value you type into your program wherever it is needed. Examples include the constants used for initializing a variable and constants used in lines of code:
21 12.34 'A' "Hello world!" false null
In addition to literal constants, most textbooks refer to symbolic constants or named constants as a constant represented by a name. Many programming languages use ALL CAPS to define named constants.
Language | Example |
---|---|
C++ | #define PI 3.14159 or const double PI = 3.14159; |
C# | const double PI = 3.14159; |
Java | const double PI = 3.14159; |
JavaScript | const PI = 3.14159; |
Python | PI = 3.14159 |
Swift | let pi = 3.14159 |
Technically, Python does not support named constants, meaning that it is possible (but never good practice) to change the value of a constant later. There are workarounds for creating constants in Python, but they are beyond the scope of a first-semester textbook.
Defining Constants and Variables
Named constants must be assigned a value when they are defined. Variables do not have to be assigned initial values. Variables once defined may be assigned a value within the instructions of the program.
Language | Example |
---|---|
C++ | double value = 3; |
C# | double value = 3; |
Java | double value = 3; |
JavaScript | var value = 3; |
Python | value = 3 |
Swift | var value:Int = 3 |
Key Terms
- constant
- A data item whose value cannot change during the program’s execution.
- variable
- A data item whose value can change during the program’s execution.