What is the concept of macros in programming languages ?
What is the concept of macros in programming languages ?
A macro is a fragment of code which has been given a name called macroname. Whenever the macroname is used in developing a program, it is replaced by the contents of the macro.
There are two kinds of macros. They mostly differ in what they look like when they are used.
- Object-like macros resemble data objects when used,
- Function-like macros resemble function calls.
In programming, macro represents the segment of code. It has to be defined along with the header files.
It is represented as :
In C :
#include<stdio.h>
#define macro macroname
void main ()
{
-------
-------
}
In C++ :
#include<iostream.h>
#define macro macroname
void main ()
{
-------
-------
}
There are two types of macros, object-like and function-like.
Object-like macros do not take parameters; function-like macros do.
The generic syntax for declaring an identifier as a macro of each type is, respectively,
#define <identifier> <replacement token list>
#define <identifier>(<parameter list>) <replacement token list>
Note that the function-like macro declaration must not have any whitespace between the identifier and the first, opening, parenthesis. If whitespace is present, the macro will be interpreted as object-like with everything starting from the first parenthesis added to the token list.
Whenever the identifier appears in the source code it is replaced with the replacement token list, which can be empty. For an identifier declared to be a function-like macro, it is only replaced when the following token is also a left parenthesis that begins the argument list of the macro invocation. The exact procedure followed for expansion of function-like macros with arguments is subtle.
Object-like macros were conventionally used as part of good programming practice to create symbolic names for constants, e.g.
#define PI 3.14159
instead of hard-coding those numbers throughout one's code. However, both C and C++ provide the const directive, which provides another way to avoid hard-coding constants throughout the code.
An example of a function-like macro is
#define RADTODEG(x) ((x) * 57.29578)
This defines a radians to degrees conversion which can be written subsequently, e.g. RADTODEG(34) or RADTODEG (34). This is expanded in-place, so the caller does not need to litter copies of the multiplication constant all over his code. The macro here is written as all uppercase to emphasize that it is a macro, not a compiled function.
Bookmarks