A constant array is an array whose values cannot be modified after initialization. This is achieved by using the const
keyword in conjunction with the array declaration. Declaring an array as constant ensures that its elements remain read-only, providing safety and preventing accidental modifications.
To create a const array in C++, you need to use the const
keyword before the array declaration. Here’s a simple example:
const int arr[5] = {1, 2, 3, 4, 5};
In this example, the elements of the array arr
are declared as const
, meaning they cannot be changed after initialization.
You can access elements of a const array just like any other array, but trying to modify them will result in a compilation error:
#include <iostream>
int main() {
const int arr[5] = {1, 2, 3, 4, 5};
// Accessing elements
std::cout << "Element at index 2: " << arr[2] << std::endl;
// Attempting to modify elements (uncommenting the line below will cause an error)
// arr[2] = 10; // Error: assignment of read-only location
return 0;
}
const
communicates the intention that the array should not be modified.const
can sometimes allow the compiler to perform optimizations, leading to more efficient code.Constant Array of Integers
const int numbers[3] = {10, 20, 30};
Constant Array of Strings
const char* messages[2] = {"Hello", "World"};
Constant 2D Array
const int matrix[2][2] = {
{1, 2},
{3, 4}
};
You can also declare constant arrays using the C++ Standard Library’s std::array
:
#include <array>
#include <iostream>
int main() {
const std::array<int, 3> myArray = {1, 2, 3};
// Attempting to modify will result in a compile-time error
// myArray[0] = 10; // Error
std::cout << "Element at index 1: " << myArray[1] << std::endl;
return 0;
}
Const Array: Declares all elements in the array as read-only.
const int arr[5] = {1, 2, 3, 4, 5}; // All elements are const
Const Pointer to Array: The pointer is constant, but the values can still be modified.
int arr[5] = {1, 2, 3, 4, 5};
int* const p = arr; // p is a const pointer, but elements of arr can be modified