Programming Fundamentals/Constants and Variables
Overview
[edit | edit source]A constant is a value that cannot be changed by the program during normal execution, in other words, 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, in other words, the value is variable.
Discussion
[edit | edit source]Understanding Constants
[edit | edit source]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
|
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
[edit | edit source]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; let value = 3;
|
Python | value = 3
|
Swift | var value:Int = 3
|
Key Terms
[edit | edit source]- 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.