Introduction
Macros allow replacement of the identifier by using a statement or expression. The replacement text is called the macro body. C uses macros extensively in its standard header files, such as in getchar(), getc().
Program
#define CUBE(x) x*x*x //A #includemain () { int k = 5; int j = 0; j = CUBE(k); //B j = k*k*k printf ("value of j is %d\n", j); //C }
Explanation
-
The macro can be defined by using parameters, but that is not mandatory.
-
The parameter name that is used in a macro definition is called the formal parameter. In this example, it is x.
-
x*x*x is called the macro body.
-
There should not be any spaces between the macro name and the left parenthesis.
-
CUBE(k) in statement B indicates a macro call.
-
An argument such as k, which is used for calling a macro, is called an actual parameter.
-
While expanding the macro, the actual parameter is substituted in the formal parameter and the macro is expanded. So you will get the expansion as j = k*k*k.
-
The value of j is calculated as 125.
-
Since macro expansion is mainly a replacement, you can use any data type for the actual parameter. So, the above macro works well for the float data type.
Points to Remember
-
A macro is used when you want to replace a symbol with an expression or a statement.
-
You can define macros by using parameters.
No comments:
Post a Comment