Function-like Macros That Take Arguments

Like any user-defined function, user-defined function-like macros can also take arguments:

#define OOPS(X) printf("Oh no, %s!", X)

With that macro, any C code like this:

OOPS("Tim");

is turned into

printf("Oh no, %s!", "Tim");

during preprocessing.

Or, consider the following, more complex example:

#define AVE(X,Y)  ((X)+(Y))/2

The AVE macro now represents the code for calculating the average of two numbers. So this C code:

printf ("The average of %.1f and %.1f is
 %.2f.\n", 20.0, 118.0,
 AVE(20.0,118.0)); ...

Get C Programming: Visual Quickstart Guide 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.