Preprocessor and Build Boundaries
Function Macros
Function-like macros copy text; this example shows the expanded expression beside a safer inline function call.
Function Macros
function_macros.cpp
#include <iostream>
#define ADD_TEN_BAD(x) x + 10
inline int addTen(int value) {
return value + 10;
}
int main() {
int value = ;
int textReplacementResult = value + 10 * 2;
int functionResult = addTen(value) * 2;
std::cout << "value=" << value << std::endl;
std::cout << "textReplacementResult=" << textReplacementResult << std::endl;
std::cout << "functionResult=" << functionResult << std::endl;
return 0;
}
#include <iostream>
#define ADD_TEN_BAD(x) x + 10
inline int addTen(int value) {
return value + 10;
}
int main() {
int value = ;
int textReplacementResult = value + 10 * 2;
int functionResult = addTen(value) * 2;
std::cout << "value=" << value << std::endl;
std::cout << "textReplacementResult=" << textReplacementResult << std::endl;
std::cout << "functionResult=" << functionResult << std::endl;
return 0;
}
#include <iostream>
#define ADD_TEN_BAD(x) x + 10
inline int addTen(int value) {
return value + 10;
}
int main() {
int value = ;
int textReplacementResult = value + 10 * 2;
int functionResult = addTen(value) * 2;
std::cout << "value=" << value << std::endl;
std::cout << "textReplacementResult=" << textReplacementResult << std::endl;
std::cout << "functionResult=" << functionResult << std::endl;
return 0;
}
function-like macro
A function-like macro can look like a function call, but the preprocessor still treats it as text replacement.