Preventing Changes of Array Arguments in C++ Functions

You can define const array parameter in a function to prevent it from being changed Point in a function.

Passing an array merely passes the starting memory address of the array. The array elements are not copied. This makes sense for conserving memory space. However, using array argu­ments could lead to errors if your function accidentally changed the array. To prevent this, const array       you can put the const keyword before the array parameter to tell the compiler that the array cannot be changed. The compiler will report errors if the code in the function attempts to modify the array.

Listing 7.6 gives an example that declares a const array argument list in the function p (line 4). In line 7, the function attempts to modify the first element in the array. This error is detected by the compiler, as shown in the sample output.

Listing 7.6 ConstArrayDemo.cpp

1 #include <iostream>
2
using namespace std;
3
4
void p(const int list[], int arraySize)
5 {
6   
// Modify array accidentally
7    list[0] = 100; // Compile error!
8 }
9

10 int main()
11 {
12   
int numbers[5] = {1, 4, 3, 6, 8};
13    p(numbers,
5);
14
15   
return 0;
16 }

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *