Skip to content

Instantly share code, notes, and snippets.

@nikAizuddin
Last active August 29, 2015 14:09
Show Gist options
  • Save nikAizuddin/fd3b9989b04ae7b3517f to your computer and use it in GitHub Desktop.
Save nikAizuddin/fd3b9989b04ae7b3517f to your computer and use it in GitHub Desktop.
How C execute z = ++x + ++x + ++x;
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int x = 2;
int z = 0;
z = ++x + ++x + ++x;
printf("z = %d\n",z);
return 0;
}
Disassembled:
08048420 <main>:
...
...
...
sub $0x20,%esp ;reserve 32 bytes of stack for var x and z
movl $0x2,0x1c(%esp) ;int x = 2
...
movl $0x0,0x18(%esp) ;int z = 0
...
addl $0x1,0x1c(%esp) ;x = x + 1
addl $0x1,0x1c(%esp) ;x = x + 1
mov 0x1c(%esp),%eax ;eax = x
lea (%eax,%eax,1),%edx ;edx = eax + eax
addl $0x1,0x1c(%esp) ;x = x + 1
mov 0x1c(%esp),%eax ;eax = x
add %edx,%eax ;eax = eax + edx
mov %eax,0x18(%esp) ;z = eax
...
...
...
call 80482f0 <printf@plt> ;printf()
mov $0x0,%eax ;return 0
leave
ret
...
...
...
...
...
...
notes: "..." = instruction that is not important
To simplify this, here the step-by-step instructions performed by the program:
------------------------------------------------------------------------------
Problem: z = ++x + ++x + ++x, find z = ?
Given: x = 2
Step 1:
(++x + ++x) + ++x
x = x + 1
x = 2 + 1
x = 3
x = x + 1
x = 3 + 1
x = 4
(4 + 4) + ++x
8 + ++x
Step 2:
(8 + ++x)
x = x + 1
x = 4 + 1
x = 5
(8 + 5)
13
z = 13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment