Assembly Language for Beginners

(nextflipdebug2) #1

1.9. SCANF()


This simple example is a demonstration of the fact that compiler translates list of expressions in C/C++-
block into sequential list of instructions. There are nothing between expressions in C/C++, and so in
resulting machine code, there are nothing between, control flow slips from one expression to the next
one.


x64


The picture here is similar with the difference that the registers, rather than the stack, are used for argu-
ments passing.


MSVC


Listing 1.68: MSVC 2012 x64

_DATA SEGMENT
$SG1289 DB 'Enter X:', 0aH, 00H
$SG1291 DB '%d', 00H
$SG1292 DB 'You entered %d...', 0aH, 00H
_DATA ENDS


_TEXT SEGMENT
x$ = 32
main PROC
$LN3:
sub rsp, 56
lea rcx, OFFSET FLAT:$SG1289 ; 'Enter X:'
call printf
lea rdx, QWORD PTR x$[rsp]
lea rcx, OFFSET FLAT:$SG1291 ; '%d'
call scanf
mov edx, DWORD PTR x$[rsp]
lea rcx, OFFSET FLAT:$SG1292 ; 'You entered %d...'
call printf


; return 0
xor eax, eax
add rsp, 56
ret 0
main ENDP
_TEXT ENDS


GCC


Listing 1.69: Optimizing GCC 4.4.6 x64

.LC0:
.string "Enter X:"
.LC1:
.string "%d"
.LC2:
.string "You entered %d...\n"


main:
sub rsp, 24
mov edi, OFFSET FLAT:.LC0 ; "Enter X:"
call puts
lea rsi, [rsp+12]
mov edi, OFFSET FLAT:.LC1 ; "%d"
xor eax, eax
call __isoc99_scanf
mov esi, DWORD PTR [rsp+12]
mov edi, OFFSET FLAT:.LC2 ; "You entered %d...\n"
xor eax, eax
call printf

Free download pdf