Programming & Scripting Tutorials

C++: Preprocessor Directives





Define



Preprocessing occurs before the code is compiled and Preprocessor Directives are proceded by the hash symbol (#). This is a simple program which uses the preprocessor directive keywords define and include:

#define PI 3.14159

#include <iostream>

using namespace std;

int main(){
	double radius = 4.2;
	double Area = PI*radius*radius;
		cout << "Radius : " << radius << "\nArea : " <<  Area << endl;
	system("PAUSE");
return 0;
}
Download

When the compiler compiles the code it pastes all the code from iostream where the include statement was, and then changes every time "PI" is typed to 3.14159. We have used include statements in almost all the applications we have created so far but did not look at them like this.

Macros



Another common use for preprocessor directives is creating macros; Like the previous define directive we use the define keyword, but macros behave slightly differently and are a bit like functions:

#include <iostream>

#define MACRO1(one, two) (one*two)

using namespace std;

int main(){
double a = 1;
double b = 2;
double mac1 = MACRO1(a, b);
cout << mac1 << endl;
system("PAUSE");
}

As you have probably figured out this would display "2" on the screen.


Conditionals



We can also use conditionals to determine what code should be compiled, unlike normal if statements this determines which bits code should be compiled not which bit of code should be executed.
Like normal if statements we can have elseif and else branches. The following code demonstrates these conditionals:

#include <iostream>

#define A 0
#define B 0


using namespace std;

int main(){
int C = 0;
#if A//if statement
	C = 1;
#elif B//elseif statement
	C = 2;
#else //else statement
	C = 3;
#endif
cout << C << endl;
system("PAUSE");
return 0;
}

As you may have noticed from running the program these conditionals dont behave like normal ones do, and if the expression you write (after the #if) has a nonzero value, it will do whatever is under the #if however if the value is zero it will leave the statement as false, and because we are preprocessing therefore remove that chunk of code. Therefore the above code would display 3, and not other values as you may have expected.


#undef



We can also use "#undef NAME" to undefine values, and then we can do different things if things are or are not defined using "#ifdef" and "#ifndef" as appropriate. (dont forget to "#endif")

This C++ tutorial was written by


Back to C++

Advertisement: