static variable in a function
:
1.Allocated once at a fixed address,that is , the object is created in a special static data area rather than on the stack each time a function is called.This is the concept of static storage.
#include <iostream>
using namespace std;
int test(int a)
{
static int i=3;//第一次调用函数时,初始化.第二次调用函数时,此句不执行
i++;
return i;
}
int main()
{
cout<<test(3)<<endl;
cout<<test(3)<<endl;
}
输出结果:4 5
- --- F:/1/file1.cpp ------------------------------------------------------------------------------------------------------
- 1: #include <iostream>
- 2: using namespace std;
- 3:
- 4: int test(int a)
- 5: {
- 00401030 push ebp
- 00401031 mov ebp,esp
- 00401033 sub esp,40h
- 00401036 push ebx
- 00401037 push esi
- 00401038 push edi
- 00401039 lea edi,[ebp-40h]
- 0040103C mov ecx,10h
- 00401041 mov eax,0CCCCCCCCh
- 00401046 rep stos dword ptr [edi]
- 6: static int i=3;//注意这句没相应的汇编,变量存在静态存储区
- 7:
- 8: i++;
- 00401048 mov eax,[___xt_z+110h (00434dc0)]
- //内存跟踪 00434DC0 03 00 00 00
- 0040104D add eax,1
- 00401050 mov [___xt_z+110h (00434dc0)],eax
- 9: return i;
- 00401055 mov eax,[___xt_z+110h (00434dc0)]
- 10: }
- 0040105A pop edi
- 0040105B pop esi
- 0040105C pop ebx
- 0040105D mov esp,ebp
- 0040105F pop ebp
- 00401060 ret
- --- F:/1/file1.cpp ------------------------------------------------------------------------------------------------------
- 11: int main()
- 12: {
- 00401070 push ebp
- 00401071 mov ebp,esp
- 00401073 sub esp,40h
- 00401076 push ebx
- 00401077 push esi
- 00401078 push edi
- 00401079 lea edi,[ebp-40h]
- 0040107C mov ecx,10h
- 00401081 mov eax,0CCCCCCCCh
- 00401086 rep stos dword ptr [edi]
- 13: test(3);
- 00401088 push 3
- 0040108A call @ILT+0(test) (00401005)
- 0040108F add esp,4 //由push 3这条指令引起,堆栈平衡
- 14: test(3);
- 00401092 push 3
- 00401094 call @ILT+0(test) (00401005)
- 00401099 add esp,4
- 15: }
- 0040109C pop edi
- 0040109D pop esi
- 0040109E pop ebx
- 0040109F add esp,40h
- 004010A2 cmp ebp,esp//?这两句的作用是?
- 004010A4 call __chkesp (00408190)//?
- 004010A9 mov esp,ebp
- 004010AB pop ebp
- 004010AC ret
2.File static
Local to a particular translation unit (and local to a class scope in C++,as you will see later),Here ,static controls the visibility of a name.So the name can not be seen outside the translation unit or class.This also describes the concept of linkage,which determines what names the linker will see.
这个我无法从汇编中看出区别.希望高手赐教.
网上找到的call _chkesp(******)的资料
调试版才会有,检查栈是否被破坏了.这样就能及时在你出错的地方停下了告诉你.发行版自动消除这些代码(调试产生的).有时候也可以手工加入这些调试检查代码,用于检查并确定错误所在位置。
关闭/GZ开关,可以去掉