Menu

C++ TUTORIALS - C++ Preprocessor

C++ Preprocessor

ADVERTISEMENTS

Predefined C++ Macros:

MacroDescription
__LINE__This contain the current line number of the program when it is being compiled.
__FILE__This contain the current file name of the program when it is being compiled.
__DATE__This contains a string of the form month/day/year that is the date of the translation of the source file into object code.
__TIME__This contains a string of the form hour:minute:second that is the time at which the program was compiled.

ADVERTISEMENTS

The #define Preprocessor:

#define macro-name replacement-text 

ADVERTISEMENTS

#include <iostream>
using namespace std;

#define PI 3.14159

int main ()
{
 
    cout << "Value of PI :" << PI << endl; 

    return 0;
}

$gcc -E test.cpp > test.p

...
int main ()
{
 
    cout << "Value of PI :" << 3.14159 << endl; 

    return 0;
}

Function-Like Macros:

#include <iostream>
using namespace std;

#define MIN(a,b) (((a)<(b)) ? a : b)

int main ()
{
   int i, j;
   i = 100;
   j = 30;
   cout <<"The minimum is " << MIN(i, j) << endl;

    return 0;
}

The minimum is 30

Conditional Compilation:

#ifndef NULL
   #define NULL 0
#endif

#ifdef DEBUG
   cerr <<"Variable x = " << x << endl;
#endif

#if 0
   code prevented from compiling
#endif

#include <iostream>
using namespace std;
#define DEBUG

#define MIN(a,b) (((a)<(b)) ? a : b)

int main ()
{
   int i, j;
   i = 100;
   j = 30;
#ifdef DEBUG
   cerr <<"Trace: Inside main function" << endl;
#endif

#if 0
   /* This is commented part */
   cout << MKSTR(HELLO C++) << endl;
#endif

   cout <<"The minimum is " << MIN(i, j) << endl;

#ifdef DEBUG
   cerr <<"Trace: Coming out of main function" << endl;
#endif
    return 0;
}

Trace: Inside main function
The minimum is 30
Trace: Coming out of main function

The # and ## Operators:

#include <iostream>
using namespace std;

#define MKSTR( x ) #x

int main ()
{
    cout << MKSTR(HELLO C++) << endl;

    return 0;
}

HELLO C++

  cout << MKSTR(HELLO C++) << endl;

  cout << "HELLO C++" << endl;

#define CONCAT( x, y )  x ## y

#include <iostream>
using namespace std;

#define concat(a, b) a ## b
int main()
{
   int xy = 100;
   
   cout << concat(x, y);
   return 0;
}

100

  cout << concat(x, y);

  cout << xy;

Predefined C++ Macros:

#include <iostream>
using namespace std;

int main ()
{
    cout << "Value of __LINE__ : " << __LINE__ << endl;
    cout << "Value of __FILE__ : " << __FILE__ << endl;
    cout << "Value of __DATE__ : " << __DATE__ << endl;
    cout << "Value of __TIME__ : " << __TIME__ << endl;

    return 0;
}

Value of __LINE__ : 6
Value of __FILE__ : test.cpp
Value of __DATE__ : Feb 28 2011
Value of __TIME__ : 18:52:48