CPP Preprocessor commands

Preprocessor and the Compiler

  • Every time you run your compiler, your preprocessor runs first.
  • The preprocessor looks for preprocessor instructions, each of which begins with the symbol #.
  • The #define Preprocessor Directive.
    #define macroName replacementString
    This causes the compiler to go through the file, replacing every occurrence of macroName with replacementString.
    #define BIG 512
    int myArray[BIG]; // will replace BIG with 512 
  • Using #define for Tests/Debug:
    #define DEBUG
    Later in your listing . . . .
    #if defined DEBUG
    cout << "Debug defined";
  • Using #define for Macro function:
    #define TWICE(x) ( (x) * 2 )
    and then in your code you write . . . .
    TWICE(4)    // and the value ( (4) * 2 ) is substituted
  • To avoid inclusion of header file more then once you can use inclusion guards:
    #ifndef PERSON_HPP    // if this header is included (defined)
    #define PERSON_HPP    // define it and include all up to the #endif
    ...                   // the whole header file (*.hpp) goes here
  • The stringizing operator (#) puts quotes around any characters following the operator, up to the next whitespace.
    #define WRITESTRING(x) cout << #x
    and then in your code you write . . . .
    WRITESTRING(This is my string);
    // turns it into: cout << "This is my string";
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.