O'Reilly logo

Sams Teach Yourself C++ in 24 Hours, Third Edition by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required