Nearly all of the other answers are correct, but they miss one aspect of this: When you use the extra const
on a parameter in a function declaration, the compiler will essentially ignore it. For a moment, let's ignore the complexity of your example being a pointer and just use an int
.
void foo(const int x);
declares the same function as
void foo(int x);
Only in the definition of the function is the extra const
meaningful:
void foo(const int x) {
// do something with x here, but you cannot change it
}
This definition is compatible with either of the declarations above. The caller doesn't care that x
is const
--that's an implementation detail that's not relevant at the call site.
If you have a const
pointer to const
data, the same rules apply:
// these declarations are equivalent
void print_string(const char * const the_string);
void print_string(const char * the_string);
// In this definition, you cannot change the value of the pointer within the
// body of the function. It's essentially a const local variable.
void print_string(const char * const the_string) {
cout << the_string << endl;
the_string = nullptr; // COMPILER ERROR HERE
}
// In this definition, you can change the value of the pointer (but you
// still can't change the data it's pointed to). And even if you change
// the_string, that has no effect outside this function.
void print_string(const char * the_string) {
cout << the_string << endl;
the_string = nullptr; // OK, but not observable outside this func
}
Few C++ programmers bother to make parameters const
, even when they could be, regardless of whether those parameters are pointers.