Modification of A/C + + const variable

Source: Internet
Author: User
Tags volatile

The const in C is a run-time const that is only defined at compile time and is initialized only at run time, which is why Const cannot be used to define an array, and the value of const can be dynamically modified.

Const in C + + is compile-time const, so it can be used to initialize the array, the value of the attempt to modify the const is undefined, if you want to modify the value of const can only change the const variable is declared as

Const volatile c=10.

Test Case:

const int ci=10;

int *j = (int *) &ci;

*j=100;

printf ("%d,%d", ci,*j);

cout<< "Address I:" <<&ci<<endl;

cout<< "Address J:" <<j<<endl;

The volatile modifier is capable of changing the value of const in C + + because volatile prevents the compiler's constant folding optimization (constant folding optimization: A const variable, or constant), placed in the compiler's symbol table, which is evaluated directly from the table. It eliminates the time it takes to access the memory, thus achieving optimization. And on this basis add the volatile modifier, that is, tell the compiler that the variable is volatile, do not optimize the sentence, each time the calculation to go to the memory to take the number of

Modification of A/C + + const variable

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.