Programming and Graphics

(Kiana) #1

3.10 Preprocessor define and undefine 89


#define print cout<<

int main()
{
stringa="hello";
print a;
print endl;
return 0;
}

Running the code prints on the screen:


hello

The preprocessor has substituted the C++ command “cout <<” for every in-
stance of the “print” statement in the code. Effectively, “print” has become
a macro for “cout <<”.


A macro can be removed at any time using theundef preprocessor
directive. As an example, consider the code:


#include <iostream>
using namespace std;
#define print cout <<

int main()
{
#define eol << endl
string a = "hello";
print a eol;
#undef eol
#define eol << " for your business" << endl
string b = "thank you";
print b eol;
return 0;
}

Running the code prints on the screen:


hello
thank you for your business

Thedefinepreprocessor directive may also be used to implement simple
functions. For example, the block of commands:


#define square(x) x*x;
double e = 5.0;
Free download pdf