[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3.3 The #if, #ifdef, #ifndef, #else and #elseif statements

These are all preprocessor directives aimed at selecting certain parts of code and removing other depending on the state of a preprocessor variable.

The #if statement looks very much like a normal if statement, just written a bit differently.

Assume you may have the following define somewhere:

 
#define CODE_VAR  2

or
	
#define CODE_VAR  3

Then you can write

 
#if CODE_VAR == 2
    <code that will be kept only if CODE_VAR == 2>
#else
    <code that will be kept only if CODE_VAR != 2>
#endif

You don't have to have the #else statement there at all if you don't want to.

It's sufficient to have the following statement to 'define' a preprocessor pattern as existing:

 
#define CODE_VAR    /* This defines the existence of CODE_VAR */

Then you can write like this:

 
#ifdef CODE_VAR
    <code that will be kept only if CODE_VAR is defined>
#else
    <code that will be kept only if CODE_VAR isn't defined>
#endif

or

 
#ifndef CODE_VAR
    <code that will be kept only if CODE_VAR isn't defined>
#else
    <code that will be kept only if CODE_VAR is defined>
#endif

Again, the #else part is optional.

The #if/#ifdef/#ifndef preprocessor commands are almost only used to add debug code that you don't want to have activated all of the time, or code that will work differently depending on other very rarely changing parameters. Since the conditions have to be hard-coded in the file and can't change during the course of the use of the object this is something you very rarely do.

Please consider that adding these statements reduces the legibility and thus also the quality and long-term maintainability of the code. Keeping them to a minimal is recommended.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated by Hekay Permer on April, 20 2005 using texi2html