Preprocessor and Build Boundaries
Macro Constants
An object-like macro can name a compile-time text replacement, while a normal variable still changes at runtime.
macro constant
A macro constant is replaced by the preprocessor before the compiler sees the program.
Macro Constants
macro_constants.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
#define TAX_PERCENT 8
#if TAX_PERCENT == 8
constexpr int taxPercent = 8;
#else
constexpr int taxPercent = 0;
#endif
int main() {
int subtotal = 25;
int tax = subtotal * taxPercent / 100;
int total = subtotal + tax;
std::cout << "subtotal=" << subtotal << std::endl;
std::cout << "tax=" << tax << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
#include <iostream>
#define TAX_PERCENT 8
#if TAX_PERCENT == 8
constexpr int taxPercent = 8;
#else
constexpr int taxPercent = 0;
#endif
int main() {
int subtotal = 10;
int tax = subtotal * taxPercent / 100;
int total = subtotal + tax;
std::cout << "subtotal=" << subtotal << std::endl;
std::cout << "tax=" << tax << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
#include <iostream>
#define TAX_PERCENT 8
#if TAX_PERCENT == 8
constexpr int taxPercent = 8;
#else
constexpr int taxPercent = 0;
#endif
int main() {
int subtotal = 40;
int tax = subtotal * taxPercent / 100;
int total = subtotal + tax;
std::cout << "subtotal=" << subtotal << std::endl;
std::cout << "tax=" << tax << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
subtotal ← 25, tax ← 2, total ← 27
11int main() {12 int subtotal→ 25 = 25; //@subtotal=10, 401314 int tax→ 2 = subtotal25 * taxPercent8 / 100;15 int total→ 27 = subtotal25 + tax2;1617 std::cout << "subtotal=" << subtotal25 << std::endl;18 std::cout << "tax=" << tax2 << std::endl;19 std::cout << "total=" << total27 << std::endl;20 return 0;21}outputsubtotal=25 tax=2 total=27
subtotal ← 10, tax ← 0, total ← 10
11int main() {12 int subtotal→ 10 = 10;1314 int tax→ 0 = subtotal10 * taxPercent8 / 100;15 int total→ 10 = subtotal10 + tax0;1617 std::cout << "subtotal=" << subtotal10 << std::endl;18 std::cout << "tax=" << tax0 << std::endl;19 std::cout << "total=" << total10 << std::endl;20 return 0;21}outputsubtotal=10 tax=0 total=10
subtotal ← 40, tax ← 3, total ← 43
11int main() {12 int subtotal→ 40 = 40;1314 int tax→ 3 = subtotal40 * taxPercent8 / 100;15 int total→ 43 = subtotal40 + tax3;1617 std::cout << "subtotal=" << subtotal40 << std::endl;18 std::cout << "tax=" << tax3 << std::endl;19 std::cout << "total=" << total43 << std::endl;20 return 0;21}outputsubtotal=40 tax=3 total=43