Navigation: Introduction to Programming

Tutorial 7 - The Pre-Processor


A quick tutorial on the pre-processor.

The Pre-Processor

You have come across the # hash symbol at the top of some c++ files. This # symbol is used to declare pre-processor directives or statements. The pre-processor is part of the compiler or the compile process that processes anything declared with a # first before anything else. It will include headers for example in .cpp files before it actually compiles any code. You can use # pre-processor directives to control what code is actually compiled using some conditions and you can also declare Macros with the # symbol using some special syntax. A macro is a function or variable.


You can use the #define anywhere in your code to define some constant like pi or some other constant:
#define pi 3.14159265359

#define my_constant 67

int myfunc()
	int x = 2 + my_constant;

	return x;


#include "myheader.h"

#ifdef, #endif

#ifdef means if defined
#endif is like a closing bracket
#define A

#ifdef A
int my_var = 2;
Here A is defined so int my_var = 2 will be compiled.

You can use #ifdef to test different parts of your program for example you might want to see what happens with one function and then you might want to see what happens if you use a different function instead.

	int MyFunc()
		return 5;
	int MyFunc()
		return 7;
Then you would remove the line #define USE_FIRST_FUNCTION to use the second function instead. The second function would be used because USE_FIRST_FUNCTION is no longer defined.

A common use for #ifdef is to toggle between a Debug build and a Release build. For example, you might use some code in a debug build and other code instead in a release build:
#ifdef DEBUG
	//Use this code.
	//Release Build.
	//Use this code.


#ifndef means if not defined
int n = 3;
If SOMETHING is not defined with #define then int n = 3; will compile.


A macro can mean a function defined in the pre-processor stage.
Note: Special syntax is required to define macros in c++.
#define round(x) \
( \
	(int)(x+0.5) \
The function(Macro) above could be used to round a number.
int n = round(2.3);
The return value of round() is (int)(x+0.5)
Next Tutorial >>