What’s Next 771
21
Macros Versus Functions and Templates
Macros suffer from four problems in C++. The first is that they can be confusing if they
get large because all macros must be defined on one line. You can extend that line by
using the backslash character (\), but large macros quickly become difficult to manage.
The second problem is that macros are expanded inline each time they are used. This
means that if a macro is used a dozen times, the substitution appears a dozen times in
your program, rather than appearing once as a function call does. On the other hand, they
are usually quicker than a function call because the overhead of a function call is
avoided.
The fact that they are expanded inline leads to the third problem, which is that the macro
does not appear in the intermediate source code used by the compiler; therefore, it is
unavailable in most debuggers. This makes debugging macros tricky.
The final problem, however, is the biggest: Macros are not type-safe. Although it is con-
venient that absolutely any argument can be used with a macro, this completely under-
mines the strong typing of C++ and so is an anathema to C++ programmers. Of course,
the right way to solve this is with templates, as you saw on Day 19.
Inline Functions ..................................................................................................
It is often possible to declare an inline function rather than a macro. For example, Listing
21.6 creates an inline Cube()function, which accomplishes the same thing as the CUBE
macro in Listing 21.2, but it does so in a type-safe way.
LISTING21.6 Using Inline Rather than a Macro
0: #include <iostream>
1: using namespace std;
2:
3: inline unsigned long Square(unsigned long a) { return a * a; }
4: inline unsigned long Cube(unsigned long a)
5: { return a * a * a; }
6: int main()
7: {
8: unsigned long x=1 ;
9: for (;;)
10: {
11: cout << “Enter a number (0 to quit): “;
12: cin >> x;
13: if (x == 0)
14: break;
15: cout << “You entered: “ << x;