In C++, constants represent fixed values that do not change during the program's execution.
Constants are crucial for defining values that remain constant throughout a program, making code easier to read, maintain, and modify.
1. Defining Constants with const Keyword
The const keyword in C++ allows you to define variables whose values cannot be changed after initialization.
#include <iostream> using namespace std; int main() { const int MAX_USERS = 100; const float PI = 3.14159; cout << "Max users allowed: " << MAX_USERS << endl; cout << "Value of PI: " << PI << endl; // MAX_USERS = 200; // Uncommenting this will cause an error, as MAX_USERS is constant return 0; }
Explanation:
- MAX_USERS and PI are defined as constants using the const keyword.
- Trying to modify MAX_USERS will result in a compilation error because it is constant.
Output:
Max users allowed: 100 Value of PI: 3.14159
2. Constants with constexpr
constexpr is a keyword introduced in C++11 that defines compile-time constants, ensuring that their values can be evaluated at compile time. This is useful for optimizing code.
#include <iostream> using namespace std; constexpr int square(int x) { return x * x; } int main() { constexpr int size = square(5); // Compile-time evaluation cout << "Square of 5: " << size << endl; return 0; }
Explanation:
- square is a constexpr function, meaning its result can be computed at compile time.
- size is initialized with square(5), evaluated at compile time.
Output:
Square of 5: 25
3. Constant Pointers
In C++, pointers can also be made constant in two ways:
- A constant pointer to a variable (int *const ptr): The pointer's address cannot be changed.
- A pointer to a constant variable (const int *ptr): The value at the address cannot be modified.
#include <iostream> using namespace std; int main() { int value1 = 10; int value2 = 20; const int *ptr1 = &value1; // Pointer to a constant int int *const ptr2 = &value1; // Constant pointer to int // *ptr1 = 15; // Error: cannot modify value through ptr1 ptr1 = &value2; // Allowed: ptr1 can point to a different address *ptr2 = 30; // Allowed: ptr2 can modify value1 // ptr2 = &value2; // Error: cannot change address of ptr2 cout << "ptr1 points to: " << *ptr1 << endl; cout << "ptr2 points to: " << *ptr2 << endl; return 0; }
Explanation:
- ptr1 is a pointer to a constant integer (const int *), so it can point to different variables, but cannot modify the value at the pointed address.
- ptr2 is a constant pointer to an integer (int *const), so it can modify the value but cannot point to a different address.
Output:
ptr1 points to: 20 ptr2 points to: 30
4. Constant References
A constant reference (const &) provides read-only access to the referenced variable. This is useful in functions where you want to prevent modification of the passed parameter.
#include <iostream> using namespace std; void displayValue(const int &num) { // num++; // Error: num is a constant reference cout << "Value: " << num << endl; } int main() { int value = 42; displayValue(value); return 0; }
Explanation:
- displayValue accepts a const reference, so it cannot modify num.
- Constant references are efficient for passing large objects without copying them while preventing modifications.
Output:
Value: 42
5. Constants with #define Preprocessor Directive
The #define directive can be used to define constants, though it lacks the type-safety of const.
#include <iostream> #define PI 3.14159 #define MAX_VALUE 100 int main() { std::cout << "Value of PI: " << PI << std::endl; std::cout << "Max value: " << MAX_VALUE << std::endl; // #define lacks scope and type-safety, so avoid it in modern C++ code return 0; }
Explanation:
- #define PI and MAX_VALUE are macros that replace PI and MAX_VALUE with their defined values throughout the code.
- Macros do not obey C++ scope rules and lack type safety, so const or constexpr are generally preferred.
Output:
Value of PI: 3.14159 Max value: 100
6. Using enum for Named Constants
An enum is a user-defined data type that consists of named integer constants, making code more readable.
#include <iostream> using namespace std; enum Day { MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; int main() { Day today = WEDNESDAY; cout << "Today is day number: " << today << endl; return 0; }
Explanation:
- Each enum value represents a constant integer, making it useful for representing options or states.
- By default, MONDAY starts at 1 and increments for each subsequent value.
Output:
Today is day number: 3
7. Constants with const in Classes
The const keyword can be used in classes to define constant member variables and functions that cannot modify the object’s state.
#include <iostream> using namespace std; class Circle { public: const float PI = 3.14159; // Constant member variable float radius; Circle(float r) : radius(r) {} float area() const { // Constant member function return PI * radius * radius; } }; int main() { Circle circle(5); cout << "Area of circle: " << circle.area() << endl; return 0; }
Explanation:
- PI is a constant member variable of the Circle class, and it cannot be modified.
- area is a const member function, meaning it cannot modify any member variables of the object.
Output:
Area of circle: 78.5398
8. Constant Static Members in Classes
Static members of a class can be constant, allowing the constant to be shared among all instances of the class.
#include <iostream> using namespace std; class Constants { public: static const int MAX_USERS = 100; }; int main() { cout << "Max users allowed: " << Constants::MAX_USERS << endl; return 0; }
Explanation:
- MAX_USERS is a static constant member, which is shared across all instances of the class and accessed via ClassName::MAX_USERS.
Output:
Max users allowed: 100
9. Inline Constants with inline and constexpr
In modern C++ (C++17 and later), inline variables can be used to define constants in header files without causing multiple-definition errors.
#include <iostream> using namespace std; inline constexpr int MAX_CONNECTIONS = 10; int main() { cout << "Max connections: " << MAX_CONNECTIONS << endl; return 0; }
Explanation:
- inline constexpr allows MAX_CONNECTIONS to be defined in a header file, making it accessible across multiple translation units without causing linker errors.
Output:
Max connections: 10
10. Summary Table of Constants in C++
Constant Type | Usage Example | Description |
---|---|---|
const | const int MAX = 100; | Constant variable, cannot be modified |
constexpr | constexpr int SIZE = square(5); | Compile-time constant |
Constant Pointer | int *const ptr = # | Pointer that cannot point to a different address |
Pointer to Constant | const int *ptr = # | Pointer that cannot modify the pointed value |
Constant Reference | void func(const int &x) | Reference that cannot modify the referenced value |
#define | #define PI 3.14159 | Preprocessor constant, lacks type safety |
enum | enum Color { RED, GREEN, BLUE }; | Named integer constants |
const in Classes | class Circle { const float PI; }; | Class member constant |
Static Constant in Class | static const int MAX_USERS; | Shared constant across class instances |
inline constexpr | inline constexpr int MAX_CONNECTIONS = 10; | Cross-file constant without multiple-definition errors |
Complete
Example: Using Different Constants in C++
This example demonstrates various constant types in a C++ program.
#include <iostream> #define PI 3.14159 // Define constant with macro using namespace std; class MathConstants { public: static const int MAX_ITERATIONS = 100; // Static constant in class const double GOLDEN_RATIO = 1.61803; // Constant member variable }; enum Direction { NORTH, SOUTH, EAST, WEST }; // Enum constants constexpr int square(int x) { return x * x; } // constexpr function int main() { const int MAX_USERS = 50; // Const variable constexpr int AREA_SIZE = square(4); // constexpr variable inline constexpr int MAX_ITEMS = 5; // inline constexpr variable MathConstants math; cout << "PI: " << PI << "\n"; cout << "Golden Ratio: " << math.GOLDEN_RATIO << "\n"; cout << "Square of 4: " << AREA_SIZE << "\n"; cout << "Max users: " << MAX_USERS << "\n"; cout << "Max items: " << MAX_ITEMS << "\n"; cout << "Max iterations: " << MathConstants::MAX_ITERATIONS << "\n"; cout << "Direction (EAST): " << EAST << endl; return 0; }
Output:
PI: 3.14159 Golden Ratio: 1.61803 Square of 4: 16 Max users: 50 Max items: 5 Max iterations: 100 Direction (EAST): 2
Constants in C++ are useful for defining fixed values that improve code readability, maintainability, and performance.