Let's consider such application:
void foo (char* const constPointerToChar) {
// compile-time error: you cannot assign to a variable that is const
constPointerToChar = "foo";
}
int _tmain(int argc, _TCHAR* argv[])
{
char* str = "hello";
foo(str);
printf(str);
return 0;
}
Let's remove const
keyword:
void foo (char* pointerToChar) {
pointerToChar = "foo";
}
int _tmain(int argc, _TCHAR* argv[])
{
char* str = "hello";
foo(str);
printf(str);
return 0;
}
And output is hello
. So even if function is allowed to change pointer it changes it's copy of pointer and original pointer was not changed.
This is expected because pointers are passed by value.
I do understand why things works this way but I do not understand why someone need to declare parameter as X* const
.
When we declare function parameter as X* const
we say that "Ok I promise inside my function i will not modify my own copy of your pointer." But why caller should care what happens with variables he never see and use?
Am I correct that declaring function parameter as X* const
is useless?