Const and pointer modify const object

Source: Internet
Author: User

We all know that the const object is used to declare a variable as a constant. It cannot be modified unless the conversion is displayed in the program.

This article reminds you of an implicit error and a solution to this problem.

Consider the following code:

# Include <iostream> int main () {const int A = 0; int * P = const_cast <int *> (& A); // & A returns int *, const_cast <int *> display to int *. * p = 1; int B = * P; int c = A; STD: cout <"B:" <B <STD: Endl <"C: "<C <STD: Endl; STD: cout <& A <" "<p <STD: Endl; return 0 ;}

 

The output result is:

B: 1

C: 2

0x7fffe27cd63c 0x7fffe27cd63c

The problem is here! We obviously changed the value of A, and the address pointed to by the pointer is the same as the address of the variable.

This is so horrible. We changed the value of a through * P, but the result of the next use of a remains unchanged. This reminds us again that we should not use forced type conversion easily, which will often lead to some errors that we cannot perceive.

It is easy to solve this problem. Use the volatile modifier to force variable A to read the latest data in the memory each time it is accessed.

# Include <iostream> int main () {const volatile int A = 0; int * P = const_cast <int *> (& A); // & A returns int *, const_cast <int *> display to int *. * p = 1; int B = * P; int c = A; STD: cout <"B:" <B <STD: Endl <"C: "<C <STD: Endl; return 0 ;}

The output result is:

B: 1

C: 1

Some readers have come up with the reason: the compiler has replaced the symbol of the const object. The following uses the const object, instead of extracting the latest value from the memory.

 





 

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.