Kotaa
Kotaa

Reputation: 201

Direct memory addressing in Assembly and []

I'm reading this https://en.wikibooks.org/wiki/X86_Assembly/X86_Architecture#General-purpose_registers_.2864-bit_naming_conventions.29

At Direct memory addressing it says:

.data
  my_var dw 0abcdh ; my_var = 0xabcd

.code
  mov ax, [my_var] ; copy my_var content into ax (ax=0xabcd)

I wonder, what would it copy to ax without [] if not its value which is 0xabcd?

And why is it the content in the first place? Shouldn't it treat 0xabcd as a memory address and go look what's stored at the address 0xabcd instead?

Upvotes: 1

Views: 5798

Answers (2)

fuz
fuz

Reputation: 93172

my_var is a symbol referring to some memory address. The directive

my_var dw 0abcdh

causes the assembler to allocate two bytes of storage, write the value 0abcdh to it and then let my_var point to the beginning of that storage.

The comment my_var = 0xabcd wants to explain that the variable my_var points to has this value. To understand this, observe that in high-level languages like C, when you declare a global variable, the variable name is always implicitly dereferenced:

int foo = 1;
// compiles to
foo dw 1

I wonder, what would it copy to ax without [] if not its value which is 0xabcd?

If you do not use a memory reference, the value of the symbol my_var, i.e. the address of that variable, is copied. For example,

    mov ax, my_var

is as if you wrote

    ax = &my_var;

in C.

And why is it the content in the first place? Shouldn't it treat 0xabcd as a memory address and go look what's stored at the address 0xabcd instead?

No. To do that, you need two memory accesses as you first need to fetch the content of my_var to get 0xabcd and then fetch from 0xabcd to get what is there:

mov bx,[myvar]
mov ax,[bx]

Upvotes: 6

Frank C.
Frank C.

Reputation: 8106

Kotaa

Basically:

mov  ax, my_var   ; Moves the location of my_var into ax
mov  ax, [my_var] ; Moves the content found at the address of my_var

To your second block of questions. If, indeed, my_var was supposed to hold a pointer to another block of data then:

mov  eax, [my_var]  ; Get pointer stored at my_var
mov  ebx, [eax]      ; Get data from pointer whose address is in eax

Upvotes: 1

Related Questions