Tips for using const pointers in C Language -- function for returning pointers

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.