Assembly Language for Beginners

(Jeff_L) #1

1.9. SCANF()


; high part of x address is still in $s0.
; add low part to it and load a word from memory:
4006e8: 8e050920 lw a1,2336(s0)
; value of x is now in $a1.
4006ec: 8f99803c lw t9,-32708(gp)
4006f0: 3c040040 lui a0,0x40
4006f4: 0320f809 jalr t9
4006f8: 248408e0 addiu a0,a0,2272
4006fc: 8fbf001c lw ra,28(sp)
400700: 00001021 move v0,zero
400704: 8fb00018 lw s0,24(sp)
400708: 03e00008 jr ra
40070c: 27bd0020 addiu sp,sp,32


We see that the address is formed usingLUIandADDIU, but the high part of address is still in the $S0
register, anditispossibletoencodetheoffsetinaLW(“LoadWord”)instruction, soonesingleLWisenough
to load a value from the variable and pass it toprintf().


Registers holding temporary data are prefixed with T-, but here we also see some prefixed with S-, the
contents of which must be preserved before use in other functions (i.e., saved somewhere).


That is why the value of $S0 has been set at address 0x4006cc and has been used again at address
0x4006e8, after thescanf()call. Thescanf()function does not change its value.


1.9.4 scanf()


As was noted before, it is slightly old-fashioned to usescanf()today. But if we have to, we have to check
ifscanf()finishes correctly without an error.


#include <stdio.h>


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


if (scanf ("%d", &x)==1)
printf ("You entered %d...\n", x);
else
printf ("What you entered? Huh?\n");

return 0;
};


By standard, thescanf()^75 function returns the number of fields it has successfully read.


In our case, if everything goes fine and the user enters a numberscanf()returns 1, or in case of error
(orEOF^76 ) — 0.


Let’s add some C code to check thescanf()return value and print error message in case of an error.


This works as expected:


C:...>ex3.exe
Enter X:
123
You entered 123...


C:...>ex3.exe
Enter X:
ouch
What you entered? Huh?


(^75) scanf, wscanf:MSDN
(^76) End of File

Free download pdf