In C const this keyword, wiki gives such a sentence
When applied on an object Declaration,[b] It indicates that object is a Constant:its value does not change, unlike a Variable. This basic use–to declare Constants–has parallels in many other languages
is actually used to not allow the modification of its value, but the need to think about it is not allowed to modify the value of a or in memory value, if you want to modify the value in memory what to do? The CPU only knows 0101, the compiler is how to complete the function of the const, the following through the experimental analysis, (Experimental platform 64-bit win7,vs2008)
Initial code
intintconstint a=10; c=1; return0;}
Very often, if
A=11; The first compilation does not pass, this is the C syntax is not allowed.
Take a look at the value of the memory in a corresponding to this
If you want to modify a value, there is another way that the pointer is done indirectly. Then modify the code
intintint a=10; int*p=(int*)*p=11return0;}
Compile through, see what's in the memory.
Has indeed been modified,
That is, you can still modify the value of this memory by bypassing the compiler's const-modifier rules.
There will be a problem here, after the modification, a also point to the address, but the next time a reference to a, is not a memory address from the value of the
such as the following situation
intintint a=10; int*p=(int*)*p=11; c=1return0;}
The value of result B is 11, that is, when the compiler calculates a, it does not take a value from the memory corresponding to a.
How the compiler is done. Look at the compilation of this piece of code.
intB,c; ConstintA=Ten;012E1F6E mov dword ptr [a],0ahint *p=(int*)&a;012E1f75 Lea Eax,[a]012E1F78 mov dword ptr [P],eax*p= One;012E1F7B mov eax,dword ptr [p]012E1F7E mov dword ptr [EAX],0BH c=1;012E1F84 mov dword ptr [C],1B=a+c;012E1F8B mov eax,dword ptr [c]012e1f8e Add eax,0ah012E1f91 mov dword ptr [B],eaxreturn 0;012e1f94XOREax,eax
The main thing is these words
b=a+c;012E1F8B mov eax,dword ptr [c]012E1F8E add eax,0Ah012E1F91 mov dword ptr [b],eax
When referring to the value of C, the data is removed from the memory of C and then assigned to the register EAX,
However, when referencing a variable, it is not like C, but instead of using 10来 directly.
The horizontal slot, which is not the macro definition, directly replaces the value of a with its initialization,
Using a contrasting experiment
#define a_tmp (10)intintconstint a=10; int *p=(int*)&a; *p=11; c=1return0;}
Observing assembly code
b=a+c;01221F8B mov 01221F8E add eax,001221F91 mov dword ptr [b],eax b=a_tmp+c;01221F94 mov 01221F97 add eax,001221F9A mov
Just like this, it's clear ....
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Parsing the compiler's handling of C keywords skip the compiler's syntax check and complete a very dangerous operation