Home Segments Index Top Previous Next

136: Sidetrip

Rather than define pi yourself, you can rely, if you wish, on C++'s library of mathematics constants and functions, which contains various macros.

Before the main work of translation to machine code begins, the C++ compiler replaces each instance of each macro identifier by a character sequence prescribed in the macro's declaration. Thus, the C++ compiler replaces the four characters in M_PI—a macro available in most modern versions of the C++ mathematics library—by the seven characters in 3.14159 (or probably by a longer, machine-dependent sequence of characters).

Note that M_PI is an upper-case-only identifier, because C++ programmers generally adhere to an upper-case-only convention when declaring macros.

To use the M_PI macro, you replace the definition, const double pi = 3.14159, with a line that loads information from the mathematics library:

#include  
// Use the mathematics library, which contains a declaration for M_PI: 
#include  
// Then, define tank_car_volume, a function that uses M_PI: 
double tank_car_volume (double r, double l) { 
  return M_PI * r * r * l; 
} 
// Then, define main: 
main ( ) { 
  cout << "The volume of a standard tank car is " 
       << tank_car_volume (3.5, 40.0) << endl; 
} 
--- Result --- 
The volume of a standard tank car is 1539.38