With the FOR directive you can iterate through a list of arguments, doing some operation on each of them in turn. It has the following syntax:
FOR parameter, <argumentlist>
statements
ENDM
The parameter is a placeholder that will be used as the name of each argument inside the FOR block. The argument list must be a list of comma-separated arguments and must always be enclosed in angle brackets, as the following example illustrates: <$I<< \ra (angle brackets);FOR loops>
series LABEL BYTE
FOR arg, <1,2,3,4,5,6,7,8,9,10>
BYTE arg DUP (arg)
ENDM
On the first iteration, the arg parameter is replaced with the first argument, the value 1. On the second iteration arg is replaced with 2. The result is an array with the first byte initialized to 1, the next two bytes initialized to 2, the next three bytes initialized to 3, and so on.
In this example the argument list is given specifically, but in some cases the list must be generated as a text macro. The value of the text macro must include the angle brackets.
arglist TEXTEQU <!<3,6,9!>> ; Generate list as text macro
FOR arg, arglist
. ; Do something to arg
.
.
ENDM
Note the use of the literal character operator (!) to use angle brackets as characters, not delimiters (see Section 9.3.1).
Summary: Variable parameter lists provide flexibility.
The FOR directive also provides a convenient way to process macros with a variable number of arguments. To do this, add VARARG to the last parameter to indicate that a single named parameter will have the actual value of all additional arguments. For example, the following macro definition includes the three possible parameter attributes—required, default, and variable.
work MACRO rarg:REQ, darg:=<5>, varg:VARARG
The variable argument must always come last. If this macro is called with the statement
work 5, , 6, 7, a, b
the first argument is received as passed, the second is replaced by the default value 5, and the last four are received as the single argument <6, 7, a, b>. This is the same format expected by the FOR directive. The FOR directive discards leading spaces but recognizes trailing spaces.
The following macro illustrates variable arguments:
show MACRO chr:VARARG
mov ah, 02h
FOR arg, <chr>
mov dl, arg
int 21h
ENDM
ENDM
When called with
show 'O', 'K', 13, 10
the macro displays each of the specified characters one at a time.
The parameter in a FOR loop can have the required or default attribute. The show macro can be modified to make blank arguments generate errors:
show MACRO chr:VARARG
mov ah, 02h
FOR arg:REQ, <chr>
mov dl, arg
int 21h
ENDM
ENDM
The macro now generates an error if called with
show 'O',, 'K', 13, 10
Another approach would be to use a default argument:
show MACRO chr:VARARG
mov ah, 02h
FOR arg:=<' '>, <chr>
mov dl, arg
int 21h
ENDM
ENDM
Now if the macro is called with
show 'O',, 'K', 13, 10
it inserts the default character, a space, for the blank argument.