by Dinesh Thakur Category: Array

If we desire that the elements of a vector should not be modified, we can declare that vector as a const vector. However, we must initialize this vector when it is declared, as it is not possible to modify it subsequently. Thus, a const vector can be declared and initialized as shown below.

const int mdays[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30,31, 30, 31};

If we subsequently modify any element of this vector, the compiler gives an error. The compiler also gives a warning when this array is passed to a function that accepts a non const vector.

Now we need to understand the use of const arrays as function parameters. As we know, the use of the pass by reference mechanism makes an array parameter an input-output parameter. Modifications to an array parameter actually causes the corresponding array argument in the calling function to be modified. This may not be desirable in some situations.

In several situations we do not want a function to modify the given array argument. This can of course be written as a comment at the beginning of the function. However, it does not guarantee that we (or some one else) will not modify the array inside the function. To avoid any inadvertent modification to the argument array, we should use a const array. For example, the ivec_print function (Example 9.6a) used to print the elements of a given array does not and inadvertently should not modify the given array. Thus, we can use a const array as shown below (function body is omitted to save space):

void ivec_print(const int x[], int n) { ... }

Now if the function inadvertently modifies one or more array elements (directly or through some function call), the compiler will be able to catch the error. This feature is very useful and prevents the occurrence of several hard to trace bugs.

Note that as in case of a scalar variable, we can pass a const or non-const array as an argument where a const array parameter is expected. However, the compiler gives a warning when we pass a const array where a non-canst array parameter is expected.

Finally note that while using a non-const array parameter, if we wish to modify the elements of the parameter array within a function without affecting the argument array, we will need to use a local copy of the array in the called function.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles