Ricardo Altamirano
Ricardo Altamirano

Reputation: 15208

Why are the disassemblies of these two simple statements slightly different?

I wrote two simple programs that store the same integer value to two different variables, and I'm wondering why the disassembly is slightly different between both programs.

First program:

int y;
int x = (y = 2);

Disassembly:

0000003a  mov         dword ptr [ebp-40h],2 
00000041  mov         eax,dword ptr [ebp-40h] 
00000044  mov         dword ptr [ebp-44h],eax

Second program:

int x = 2, y = 2;

Disassembly:

0000003a  mov         dword ptr [ebp-40h],2 
00000041  mov         dword ptr [ebp-44h],2 

The second line in the first program, which is clearly the only change, simply copies the value pointed to by [ebp-40h] into the eax registry, right? Maybe it's a dumb question, but why are these slightly different? I'm not very familiar with assembly, to say the least, so I take it that you have to move a value into a registry before pointing to it? (or whatever the third line does. I think it's pointing...)

For the sake of readability, I plan to never instantiate variables in serious code like I did in the first program.

Edit

Per the discussion in the comments, I compiled Release builds of these two snippets instead of the Debug builds I had been using before. The results are virtually identical:

First program:

00000000  push        ebp 
00000001  mov         ebp,esp 
00000003  push        eax 
00000004  mov         dword ptr [ebp-4],ecx 
00000007  cmp         dword ptr ds:[005E14B4h],0 
0000000e  je          00000015 
00000010  call        6C37403F 
00000015  nop 
00000016  mov         esp,ebp 
00000018  pop         ebp 
00000019  ret 

Second program:

00000000  push        ebp 
00000001  mov         ebp,esp 
00000003  push        eax 
00000004  mov         dword ptr [ebp-4],ecx 
00000007  cmp         dword ptr ds:[005514B4h],0 
0000000e  je          00000015 
00000010  call        6C42403F 
00000015  nop 
00000016  mov         esp,ebp 
00000018  pop         ebp 
00000019  ret 

It looks like the differences are only in memory addresses (i.e. not really a difference). I think that's the correct interpretation, at any rate.

Upvotes: 1

Views: 231

Answers (1)

usr
usr

Reputation: 171236

Your first example is rewritten to:

y = 2;
x = y;

because

(y = 2)

"evaluates" to

y

after assigning y.

And that matches the disassembly 1:1.

Sidenote: You can see the same effect with properties:

Button b;
b.Width = b.Height = 100; //inefficient!

Upvotes: 5

Related Questions