This is a fundamental thing that every C++ programmers must know.
const to data
This is the simplest form of pointer definition that we always do.
const int* data3 = arr2; // Const to data data3[0] = 55; // ERROR: Data can't be changed data3 = arr1; // Success: Can't change the pointer to somewhere else
Here the data is can’t changed using data3 pointer. but the pointer itself can be modified and can point to some other location.
Usually we don’t care even if pass the pointer to some function and that pointer changes to some other location, as the function parameters points to same location but the pointer is a copy of actual parameter. But things may go different if we wrongly pass reference to function parameters even it’s const. So we’ve to take care this while designing the interfaces.
void Foo( LPCTSTR& lpszValue )
{
lpszValue = _T( "codereflect.com" );
}
int _tmain(int argc, _TCHAR* argv[])
{
LPCTSTR sz = NULL;
Foo(sz);
_tprintf( sz );
return 0;
}
const to pointer
In this form of usage, the pointer can’t be changed to some location but the data can be changed.
int* const data2 = arr2; // const to pointer data2 = arr1; // Can't change the pointer to somewhere else data2[0] = 55; // SUCCESS: Data can be changed
const to both data and pointer
This is the goodness of both
. The most secure pointer.
const int* const data1 = arr1; // Const to both pointer and data data1 = arr2; // ERROR: can't change the pointer data1[0] = 100; // ERROR: can't change the data