Assembly Language for Beginners

(nextflipdebug2) #1

1.9 scanf().


possible to create a hypothetical compiler able to pass arguments via a special structure without using
stack at all.


MIPS $A0 ...$A3 registers are labeled this way only for convenience (that is in the O32 calling convention).
Programmersmayuseanyotherregister(well, maybeexcept$ZERO)topassdataoruseanyothercalling
convention.


TheCPUis not aware of calling conventions whatsoever.


We may also recall how new coming assembly language programmers passing arguments into other func-
tions: usually via registers, without any explicit order, or even via global variables. Of course, it works
fine.


1.9 scanf()


Now let’s use scanf().


1.9.1 Simple example


#include <stdio.h>


int main()
{
int x;
printf ("Enter X:\n");


scanf ("%d", &x);

printf ("You entered %d...\n", x);

return 0;
};


It’s not clever to usescanf()for user interactions nowadays. But we can, however, illustrate passing a
pointer to a variable of typeint.


About pointers


Pointers are one of the fundamental concepts in computer science. Often, passing a large array, structure
orobjectasanargumenttoanotherfunctionistooexpensive,whilepassingtheiraddressismuchcheaper.
Forexample,ifyougoingtoprintatextstringtoconsole,it’smucheasiertopassitsaddressintoOSkernel.


In addition if thecalleefunction needs to modify something in the large array or structure received as a
parameter and return back the entire structure then the situation is close to absurd. So the simplest thing
to do is to pass the address of the array or structure to thecalleefunction, and let it change what needs
to be changed.


A pointer in C/C++—is simply an address of some memory location.


In x86, the address is represented as a 32-bit number (i.e., it occupies 4 bytes), while in x86-64 it is a 64-
bit number (occupying 8 bytes). By the way, that is the reason behind some people’s indignation related
to switching to x86-64—all pointers in the x64-architecture require twice as much space, including cache
memory, which is “expensive” memory.


It is possible to work with untyped pointers only, given some effort; e.g. the standardC functionmemcpy(),
that copies a block from one memory location to another, takes 2 pointers of typevoid*as arguments,
since it is impossible to predict the type of the data you would like to copy. Data types are not important,
only the block size matters.


Pointers are also widely used when a function needs to return more than one value (we are going to get
back to this later (3.21 on page 611) ).


scanf()function—is such a case.

Free download pdf