Introduces you to the definition of symbolic constants and macros illustrating
their significance and use. In addition, standard macros for character handling
are introduced.
Macros
Sample program
// sintab.cpp // Creates a sine function table #include <iostream> #include <iomanip> #include <cmath> using namespace std; #define PI 3.1415926536 #define START 0.0 // Lower limit #define END (2.0 * PI) // Upper limit #define STEP (PI / 8.0) // Step width #define HEADER (cout << \ " ***** Sine Function Table *****\n\n") int main() { HEADER; // Title // Table Head: cout << setw(16) << "x" << setw(20) << "sin(x)\n" << " -----------------------------------------" << fixed << endl; double x; for( x = START; x < END + STEP/2; x += STEP) cout << setw(20) << x << setw(16) << sin(x) << endl; cout << endl << endl; return 0; }
Screen output
****** Table for the Sine Function ****** x sin(x) -------------------------------------------- 0.000000 0.000000 0.392699 0.382683 0.785398 0.707107 . . . . . .
C++ has a simple mechanism for naming constants or sequences of
commands, that is for defining macros. You simply use the
preprocessor's #define directive.
Syntax:
#define name substitutetext
This defines a macro called name. The
preprocessor replaces name with substitutetext throughout the subsequent program. For
example, in the program on the opposite page, the name PI is replaced by the number 3.1415926536 throughout the program in the first phase of
compilation.
There is one exception to this general rule: substitution does not
take place within strings. For example, the statement
cout << "PI";
outputs only PI and not the numerical
value of PI.
Symbolic Constants
Macros that are replaced by constants, such as the PI macro, are also known as symbolic
constants. You should note that neither an equals sign nor a semicolon is
used, as these would become part of the substitute text.
You can use any macros you have previously defined in
subsequent #define directives. The program opposite
uses the symbolic constant PI to define other
constants.
More about Working with Macros
Any preprocessor directive, and this includes the #define directive, must be placed in a line of its own. If
the substitute text is longer than one line, you can terminate the line with a
backslash \ and continue the substitute text in the
next line, as is illustrated by the macro HEADER on the
opposite page.
The rules that apply to naming variables also apply to naming
macros. However, it is standard practice to capitalize symbolic constants to
distinguish them from the names of variables in a program.
Using macros makes a C++ program more transparent and flexible.
There are two main advantages:
-
good readability: You can name a macro to indicate the use of the macro
-
easy to modify: If you need to change the value of a constant throughout a program, you simply change the value of the symbolic constant in the #define directive.
0 Comments