When do I need to specify the size of the operand in Assembly?

Viewed 553

I am just starting studying Assembly (x86, NASM) in university and I am really confused about how it works. Out of the many questions I have about it, this keeps bugging me.

When do I need to speficify the size of the operand? Is there a rule? For example:

segment  data use32 class=data
    a  db 10
    b  dw 40
segment  code use32 class=code
start:
    mov  AX, [b]
    div  BYTE [a]

Here we specified the size of the operand in the div opcode as BYTE. If I delete that BYTE part, I get an error, so we need to specify it.

segment  data use32 class=data
    a  db 10
    b  dw 40
segment  code use32 class=code
start:
    mov  AH, 2
    mul  AH

Here, we didn't need to specify the size of the operand 2. It just works.

So when do I have to specify the size? Is it as simple as: when I have a variable declared in memory, specify its size? Considering the examples given above, I am inclined to think so, but through my short experience with Assembly I found that it tends to defy my logic as to how things should work.

Also, after illuminating me about when we need to specify the size, can you please also tell me WHY we need to do this? When we need to do it, why do we need to do it? I mean, we already declared the variable, so the type of the variable should be visible to the program, shouldn't it? Why do we need to specify the size, else we get an error?

1 Answers

You don't need to specify an operand size if it can be inferred from something else you did specify. For example, mov only works on two operands of the same size, and AX is a word-sized register, so in mov AX, [b], it can infer that [b] must be word-sized. But you only specify one operand to div, so you have to tell it what size [a] is since it doesn't have any information to infer it from.

Related