|
|
|
|
|
|
|
which in turn evaluates to 1,728. THREE(5+7), however, evaluates to |
|
|
|
|
|
|
|
|
Because multiplication has a higher precedence than addition, this becomes |
|
|
|
|
|
|
|
|
5 + (7 * 5) + (7 * 5) + 7 |
|
|
|
|
|
|
|
|
which finally evaluates to 82. |
|
|
|
|
|
|
|
|
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 in line each time they are used. This means that if a macro is used a dozen times, the substitution will appear 12 times in your program, rather than once as a function call will. 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, and thus is unavailable in most debuggers. This makes debugging macros tricky. |
|
|
|
|
|
|
|
|
The final problem, however, is the biggest: macros are not type-safe. While it is convenient that absolutely any argument can be used with a macro, this completely undermines the strong typing of C++ and so is anathema to C++ programmers. Templates overcome this problem, as you'll see in two hours. |
|
|
|
|
|
|
|
|
The preprocessor provides two special operators for manipulating string in macros. The stringizing operator (#) substitutes a quoted string for whatever follows the stringizing operator. The concatenation operator bonds two strings together into one. |
|
|
|
|
|
|
|
|
The stringizing operator (#) puts quotes around any characters following the operator, up to the next white space. So, if you write: |
|
|
|
|
|
|
|
|
#define WRITESTRING(x) cout << #x |
|
|
|
|
|