Constants
While variables store data that can change, some values should never change. In this lesson, you will learn what constants are, how to define them using const and #define, and why they make your code safer.
Introduction
In the previous lesson, you learned that variables store data whose values can change during program execution. For example, marks may initially contain 80 and later be updated to 90. However, some values should remain unchanged, such as the number of days in a week, mathematical values such as pi, or fixed limits used by an application. Such values are represented using constants. Constants make programs more reliable by preventing accidental modification of important values.
What is a Constant?
A constant represents a value that is not allowed to change after it has been initialized. In simple words, a constant is a fixed value used by a program. Named constants give meaningful names to important values and help communicate that those values should remain unchanged.
Why Do We Need Constants?
Without Constants
- Important values could be modified accidentally.
- Programs become harder to understand and maintain.
- The same hardcoded value may appear in many places.
- Changing an important value may require editing multiple parts of the program.
With Constants
- Protect values that should remain unchanged.
- Improve code readability.
- Reduce accidental programming errors.
- Make programs easier to update and maintain.
Real-World Analogy
Imagine an official standard or rule that must remain fixed. For example, a week always contains seven days. A program may use this value many times, but the value itself should not be changed accidentally. A constant works in a similar way by representing a value that is intended to remain unchanged.
Characteristics of Constants
Constants represent values that should remain unchanged, communicate programmer intent, improve readability, and help prevent accidental modification.
- Represent values that should remain fixed.
- Cannot be modified through the constant name after initialization.
- Can have meaningful names.
- Improve program safety and readability.
- Reduce accidental changes to important values.
Variables vs Constants
| Feature | Variable | Constant |
|---|---|---|
| Value | Can change during execution | Cannot be changed after initialization |
| Usage | Stores changing data | Represents fixed data |
| Assignment | Can usually be assigned new values | Cannot be reassigned through the constant name |
| Purpose | Used for dynamic information | Used for values intended to remain unchanged |
Types of Constants in C++
C++ provides several ways to represent values that remain fixed. The most common forms beginners encounter are literal constants, const-qualified objects, and preprocessor macros.
1. Literal Constants
Values written directly in source code, such as 100, 3.14, 'A', true, and "Hello".
2. const Keyword
Creates a typed object whose value cannot be modified through that object after initialization.
3. #define Directive
Creates a preprocessor macro that performs text replacement before compilation.
100 // Integer literal
3.14 // Floating-point literal
'A' // Character literal
"Hello" // String literal
const double PI = 3.14159;
#define MAX_SIZE 100Memory Representation
Suppose the program contains const int DAYS = 7;. Conceptually, DAYS can be visualized as a named object containing the value 7. The const qualifier prevents the program from modifying that object through the name DAYS after initialization.
Constant: DAYS
Address Value
1000 ─────► 7
DAYS cannot be assigned another value.
(The address shown is only an example.)Example 1: Using const
#include <iostream>
int main()
{
const double PI = 3.14159;
std::cout << PI;
return 0;
}const double PI = 3.14159;
const indicates that PI cannot be modified through this name after initialization. double is the data type, PI is the identifier, and 3.14159 is the initial value.
std::cout << PI;
This sends the value represented by PI to the standard output stream.
3.14159
Example 2: Attempting to Modify a Constant
#include <iostream>
int main()
{
const int DAYS = 7;
DAYS = 10; // ❌ Compilation error
std::cout << DAYS;
return 0;
}DAYS was declared as const, so the program cannot assign another value to it after initialization. The statement DAYS = 10; is therefore rejected by the compiler.
Example 3: Using #define
#include <iostream>
#define MAX_SIZE 100
int main()
{
std::cout << MAX_SIZE;
return 0;
}#define MAX_SIZE 100
This defines an object-like preprocessor macro. During preprocessing, occurrences of MAX_SIZE are replaced with the replacement text 100.
Modern C++ Preference
For typed constants, modern C++ generally prefers const or constexpr because they participate in the language type system and follow normal C++ scope rules.
100
Constants in Real-World Applications
Mathematics
Mathematical values and fixed coefficients used in calculations.
Banking
Configured limits, fixed fee values, and rates that should not change during a particular calculation.
Games
Maximum health limits, level limits, map dimensions, and other fixed game rules.
Educational Systems
Maximum marks, subject limits, and fixed grading thresholds.
Scientific Applications
Physical constants and fixed conversion factors used in calculations.
Advantages of Constants
Constants communicate intent, prevent accidental reassignment, replace unexplained magic values with meaningful names, and make important values easier to manage.
- Prevent accidental modification through the constant name.
- Improve program readability.
- Make programs easier to maintain.
- Replace unexplained magic values with meaningful names.
- Communicate which values are intended to remain unchanged.
Common Beginner Mistakes
A const object cannot be assigned a new value after it has been initialized.
Use a variable when the value needs to change. Use a constant when the value should remain unchanged.
Repeated unexplained values make code difficult to understand. Give important fixed values meaningful names.
Names should explain the purpose of the value. Prefer descriptive names such as MAX_SIZE or TAX_RATE over unclear names such as x or temp.
Preprocessor macros do not behave like typed C++ objects. Prefer const or constexpr for most typed constants in modern C++.
const int x = 10;
x = 20; // ❌ Error// ❌ Bad: the meaning of 3.14159 is repeated directly
double area = 3.14159 * radius * radius;
// ✅ Better: give the value a meaningful name
const double PI = 3.14159;
double area = PI * radius * radius;Best Practices
- Use const for objects that should not be modified after initialization.
- Use meaningful names that explain what each constant represents.
- Follow one consistent naming convention for constants throughout the project.
- Avoid repeating unexplained magic values throughout the code.
- Prefer const or constexpr over preprocessor macros for typed constants.
- Use constexpr when a value should be usable in constant-expression contexts.
- Keep related constants organized logically.
Frequently Asked Questions
What is a constant?
A constant represents a value that is not intended to change after initialization.
Which keyword creates a constant object?
The const keyword is used to declare an object that cannot be modified through that const-qualified object after initialization.
Can a constant be modified?
A const object cannot be assigned a new value through its const-qualified name after initialization.
What is the difference between a variable and a constant?
A variable is intended to hold data that may change, while a constant represents data that should remain unchanged.
What is the difference between const and #define?
const creates a typed C++ object that follows language scope and type rules. #define creates a preprocessor macro that performs text replacement before compilation.
Should modern C++ use #define for constants?
Usually no. For typed constants, const or constexpr is generally preferred. Macros are still useful for specific preprocessor tasks.
Key Takeaways
- Constants represent values that should remain unchanged.
- The const keyword creates const-qualified objects.
- A const object must not be reassigned after initialization.
- Literal constants are fixed values written directly in source code.
- #define creates preprocessor macros rather than typed C++ constants.
- Modern C++ generally prefers const or constexpr for typed constants.
- Meaningful constants make programs safer, clearer, and easier to maintain.
Summary
Constants are an essential part of C++ programming because they represent values that should remain unchanged. By using const and other modern C++ constant mechanisms instead of repeating hardcoded values, programmers can write safer, clearer, and more maintainable code. Understanding constants also prepares you for working with configuration values, fixed limits, mathematical values, and compile-time expressions in larger applications.