Using Arguments with #define
By using arguments, you can create macros that look and act much like functions. A macro with arguments looks very similar to a function because the arguments are enclosed within parentheses. Listing 16.2 provides some examples that illustrate how such a macro function is defined and used. Some of the examples also point out possible pitfalls, so read them carefully.
Listing 16.2 The mac_arg.c program.
/* mac_arg.c -- macros with arguments */ #include <stdio.h> #define SQUARE(X) X*X #define PR(X) printf("The result is %d.\n", X) int main(void) { int x = 4; int z; z = SQUARE(x); PR(z); z = SQUARE(2); PR(z); PR(SQUARE(x+2)); PR(100/SQUARE(2)); printf("x is %d\n.", x); PR(SQUARE(++x)); printf("After incrementing, ... |
Get C Primer Plus®, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.