Make pointer and reference arguments const

This tip submitted by Akshay on 2010-10-16 18:30:10. It has been viewed 15689 times.
Rating of 5.1 with 139 votes

When you write a function that takes a pointer or a reference, and you do not plan to modify the original object pointed to or referred to, you should make your argument const:

int addValues (const int *array, int n)
    int sum = 0;
    for ( int i = 0; i < n; i++ ) 
        sum += array[ i ];
    return sum;

This makes it clear that the function will not change the value of the original array, and it also prevents accidental modifications.

You can learn more about using const in this tutorial on const correctness in C++.

More tips

Help your fellow programmers! Add a tip!