A macro is a name that the preprocessor replaces with text before the compiler reads the code. In C and C++, you create one with the #define directive. The mechanism is the same in both languages, so the examples here use C++ syntax.
How a macro is defined
There are two kinds:
#define MAX_SIZE 100 // object-like: a name for some text
#define SQUARE(x) ((x) * (x)) // function-like: takes a parameter
An object-like macro has no parameter list. Each use of MAX_SIZE is replaced with 100. A function-like macro has a parameter list in parentheses, and the opening parenthesis must come directly after the name, with no space. With a space before the parenthesis, the macro is object-like instead, and its whole text becomes the replacement.
What the preprocessor does with them
The preprocessor reads the source text before the compiler does. It handles each line that starts with #, which is called a directive, and it replaces macro names with their text. In simple terms, it:
- copies the contents of any file named in
#include - records each
#defineand removes each#undef - keeps or drops blocks marked with
#if,#ifdefor#ifndef - replaces each macro use with its text, and repeats the replacement if that text contains more macro names
The compiler then receives the resulting text, and it never sees the macro names.
A small example
#include <iostream>
#define MAX_SIZE 3
#define SQUARE(x) ((x) * (x))
int main() {
for (int i = 0; i < MAX_SIZE; ++i) {
std::cout << SQUARE(i) << '\n';
}
}
The program prints 0, 1 and 4, each on its own line. The compiler never sees MAX_SIZE or SQUARE. It sees 3 and ((i) * (i)) in their place.
Common uses
- Named values.
MAX_SIZEabove is a simple case. Modern C++ often prefersconstexprfor constants, because aconstexprvariable has a type and follows normal scope rules. - Header guards. A header guard in C or C++ keeps a header from being processed twice:
#ifndef MY_HEADER_H
#define MY_HEADER_H
// declarations go here
#endif
- Platform checks.
#ifdef _WIN32is a common test for Windows builds, since Windows compilers define_WIN32. - Debug information.
__FILE__and__LINE__are predefined macros that give the file name and line number.
Macros have no types or scope
A macro is text. It has no type, and it does not follow the scope rules that variables and functions do. That is the core of the answer to “Why not use macros in C++?”
A common question is “What is the difference between inline and macro?” An inline function is type-checked, and each argument is evaluated once. A function-like macro only pastes text, so an argument with side effects can run more than once.
Macros belong to the preprocessor, the stage that does this text work before compiling. If you are asking “What is a preprocessor in C?”, the short answer is that it rewrites the source before the compiler reads it.