C++ Constants
In C++, constants are variables whose values cannot be changed once they are initialized. They are a crucial part of writing reliable and maintainable code because they provide guarantees that certain values remain constant throughout the execution of the program. Using constants can help improve code readability and reduce errors that might occur when values are accidentally modified.
This post will cover the following:
const
Keywordconstexpr
KeywordIn C++, constants are typically declared using the const
or constexpr
keyword. These keywords ensure that the variable is treated as a constant, meaning its value cannot be modified after it is initialized.
const
KeywordThe const
keyword is used to define variables whose value is set at initialization and cannot be changed later. This applies to all types of variables (primitive types, objects, arrays, etc.).
const data_type variable_name = value;
Example:
#include <iostream>
using namespace std;
int main() {
const int MAX_SIZE = 100; // Constant integer
cout << "Maximum Size: " << MAX_SIZE << endl;
// Uncommenting the following line would cause an error
// MAX_SIZE = 200; // Error: cannot assign to a const variable
return 0;
}
In this example, MAX_SIZE
is declared as a constant integer with the value 100
. Attempting to modify it later in the code would result in a compile-time error.
const
variable is assigned a value, it cannot be modified.const
variables can be initialized at the time of declaration.constexpr
KeywordThe constexpr
keyword was introduced in C++11 and ensures that the value of a variable is known at compile-time. This makes it ideal for situations where the value is required to be constant during compilation, such as when initializing array sizes or performing certain calculations at compile-time.
constexpr data_type variable_name = value;
Example:
#include <iostream>
using namespace std;
constexpr int getSquare(int n) {
return n * n;
}
int main() {
constexpr int num = 5;
constexpr int square = getSquare(num); // Evaluated at compile time
cout << "Square of " << num << " is: " << square << endl;
return 0;
}
In this example, the value of square
is computed during compilation because num
and getSquare(num)
are both marked as constexpr
. This can improve performance by reducing runtime overhead.
constexpr
variables must have their values known at compile-time.constexpr
can also be evaluated at compile-time if they meet certain conditions (e.g., the function's arguments must be constant expressions).Literal constants are fixed values that are embedded directly into the program code. These include integers, floating-point numbers, characters, and strings. Literal constants do not require a variable declaration and cannot be changed during program execution.
#include <iostream>
using namespace std;
int main() {
cout << "Integer Literal: " << 42 << endl; // Integer constant
cout << "Float Literal: " << 3.14f << endl; // Floating-point constant
cout << "Char Literal: " << 'A' << endl; // Character constant
cout << "String Literal: " << "Hello, World!" << endl; // String constant
return 0;
}
There are several advantages to using constants in C++ programs:
Using constants ensures that certain values cannot be accidentally changed during the program’s execution. This reduces the risk of bugs that can arise from modifying values that should remain fixed.
Constants make the intent of the code clearer. For example, if you use a constant to represent the maximum size of an array, it’s easy for a reader of the code to understand its purpose compared to using a magic number.
const int MAX_HEIGHT = 500;
This is much clearer than simply using 500
directly in the code.
If you need to change a constant value (e.g., the maximum size or the tax rate), you only need to modify it in one place in the code. This makes your code easier to maintain.
In some cases, using constexpr
can allow the compiler to optimize your code better, since the value is known at compile-time. For example, it can be used in array sizes, template parameters, or when precomputing values.
In C++, you can also declare constant pointers and pointers to constants.
A constant pointer is a pointer whose value cannot be changed, i.e., the address it points to cannot be modified, but the content at that address can be changed.
int num = 5;
int* const ptr = # // Constant pointer
*ptr = 10; // Allowed: modifying the value at the address
// ptr = &anotherVar; // Error: cannot change the pointer's address
A pointer to a constant is a pointer that can point to different addresses, but the value at the address cannot be modified.
const int num = 5;
const int* ptr = # // Pointer to constant
// *ptr = 10; // Error: cannot modify the value at the address
ptr = &anotherVar; // Allowed: changing the pointer's address