Reprinted from Csdn
http://blog.csdn.net/huangshanchun/article/details/41215065
const differences in C and C + +
Test environment: Windows 7 vs2010
Using the const modifier variable means that it is read-only, but the const in C is quite different from the const in C + +.
C Language Const is "counterfeit", see the following C program:
[CPP]View Plaincopy
- #include <stdio.h>
- #include <stdlib.h>
- int main ()
- {
- const INT a = 5;
- int *p = NULL;
- printf ("A before modification:%d \ n", a);
- p = (int *) &a;
- *p = 6;
- printf ("a modified:%d \ n", a);
- System ("pause");
- return 0;
- }
Test results:
The value of a in the program can be modified, although we cannot directly modify, but can be obtained by obtaining the address of a to indirectly modify.
The same program we implemented in C + +:
[CPP]View Plaincopy
- #include <iostream>
- Using namespace std;
- int main ()
- {
- const INT a = 5;
- int *p = NULL;
- cout<<"a modified before:" <<a<<endl;
- p = (int *) &a;
- *p = 6;
- cout<<"a modified:" <<a<<endl;
- System ("pause");
- return 0;
- }
Test results:
C + + and C do not work the same, and the C + + compiler handles const constants by placing constants in the symbol table when a constant declaration is encountered, and when a constant is found in the compilation, it is replaced directly by the values in the symbol table.
Question: How to interpret the address, the compilation process if you find that the const using extern or the & operator, the corresponding constant allocation of storage space (in order to be compatible with C). Although the C + + compiler may allocate space for Const constants (for & Operations), it does not use the values in its storage space.
Conclusion:
const constant in C: It is a read-only variable, has its own storage space, can be indirectly modified by the address of its value.
Const constants in C + +: They are placed in the symbol table, may allocate storage space, may not allocate storage space, and a temporary memory space is allocated when the & symbol is used.
Reproduced const differences in C and C + +