I have a very basic doubt here. I have two very simple C codes and their assembly codes:
program 1:
main()
{
int temp1, temp2, temp3;
char temp5, temp6, temp7, temp8, temp9;
temp1 = 5;
temp1 = 9 - temp1;
}
Assembly:
0x080483b4 <+0>: push ebp
0x080483b5 <+1>: mov ebp,esp
0x080483b7 <+3>: sub esp,0x20
0x080483ba <+6>: mov DWORD PTR [ebp-0xc],0x5
0x080483c1 <+13>: mov eax,0x9
0x080483c6 <+18>: sub eax,DWORD PTR [ebp-0xc]
0x080483c9 <+21>: mov DWORD PTR [ebp-0xc],eax
0x080483cc <+24>: leave
0x080483cd <+25>: ret
Program 2:
main()
{
int temp1, temp2, temp3;
char temp5, temp6, temp7, temp8, temp9;
temp1 = 5;
temp1 = 9 + temp1;
}
Assembly:
0x080483b4 <+0>: push ebp
0x080483b5 <+1>: mov ebp,esp
0x080483b7 <+3>: sub esp,0x20
0x080483ba <+6>: mov DWORD PTR [ebp-0xc],0x5
0x080483c1 <+13>: add DWORD PTR [ebp-0xc],0x9
0x080483c5 <+17>: leave
0x080483c6 <+18>: ret
Why in the case of subtraction, eax register need to be used and not in the case of addition. Can't it be like:
0x080483c1 <+13>: sub DWORD PTR [ebp-0xc],0x9
instead of -
0x080483c1 <+13>: mov eax,0x9
0x080483c6 <+18>: sub eax,DWORD PTR [ebp-0xc]
I'm guessing because addition is commutative (A + B == B + A), whereas subtraction is not (A - B != B - A). Because of this the addition of 9 + temp1
is the same as temp1 + 9
, hence the simpler assembler sequence. 9 - temp1
involves creating a temporary variable.
temp1 = 9 - temp1;
is the same as temp1 = - temp1 + 9;
. This carries out 2 operations:
temp1
eax
is used as the temporary location to save the middle value.
In the addition case, there's no "middle value", the operation can be done directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With