The point is that you prevent the function body from altering the value. The function argument is just an automatic variable within the function body and you may want to ensure it remains at its input value. Consider
int foo(int x)
{
/* lots of code */
some_other_func(x); // may modify x
/* even more code */
return x+42; // x may have been modified
}
and
int foo(const int x)
{
/* lots of code */
some_other_func(x); // will not compile if x is taken by non-const reference
/* even more code */
return x+42; // x is guaranteed at its input value
}
As a rule of thumb, declare everything const
that is not meant to be altered. Then, if you or somebody accidentally attempts to alter such a variable, a compile-time error will result.
Note also that the const
declarator has no effect in a function declaration, but only in the function definition, i.e. the following is perfectly fine (in fact recommended):
struct bar
{
int foo(int) const;
/* more code */
};
int bar::foo(const int x) const // possibly in another compilation unit
{
...
}