Const-modified constants cannot be directly modified, but can be indirectly modified through pointers.

Source: Internet
Author: User

Const-modified constants cannot be directly modified, but can be indirectly modified through pointers.
In the following code, const-qualified a cannot be directly modified.

Void main () {const int a = 3; a = 1 ;}

In C ++Const-modified constants cannot be directly modified, but can be indirectly modified through pointers.

Let's look at the following example:

Output 5 3 after running

Run in one step and use the memory window for viewing. a is 3 before modification.

After a is indirectly modified using the pointer, a displays 5 in the memory.
The original intention is to modify the value of const constant a through the pointer, but after running, it is found that the output of a is still 3, and the value of a is not changed on the surface. But check the memory window and find that a has been changed. This is caused by Compiler Optimization. When a is met, the compiler reads 3 to a directly from the register rather than from the memory! To improve this situation, we can add a volatile modifier when defining a to avoid Compiler Optimization:

 

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.