Introduction --
In C, some functions return pointers, that is, the functions that return pointers. Generally, the function implementer does not want the function caller to modify the content pointed to by the pointer.
Solution --
Returns a pointer to the const variable when the function returns. The sample code is as follows:
[Cpp]
# Include "stdafx. h"
Static const int * testPointerToConstVaribles ();
Int _ tmain (int argc, _ TCHAR * argv [])
{
Const int * TestPointer = NULL;
TestPointer = testPointerToConstVaribles ();
Return 0;
}
Const int * testPointerToConstVaribles ()
{
Static int ConstVarible = 100;
Return & ConstVarible; // returns the pointer to the const variable
}
If you try to change the pointer pointing value in the Code, the following error code will occur:
[Cpp]
# Include "stdafx. h"
Static const int * testPointerToConstVaribles ();
Int _ tmain (int argc, _ TCHAR * argv [])
{
Const int * TestPointer = NULL;
TestPointer = testPointerToConstVaribles ();
* TestPointer = 34; // modify the pointer to a value that causes a compilation error.
Return 0;
}
Const int * testPointerToConstVaribles ()
{
Static int ConstVarible = 100;
Return & ConstVarible; // returns the pointer to the const variable
}
The following error occurs when the code above is compiled in VS 2005 (the error code block is "* TestPointer = 34; // modify the value pointed to by the pointer, causing a compilation error ")
"Error C3892: 'testpointer ': you cannot assign to a variable that is const"
Summary
The above scheme can prevent unauthorized modification of pointer pointing values.
From DriverMonkey's column