Jump to content

Parameterized macro

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Erik9bot (talk | contribs) at 02:49, 3 August 2009 (remove Category:Articles lacking sources (Erik9bot)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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.