(2) how to modify the const variable in C ++ with lwj Q &

Source: Internet
Author: User
Document directory
  • (1) output results when the volatile modifier is added (the program code is the same as above ):
  • (2) When there is no volatile modifier. Output result:
  • (1) When the volatile modifier is added, the output result is:
  • (2) If no volatile modifier exists, the output result is as follows:
I. Conclusion

Statement: Unlike the const variable modification in C Language (you can indirectly modify the value of the const variable through the pointer), Here we only discuss the const in C ++.

The C ++ const modifier indicates a constant, that is, if it is not modified in the future, it is declared as a const. Otherwise, if it is to be modified, why should it be declared as a const at the beginning?

According to the C ++ standard, changing the const variable is:Undefined behavior(Computer code with unpredictable behavior), so this behavior depends on the specific implementation of various compilers (that is, different compilers may behave differently ).

The conclusion is: we do not recommend this!

However, yes, but there are methods on the Internet forums and blogs for modifying the const variable, either depending on a specific compiler or not.

The method is to add the volatile keyword when defining the variable (is there no other method (for example, const_cast ...)? Yes, so far, I only know that this method is possible ):

const volatile int i = 10;

Note: Volatile is not detailed here. For details, see the volatile keyword. Considering the importance of volatile, I will also write a detailed article on volatile later.

Ii. Analysis

To illustrate the problem, we will do a few small experiments in three compiler environments.

1.g ++

#include <stdio.h>int main(){    const volatile int i = 10;    int* pi = (int*)(&i);    *pi = 100;    printf("*pi: %d\n",*pi);    printf("i: %d\n",i);    printf("pi: %p\n",pi);    printf("&i: %p\n", &i);    return 0;}

Output result:

View itsAssembly Code(Command: Enter GDB, and then enter: disass main ):

It can be seen that when * PI and I are input, the number is obtained from the stack (that is, the memory.

Counterexample: Remove the volatile Keyword:

#include <stdio.h>int main(){    const int i = 10;    int* pi = (int*)(&i);    *pi = 100;    printf("*pi: %d\n",*pi);    printf("i: %d\n",i);    printf("pi: %p\n",pi);    printf("&i: %p\n", &i);    return 0;}

Output result:

It can be seen that the value of const variable I is not changed when the volatile keyword is not modified.

Use GDB to view its assembly code:

Note that at this time (without the volatile modifier), when outputting the value of variable I, the 0xa (10) value (extracted from the symbol table) is directly output, that is, the compiler is optimized here, not read from memory.

Note: The pointer pi and the & I (I address) values are the same. So, Why?

This is the constant folding in C ++: it refers to placing the const variable (that is, the constant) value in the symbol table of the compiler. During computation, the compiler directly takes the value from the table, saving the memory access time, so as to achieve the optimization.

On this basis, the volatile modifier tells the compiler that the variable is variable-prone and does not optimize the sentence. The number of variables in the memory is required for each calculation.

There is alsoSmall details: The modifier effects of each compiler on the Volatile modifier are inconsistent, and some will directly "Ignore", such as the VC ++ 6.0 Compiler (as described below ).

2. dev c ++

The running result is consistent with 1 (g ++.

3. VC ++ 6.0 (1) output results when the volatile modifier is added (same as the program code ):

The I value is still 10, not changed! Why? Don't worry, first look at its assembly code:

Note:: The mov command of G ++ assembly code is different from the mov command of VC ++ 6.0 (the transfer direction is the opposite ).

Truth and truth: Although the const variable is defined with the volatile modifier added, the VC ++ 6.0 Compiler still carries out Optimization Measures to output values from the symbol table of the compiler for I.

(2) When there is no volatile modifier. Output result:

The I value has not changed, as expected. The assembly code is:

The result is the same as that when volatile is added.

That is, in the compiling environment of VC ++ 6.0, the volatile modifier is added when the const variable is defined, which is the same as that without adding a variable. The compiler has been optimized (or even the compiler optimization option is disabled ...).

4. VS 2010

Let's look at the advanced versions of the Microsoft compiler family:

(1) When the volatile modifier is added, the output result is:

The I value is successfully modified!

(2) If no volatile modifier exists, the output result is as follows:

The I value is not modified.

Therefore, it is not recommended to modify the value of the const variable. Even if you modify the value, you must be familiar with how the current compiler interprets the undefined behavior..

References:

1. change the value of const variable in C ++

2. C/C ++ changin the value of a const

3. Baidu Encyclopedia: constant folding of C ++

4. volatile keywords

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.