Macros with Arguments
The #define directive can also be used to define macros with arguments. The general syntax is-
#define macro_name(arg 1, arg2, ......) macro_expansion
Here argl, arg2 .... are the fonnal arguments. The macro_name is replaced with the macro_expansion
and the formal arguments are replaced by the corresponding actual arguments supplied in the macro
call. So the macro_expansion will be different for different actual arguments.
For example, suppose we define these two macros-
#define SUM(x, y) ( (x) + (y) )
#define PROD(x, y) ( (x) * (y) )
Now suppose we have these two statements in our program
s= SUM(5, 6);
p = PROD(m, n);
After passing through the preprocessor these statements would be expanded as
s= ( (5) + (6) );)
p = ( (m) * (n) );)
Since this is just a replacement of text, the arguments can be of any data type.
#include
#define SUM(x,y) ((x) + (y))
#define SQUARE(e) ((e)*(e))
#define DECREMENT_BY_1(y) ((y--))
int main() {
int m = 10, n = 20;
int sum = SUM(a,b);
int val_dec_by_1 = DECREMENT_BY_1(m);
printf("sum = %d, square = %d, dec_by_1 = %d", sum, SQUARE(10),val_dec_by_1);
return 0;
}
OUTPUT: sum = 30, square = 100, dec_by_1 = 9
This code defines three macros using the #define preprocessor directive: SUM(x,y)
, SQUARE(e)
, and DECREMENT_BY_1(y)
.
The SUM macro takes two arguments x and y and returns their sum.
The SQUARE macro takes a single argument e and returns its square (i.e., e * e).
The DECREMENT_BY_1 macro takes a single argument y, decrements it by one, and returns the new value of y.
Let us see some more examples of macros with arguments -
#define SQUARE(x) ( (x)*(x) )
#define MAX( x, y ) ( (x) > (y) ? (x) : (y) )
#define MIN( x, y ) ( (x) < (y) ? (x) : (y)
#define ISLOVvER(c) ( c >= 97 && c <= 122 )
#define ISUPPER(c) ( c >= 65 && c <= 90 )
#define TOUPPER(c) ( (c) + 'A' - 'a' )
#define ISLEAP(y) ( (y%400 = = 0) II ( y%100!=0 && y%4 = = 0) )
#define BLANK_LINES(n) { int i; fore i = 0; i < n; i++ ) printf("\n"); }
#define CIRCLE_AREA(rad) ( 3.14 * (rad) *(rad) )