A C Preprocessor Macro Example
C and C++ macros perform literal, raw text replacement.
This allows developers substantial freedom to write C or C++ programs as sequences of tokens that look little like normal code before preprocessing:
#include <iostream>
#define BEGIN () {
#define END }
#define EXPECT(check) if (idx check) {}
#define OR else
#define DIE PanicFormatter() <<
class PanicFormatter {
public:
void operator<<(const char *message) {
std::cerr << message << std::endl; exit(1);
}
};
int main BEGIN
for (int idx = 0; idx < 10; idx++) {
EXPECT(< 10) OR DIE "Uh-Oh!";
}
END
Key takeaways from this example:
- Custom Syntax: Using
BEGINandENDin place of braces is not permitted by C itself, and would surprise most readers, but as the preprocessing runs before compilation, the compiler just sees the braces to which these macros expand. - Unhygienic State Access: The
EXPECTmacro implicitly accessesidx, which is defined inmainand not passed into the macro. This makes the macro’s effect depend on the context in which it is invoked (e.g., supposeidxwas a pointer to astruct BTreeIndex).
- Explain the C preprocessor operates as a pure copy-paste system. It replaces tokens line by line without any syntactic structure check.
- Notice how
EXPECT(< 10)expands toif (idx < 10) {}. The macro assumesidxexists and is accessible. - If someone uses
EXPECTinside a function withoutidx, they get a compiler error at the expansion site, not the macro definition site, which can lead to confusing and hard-to-debug compiler errors.