Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) #define

 

The preprocessor directive #define can be used for:

 

 

 

 

 

Use of #define in #include guards

 

The preprocessor statements #ifndef, #define and #endif can be used for #include guards. These prevent a header file to be #included multiple times, causing a redeclaration error. Always write (internal) #include guards [3,10]. Consider using #define only for #include guards [14].

 

#ifndef MYHEADERFILE_H
#define MYHEADERFILE_H

//Your header file

#endif

 

 

 

 

 

Use of #define in the assert statement

 

#define is used for the debugging #define NDEBUG used by assert (among others). Assert liberally to document internal assumptions and invariants [4-5,11].

 

#include <cassert>

//#define NDEBUG //Uncomment to remove all asserts

double Invert(const double x)
{
  assert(x!=0.0); //Divisions by zero are illegal
  return 1.0/x;
}

 

 

 

 

 

Use of #define in macro's

 

The preprocessor directive #define is used to define macro's.

 

Avoid macro's [1-2,7] as there are better, type-safe alternatives: consts, enums and inlines.

 

The example code below states that the preprocessor must replace the text 'DOZEN' by the value of twelve.

 

#define DOZEN 12

 

Prefer const over this type of #define [1,7-8,13].

 

The example code below states that the preprocessor must replace the 'x' between brackets by 'x+1':

 

#define PLUS_ONE(x) x+1

 

Prefer inline over this type of #define [1,7,9,12].

 

 

 

 

 

References

 

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml