GNU Info

Info Node: (nasm.info)Section 4.3.3

(nasm.info)Section 4.3.3


Next: Section 4.3.4 Prev: Section 4.3.2 Up: Section 4.3
Enter node , (file) or (file)node

4.3.3. Greedy Macro Parameters
------------------------------

   Occasionally it is useful to define a macro which lumps its entire
command line into one parameter definition, possibly after extracting
one or two smaller parameters from the front. An example might be a
macro to write a text string to a file in MS-DOS, where you might want
to be able to write

             writefile [filehandle],"hello, world",13,10

   NASM allows you to define the last parameter of a macro to be
_greedy_, meaning that if you invoke the macro with more parameters
than it expects, all the spare parameters get lumped into the last
defined one along with the separating commas. So if you code:

     %macro  writefile 2+
     
             jmp     %%endstr
       %%str:        db      %2
       %%endstr:
             mov     dx,%%str
             mov     cx,%%endstr-%%str
             mov     bx,%1
             mov     ah,0x40
             int     0x21
     
     %endmacro

   then the example call to `writefile' above will work as expected: the
text before the first comma, `[filehandle]', is used as the first macro
parameter and expanded when `%1' is referred to, and all the subsequent
text is lumped into `%2' and placed after the `db'.

   The greedy nature of the macro is indicated to NASM by the use of the
`+' sign after the parameter count on the `%macro' line.

   If you define a greedy macro, you are effectively telling NASM how it
should expand the macro given _any_ number of parameters from the
actual number specified up to infinity; in this case, for example, NASM
now knows what to do when it sees a call to `writefile' with 2, 3, 4 or
more parameters. NASM will take this into account when overloading
macros, and will not allow you to define another form of `writefile'
taking 4 parameters (for example).

   Of course, the above macro could have been implemented as a
non-greedy macro, in which case the call to it would have had to look
like

               writefile [filehandle], {"hello, world",13,10}

   NASM provides both mechanisms for putting commas in macro
parameters, and you choose which one you prefer for each macro
definition.

   See *Note Section 5.2.1:: for a better way to write the above macro.


automatically generated by info2www version 1.2.2.9