C++ Macros

chuuuing
Apr 18, 2021

Macro acts more like scripts. Macro #define A bbb replace A with bbb in the code.

#define oldmax(x, y) ((x)>(y)?(x):(y))q = oldmax(abc, 123);

After the preprocessor goes through the code, it will look like this:

q = ((abc)>(123)?(abc):(123));

Macro operators

##

The ## operator takes two separate tokens and pastes them together to form a single token.

Following macro can be used to initialize the variables in the beginning.
(Note you can use \to type in new line.)

#define INITIALIZATION(type, varname, value) \
type orig_##varname = value;

After declaration, we can use it like the follows:

#include <string>
INITIALIZATION( std::string, name, “Cindy” );
INITIALIZATION( float, weight, 55.0f );
INITIALIZATION( float, height, 166.0f );

Test for output:

std::cout <<"orig_name = " << orig_name <<endl; 
std::cout <<"orig_weight = " << orig_weight <<endl;
std::cout <<"orig_height = " << orig_height <<endl;

--

--