Macro Functions

The #define directive can also be used to create macro functions. A macro function is created using #define. Macros take arguments much like functions do. The preprocessor will substitute the substitution string for whatever argument it is given. For example, you can define the macro TWICE as

#define TWICE(x) ( (x) * 2 )

and then write in your code

TWICE(4)

The entire string TWICE(4) will be removed, and the value 8 will be substituted! When the precompiler sees the 4, it will substitute ( (4) * 2 ), which will then evaluate to 4 * 2 or 8.

A macro can have more than one parameter, and each parameter can be used repeatedly in the replacement text. Two common macros are MAX and MIN:

 #define MAX(x,y) ( (x) > (y) ? (x) : (y) ...

Get Sams Teach Yourself C++ in 24 Hours, 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.