Constants in Programming
What is a Constant?
A constant is a value that cannot be changed after it is assigned.
Constants are useful when you have a value that should stay the same while the program runs, like the value of PI, the number of days in a week, or a fixed URL.
Unlike variables, which can be updated, constants keep the same value once they are created:
PI = 3.14159
print(PI)
const PI = 3.14159;
console.log(PI);
final double PI = 3.14159;
System.out.println(PI);
const double PI = 3.14159;
cout << PI;
Try it Yourself »
Why Use Constants?
Using constants makes your code easier to understand and maintain:
- Readability: Names like
PI
orDAYS_IN_WEEK
explain what the number means. - Safety: Constants protect important values from being accidentally changed.
- Easy updates: If you need to change a constant (like a tax rate), you only update it in one place.
Changing a Constant
Once a constant is assigned, trying to change it will usually cause an error or be ignored, depending on the language.
PI = 3.14159
PI = 3 # This works in Python, but it is not recommended
print(PI)
const PI = 3.14159;
PI = 3; // Error: Assignment to constant variable
final double PI = 3.14159;
PI = 3; // Error: cannot assign a value to final variable
const double PI = 3.14159;
PI = 3; // Error: assignment of read-only variable
Try it Yourself »
Note: In Python, there is no built-in way to make a variable constant. The common practice is to write constant names in UPPERCASE
to show other programmers that the value should not change.
Constants in Practice
Here are some common examples of constants:
PI = 3.14159
(The mathematical constant pi)DAYS_IN_WEEK = 7
URL = "https://example.com"
DAYS_IN_WEEK = 7
print("A week has", DAYS_IN_WEEK, "days")
const DAYS_IN_WEEK = 7;
console.log("A week has " + DAYS_IN_WEEK + " days");
final int DAYS_IN_WEEK = 7;
System.out.println("A week has " + DAYS_IN_WEEK + " days");
const int DAYS_IN_WEEK = 7;
cout << "A week has " << DAYS_IN_WEEK << " days";