defining macros with parameters defining constant macro # define macro_name value for example: #...
TRANSCRIPT
Defining Macros with Parameters
• Defining constant macro
# define macro_name value
For example:
# define KMS_PER_MILE 1.609
• Defining macro with parameters
# define macro_name(parameter lis) macro body
For example:
# define SQUARE(n) ((n) * (n))
/* Shows the definition and use of a macro */
#include <stdio.h>#define LABEL_PRINT_INT(label, num) \ printf("%s = %d", (label), (num))intmain(void){ int r = 5, t = 12; LABEL_PRINT_INT("rabbit", r); printf(" "); LABEL_PRINT_INT("tiger", t + 2); printf("\n"); return(0);}
rabbit = 5 tiger = 14
Program Using a Macro with Parameters
Macro Expansion
LABEL_PRINT_INT(“tiger”, t+2) LABEL_PRINT_INT(“tiger”, t+2) Second Second macro call in the mainmacro call in the main
LABEL_PRINT_INT(label, num) LABEL_PRINT_INT(label, num)
Parameter matching: Parameter matching: tiger t+2tiger t+2
printf(“%s = %d”, (label), (num)) printf(“%s = %d”, (label), (num))
parameter replacement in body
printf(“%s = %d”, (“tiger”), (t+2))printf(“%s = %d”, (“tiger”), (t+2))
Rules for Defining Macros with parameters
• Same as constant macro there is no “;” at the end of macro definition
• To extend a macro over multiple lines, all except for the last line must end with backslash character “/”
• Operators with side effect should not be used as macro arguments.
For example #define RT(++a) is wrong
Rules for Defining Macros with parameters• Using the parenthesis for the formal parameters in Macro body is required to
avoid the effect of operator precedence in macro expansion. For example:Version 1 Version 2
#define SQUARE(n) n * n #define SQUARE(n) ((n) * (n)) SQUARE(x + y) SQUARE(x + y)
becomes becomes
x + y * x + y ((x + y) * (x + y))
Problem: multiplication done before addition in version 1, also.
SQUARE(m) / SQUARE(n) SQUARE(m) / SQUARE(n)
becomes becomes
m * m / n * n ((m) * (m)) / ((n) * (n)) Therefore, the result produced by version 1 is wrong
More examples of Macro with Parameters
• # define ROOT1(a, b, c) \((-(b) + sqrt((b) * (b) – 4 * (a) * (c))) / (2 * (a)))
Can be used in the main as r = ROOT1(n1, n2, n3);• # define INDEXED-FOR(ct, st, end) \ for ((ct) = (st); (ct) < (end); ++(ct)) Can be used in the main as INDEXED_FOR(i,0,X_MAX) printf(“x[%2d] = %6.2f\n”, i, x[i]);