Pointer to the const object

Source: Internet
Author: User

If the pointer points to a const object, you cannot use the pointer to change the const value. To ensure this feature, the C ++ language requires that the pointer to the const object must also have the const feature.

Therefore, assigning the address of a const object to a common const object causes non-const object pointers to cause compilation errors:

Const double Pi = 3.14;

Double * PTR = & PI; // Error

Const double * cptr = & PI; // OK

You cannot use the void * pointer to save the address of the const object. Instead, you must use the const void * pointer to save the address of the const object:

Assign the address of a non-const object to the pointer to the const object. However, any attempt to use the const object pointer to repair this non-const object will result in a compilation error. Once defined, the const Object Pointer cannot be used to modify the value of the object. But it does not indicate that this non-const object cannot be modified.

If the object pointed to by the const pointer is not const, you can directly assign a value to the object or indirectly use a common non-const pointer to modify its value: after all, this value is not Const.

# Include <iostream> using namespace STD; void main () {char STR [] = "hello"; const char * P = STR; STR [0] = 'X '; // P [0] = 'X'; // cout <STR <Endl; cout <* P <Endl; cout <p [0] <Endl; cout <p <Endl ;}

In vc6.0

Char * P = "hello ";

Such statements can be run. P points to a String constant, but the pointer P is not defined as a const object. However, the default pointer P is a pointer to a const object. The pointer P cannot be used to modify a String constant or a String constant. (Only for the vc6.0 compiler, because different compilers have different storage and processing methods for string constants, such as P [0] = 'X'; statements may run in tc2.0. Since different compilers support different string constants, it is best not to modify string constants)

My personal summary: Welcome to shoot bricks!

 

 

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.