1. Basic Concept of Labels
In assembly language, a label is a symbolic name used to mark memory addresses. In 8086 assembly, there are two types of labels:
- Regular Labels: Represents only the address of a memory unit
- Labels with Unit Length: Represents not only the address but also implicitly includes the length information of the data at that address
2. Labels with Unit Length
1. Characteristics
- Clearly indicates the data type of the memory unit (byte, word, etc.)
- The compiler performs length checks based on the label type
- Improves code readability and safety
2. Type Indicators
<span>db</span>: Defines a byte label<span>dw</span>: Defines a word label<span>dd</span>: Defines a double word label
3. Analysis of the Improved Program
assume cs:code
code segment
a db 1,2,3,4,5,6,7,8 ; Byte label a
b dw 0 ; Word label b
start:
mov si, 0 ; Initialize index
mov cx, 8 ; Loop count
s:
mov al, a[si] ; Use label a (byte type)
mov ah, 0 ; Clear ah
add b, ax ; Use label b (word type)
inc si ; Increment index
loop s ; Loop
mov ax, 4c00h
int 21h
code ends
end start
Analysis of Improvements:
- Label
<span>a</span>is explicitly declared as<span>db</span>(byte type) - Label
<span>b</span>is explicitly declared as<span>dw</span>(word type) - Memory access uses the label directly without needing the
<span>cs:</span>prefix - Array access using
<span>a[si]</span>is more intuitive
4. Advantages of Unit Length Labels
-
Type Safety: The compiler checks whether operations match the label type
mov ax, a[0] ; Error: Attempting to load byte data into a word register -
Concise Code: No need to frequently use
<span>byte ptr</span>or<span>word ptr</span> -
Strong Readability: The data type can be inferred from the label
-
Easy Maintenance: Changing the data type only requires modifying the definition
5. Practical Application Examples
Example 1: Operations on Different Data Types
data segment
count db 100 ; Byte variable
total dw 0 ; Word variable
array db 10 dup(?) ; Byte array
data ends
code segment
mov al, count ; Correct: byte to byte
add total, ax ; Correct: word to word
mov array[3], al ; Correct: byte to byte
; mov ax, count ; Error: type mismatch
code ends
Example 2: Struct Simulation
student struct
id dw ? ; Word type
age db ? ; Byte type
score dw ? ; Word type
student ends
data segment
class student 30 dup(<>) ; Array of 30 students
data ends
code segment
; Access the age of the second student
mov al, class[1*type student].age
code ends
6. Precautions
- The scope of labels is limited to the current segment
- Labels must be correctly defined before use
- Segment prefixes are still required for cross-segment access
- Array index out of bounds will not be automatically checked
Unit length labels are an important technique in assembly language to improve code quality and maintainability. Proper use can significantly reduce errors caused by data type mismatches.