user2004149
user2004149

Reputation: 97

How can i declare local variables in 8086?

If i declare my variables under .data they are considered as global variables, how can i declare them locally

@paul I am able to allocate memory but how can i type cast them(such as signed and unsigned int)

Upvotes: 3

Views: 6219

Answers (1)

Alexey Frunze
Alexey Frunze

Reputation: 62048

Declaration of local variables in assembly code depends on your assembler and it may not support such declarations at all.

Typically, local variables are allocated by moving (decrementing) the stack pointer. Allocation and initialization of a local variable on the stack can be fused together if you use the push instruction, which advances the stack pointer and writes to the stack. Example of this:

; input: eax = some integer >= 1
; output: eax = factorial of the integer
; used registers: ebx, eflags
factorial:
cmp   eax, 1
je    factorial_end
push  eax ; created a local variable on the stack
dec   eax
call  factorial
pop   ebx ; destroyed a local variable on the stack
mul   ebx
factorial_end:
ret

As for signed, unsigned and casting, there's no such thing in assembly. CPUs do exactly what you tell them to. They don't interpret inputs or outputs, it's you, the programmer to make that interpretation. And so, if you want to divide two integers as unsigned, you execute DIV with the values of the integers and if you want to make a signed division, you do the same with the IDIV instruction. If you use IDIV on what you think is usigned integers (or DIV on signed integers), the CPU will happily do that for you and the wrong result (or a division overflow exception) will be your problem to deal with. Luckily, addition, subtraction and multiplication of unsigned and 2's complement signed integers is done in the same way by the CPU for both kinds of integers and you don't need to do anything special like choosing the right instruction for each kind. Typically, only division and comparison differ between signed and unsigned integers. But again, you take care of this difference explicitly in the code.

Upvotes: 4

Related Questions