NASM - The Netwide Assembler

NASM Forum => Programming with NASM => Topic started by: gygzkunw on February 01, 2021, 05:13:56 PM

Title: Whats a practical use for lea
Post by: gygzkunw on February 01, 2021, 05:13:56 PM
I know that lea is a shift-addition instruction and lets you load the address of an effective address. I also know it doesn't affect the flag register . But i still cant come up with a practical purpose for why i should use lea when i can use mov. Please i am assembly noob, try and keep it single.

Title: Re: Whats a practical use for lea
Post by: fredericopissarra on February 01, 2021, 08:40:22 PM
1. You can use to do simple arithmetic calculations:

Code: [Select]
; int f( int x ) { return 5 * x; }
f:
  lea eax,[rdi+rdi*4]
  ret

2. You can use to precalculate a RIP relative address (x86-64):

Code: [Select]
  lea rax,[rel var]   ; You can get rid of 'rel' here if rip relative addressing is default.

3. You can get the address of an element in an array:

Code: [Select]
  ; Supose RCX is the index of an array of ints:
  lea rsi,[array+rcx*4]   ; rsi now points to array[rcx]