Const-Modified constants cannot be modified directly but can be indirectly modified by pointers

Source: Internet
Author: User
As you know, a const-qualified A is not allowed to be directly modified in the following code.
void Main () {                    const int a = 3;           A=1;}

  in C + + Const-Modified constants, which cannot be modified directly, but can be indirectly modified by pointers

Take a look at the following example:


The intent is to modify the value of the const constant A through the pointer, but after the run, it is found that the output of a remains the 3,a value surface and has not been changed.  But look at the memory window and find that a has been changed, this is the compiler optimization, and when you meet a, the compiler reads 3 to a directly from the register without reading from memory! To improve this situation, we can add a volatile modifier to the definition of a to avoid compiler optimizations:

Const-Modified constants cannot be modified directly but can be indirectly modified by pointers

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.