const
- C++ course
- Beginner
- Lesson 9/116
- 4 min
Learn to declare immutable variables with the const keyword.
const
The const keyword makes a variable immutable. After declaring const int maxUsers = 100;, writing maxUsers = 200; gives a compile error.
const tells the compiler and the reader that this value will not change. This improves reliability and helps the compiler optimize.
Using const for constants is a good habit: const double pi = 3.14159;. Add const wherever you do not want a value to change.
Using const
A const variable must be given a value when declared; it cannot be assigned later. const int x; alone is invalid; const int x = 5; is correct.
The value of a const variable can be determined at runtime. You can hold a function result as a constant: const int y = readValue(); — the value is computed when the program runs but never changes afterward.
If the value is known at compile time, constexpr may be more appropriate; you will see it in the next lesson.
Practice Define constants and print
Inside main, declare two const variables: maxUsers with value 100 (int) and taxRate with value 0.18 (double). Print both with std::cout using std::endl.
Starter code
#include <iostream>
int main() {
// Define constants with const
// Print with std::cout
return 0;
}Sample solution
#include <iostream>
int main() {
// Define constants with const
const int maxUsers = 100;
const double taxRate = 0.18;
// Print with std::cout
std::cout << maxUsers << std::endl;
std::cout << taxRate << std::endl;
return 0;
}Expected output
100 0.18
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Defining a constant
____ double pi = 3.14159;
const double pi = 3.14159;
Explanation: const double pi is an immutable variable.
2 What happens if you reassign a const variable?
const int x = 5;
x = 10;- The value changes
- The program crashes
- A warning is given but it changes
- A compile error is raised Correct answer
Explanation: Reassigning a const variable is a compile error.
3 Match const concepts
| Term | Meaning |
|---|---|
const |
Immutable |
reassignment |
Compile error |
declaration time |
Value given |
optimization |
Helps compiler |