Tuesday, 6 October 2009

Using Preprocessor Statements #ifdef, #elif, #else and #endif

Sometimes it becomes necessary to write two (or more) different peices of behaviour in a common code. Depending of its mode/place/time/version the behaviour has to be changed. It can be done by the use of simple preprocessor statements. Consider the following program:

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to show use of preprocessor macros for dynamic behaviour


using namespace

#define USE_CAR //Comment or Uncomment this if using preprocessor option


someNum = 3;
#ifdef USE_CAR
string modeOfTransport("Use a Car");
#elif USE_BUS
string modeOfTransport("Use a Bus");
string modeOfTransport("Use a Train");
string modeOfTransport("Use any mode of transport");

cout<<"Mode of Transport = "<<modeOfTransport<<" and someNum = "<<someNum<<endl;


The output is as follows:

In the program above, the statement in the start #define USE_CAR says that the code with USE_CAR should be used during compile time. Instead if USE_BUS is defined, that particular peice of code will be used. If nothing is defined then the behaviour with else will be used.

There is another way to use these preprocessor directives. It is by defining in the properties below. If defined this way then the statement should be omitted from the main program.

The output is as follows in this case:

For more information see this.

No comments:

Post a Comment