Macros

C++ macros are from a class of C++ commands called preprocessor directives. A preprocessor directive is executed before compilation takes place.

Macros start with #define. For example, say we have the following macro:

#define PI 3.14159

At the lowest level, macros are simply copy and paste operations that occur just before compile time. In the preceding macro statement, the 3.14159 literal will be copied and pasted everywhere the symbol PI occurs in the program.

Take an example of the following code:

#include <iostream>
using namespace std;
#define PI 3.14159
int main()
{
  double r = 4;
  cout << "Circumference is " << 2*PI*r << endl;
}

What the C++ preprocessor will do is first go through the code and look for any usage of the PI symbol. It will find one such usage on this line:

cout << "Circumference is " << 2*PI*r << endl;

The preceding line will convert to the following just before compilation:

cout << "Circumference is " << 2*3.14159*r << endl;

So, all that happens with a #define statement is that all the occurrences of the symbol used (example, PI) are replaced by the literal number 3.14159 even before compilation occurs. The point of using macros in this way is to avoid hardcoding numbers into the code. Symbols are typically easier to read than big, long numbers.

Advice – try to use const variables where possible

You can use macros to define constant variables. You can also use const variable expressions instead. So, say we have the following line of code:

#define PI 3.14159

We will be encouraged to use the following instead:

const double PI = 3.14159;

Using a const variable will be encouraged because it stores your value inside an actual variable. The variable is typed, and typed data is a good thing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.48.204