What is the difference between templates and macros in C++?

PointTemplateMacro
Done byCompilerPreprocessor (text)
Type safeYesNo
Scope and namespacesYesNo
DebuggingNormalHard
Side effectsNoneArguments can be evaluated twice
#include <iostream>

#define SQUARE(x) x * x

template <typename T>
constexpr T square(T x) { return x * x; }

int main() {
    int n = 3;
    std::cout << SQUARE(n + 1) << '\n';          // becomes n + 1 * n + 1 = 7: a macro bug
    std::cout << square(n + 1) << '\n';          // 16: correct
}
Output

7
16

Use constexpr, const, templates and inline functions instead of macros. Macros stay useful for include guards and conditional compiling. See Templates.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.