3

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)

2
  • 4
    You need to read up on stack frames. Basically you allocate a chunk of stack space for local variables at the start of a function and release it at the end. Disassembling a simple C function (gcc -S ...) will show you how it's done. Commented Jan 28, 2013 at 9:46
  • 2
    The "casting" is done by selecting the proper instruction: imul instead of mul; or jl (jump less) instead of jb (jump below), mov for loading integer to register, fld for loading a double to FPU. Commented Jan 28, 2013 at 10:00

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.