Sometimes the difference between a confusing C++ function and a well-designed one is just a single keyword.
That keyword is:
const
Enter fullscreen mode
Exit fullscreen mode
It's easy to overlook, especially when you're starting with C++.
But using const correctly can make your code easier to understand, harder to misuse, and clearer about what a function is allowed to do.
Let's look at why.
1. The problem: unclear function behavior
Imagine seeing this function declaration:
void PrintValues ( std :: vector < int >& values ) ;
Enter fullscreen mode
Exit fullscreen mode
What does this function do?
Does it only print the values?
Does it modify them?
Does it remove elements?
Does it sort the vector?
We can't tell from the declaration alone.
Now consider this:
void PrintValues ( const std :: vector < int >& values ) ;
Enter fullscreen mode
Exit fullscreen mode
This communicates something important:
The function receives the vector by reference, but it cannot modify the vector through that…