一、前置和后置
前置:++preAdd --preSub
后置:postAdd++ postSub–
二、思考这段代码
int main()
{
int preAdd = 0;
int postAdd = 0;
int result_preAdd = ++preAdd;
int result_postAdd = postAdd++;
int result_preSub = --preSub;
int result_postSub = postSub--;
return 0;
}
result_preAdd = ?
result_postAdd = ?
result_preSub = ?
result_postSub = ?
2.运行结果
运行结果图
思考一下原因是什么
这里笔者也想不通为什么?
看别人说的和讲的都是只知道结果不知道为什么?
所以这里可以通过查看反汇编来理解这段代码做了什么?
int main()
{
00007FF77BAE3B30 push rbp
00007FF77BAE3B32 push rdi
00007FF77BAE3B33 sub rsp,1E8h
00007FF77BAE3B3A lea rbp,[rsp+20h]
00007FF77BAE3B3F lea rcx,[00007FF77BAF1009h]
00007FF77BAE3B46 call 00007FF77BAE1352
00007FF77BAE3B4B nop
int preAdd = 0;
00007FF77BAE3B4C mov dword ptr [rbp+4],0
int postAdd = 0;
00007FF77BAE3B53 mov dword ptr [rbp+24h],0
int preSub = 1;
00007FF77BAE3B5A mov dword ptr [rbp+44h],1
int postSub = 1;
00007FF77BAE3B61 mov dword ptr [rbp+64h],1
int result_preAdd = ++preAdd;
00007FF77BAE3B68 mov eax,dword ptr [rbp+4]
00007FF77BAE3B6B inc eax
00007FF77BAE3B6D mov dword ptr [rbp+4],eax
00007FF77BAE3B70 mov eax,dword ptr [rbp+4]
00007FF77BAE3B73 mov dword ptr [rbp+0000000000000084h],eax
int result_postAdd = postAdd++;
00007FF77BAE3B79 mov eax,dword ptr [rbp+24h]
00007FF77BAE3B7C mov dword ptr [rbp+00000000000000A4h],eax
00007FF77BAE3B82 mov eax,dword ptr [rbp+24h]
00007FF77BAE3B85 inc eax
00007FF77BAE3B87 mov dword ptr [rbp+24h],eax
int result_preSub = --preSub;
00007FF77BAE3B8A mov eax,dword ptr [rbp+44h]
00007FF77BAE3B8D dec eax
00007FF77BAE3B8F mov dword ptr [rbp+44h],eax
00007FF77BAE3B92 mov eax,dword ptr [rbp+44h]
00007FF77BAE3B95 mov dword ptr [rbp+00000000000000C4h],eax
int result_postSub = postSub--;
00007FF77BAE3B9B mov eax,dword ptr [rbp+64h]
00007FF77BAE3B9E mov dword ptr [rbp+00000000000000E4h],eax
00007FF77BAE3BA4 mov eax,dword ptr [rbp+64h]
00007FF77BAE3BA7 dec eax
00007FF77BAE3BA9 mov dword ptr [rbp+64h],eax
return 0;
00007FF77BAE3BAC xor eax,eax
}
这里我通过vs Studio生成的反汇编
eax:保存数据的寄存器
mov:数据传送指令 举例:mov [地址] eax 将eax寄存器的值赋值给[地址]表示的内存中
mov eax [地址] 取出[地址]表示内存中的值给eax
inc:加一
dec:减一
前置++
int preAdd = 0;
00007FF77BAE3B4C mov dword ptr [rbp+4],0
int result_preAdd = ++preAdd;
00007FF77BAE3B68 mov eax,dword ptr [rbp+4]
00007FF77BAE3B6B inc eax
00007FF77BAE3B6D mov dword ptr [rbp+4],eax
00007FF77BAE3B70 mov eax,dword ptr [rbp+4]
00007FF77BAE3B73 mov dword ptr [rbp+0000000000000084h],eax
preAdd存储在rbp+4的内存中
1>将0->eax
2>eax+1
3>eax->preAdd
4>eax->result_preAdd
后置++
int postAdd = 0;
00007FF77BAE3B53 mov dword ptr [rbp+24h],0
int result_postAdd = postAdd++;
00007FF77BAE3B79 mov eax,dword ptr [rbp+24h]
00007FF77BAE3B7C mov dword ptr [rbp+00000000000000A4h],eax
00007FF77BAE3B82 mov eax,dword ptr [rbp+24h]
00007FF77BAE3B85 inc eax
00007FF77BAE3B87 mov dword ptr [rbp+24h],eax
1> 0->eax
2> eax->result_postAdd
3> 0->eax
4> eax+1
5> eax->postAdd