Bruno Criado
Bruno Criado

Reputation: 110

Incrementing one to a variable in IA32 Linux Assembly

I'm trying to increment 1 to a variable in IA32 Assembly in Linux

section .data
num:    dd  0x1

section .text
global _start

_start:

   add    dword [num], 1

   mov    edx, 1
   mov    ecx, [num]
   mov    ebx,1
   mov    eax,4
   int    0x80

   mov    eax,1
   int    0x80

Not sure if it's possible to do.

In another literature I saw the follow code:

mov eax, num
inc eax
mov num, eax

Is it possible to increment a value to a var without moving to a register?

If so, do I have any advantage moving the value to a register?

Upvotes: 0

Views: 165

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58007

Is it possible to increment a value to a var without moving to a register?

Certainly: inc dword [num].

Like practically all x86 instructions, inc can take either a register or memory operand. See the instruction description at http://felixcloutier.com/x86/inc; the form inc r/m32 indicates that you can give an operand which is either a 32-bit register or 32-bit memory operand (effective address).

If you're interested in micro-optimizations, it turns out that add dword [num], 1 may still be somewhat faster, though one byte larger, on certain CPUs. The specifics are pretty complicated and you can find a very extensive discussion at INC instruction vs ADD 1: Does it matter?. This is partly related to the slight difference in effect between the two, which is that add will set or clear the carry flag according to whether a carry occurs, while inc always leaves the carry flag unchanged.

If so, do I have any advantage moving the value to a register?

No. That would make your code larger and probably slower.

Upvotes: 4

Related Questions