Parameterized macro

In computer science, a parameterized macro is a type of macro that is able to insert given objects into its expansion. This gives the macro some of the power of a function.

As a simple example, in the C programming language, this is a typical macro that is not a parameterized macro:

 #define PI   3.14159

This causes the string "PI" to be replaced with "3.14159" wherever it occurs. It will always be replaced by this string, and the resulting string cannot be modified in any way. An example of a parameterized macro, on the other hand, is this:

 #define pred(x)  ((x)-1)

What this macro expands to depends on what argument x is passed to it. Here are some possible expansions:

 pred(2)    →  ((2)   -1)
 pred(y+2)  →  ((y+2) -1)
 pred(f(5)) →  ((f(5))-1)

Parameterized macros are a useful source-level mechanism for performing in-line expansion, but in languages such as C where they use simple textual substitution, they have a number of severe disadvantages over other mechanisms for performing in-line expansion, such as inline functions.

The parameterized macros used in languages such as Lisp, PL/I and Scheme, on the other hand, are much more powerful, able to make decisions about what code to produce based on their arguments; thus, they can effectively be used to perform run-time code generation.


This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.