#define - A Preprocessor Directive

Many things that can be done during preprocessing phase include :

  • Inclusion of other files through #include directive
  • Definition of symbolic constants and macros through #define directive

Through some preprocessor directives you can also conditionally compile or execute some preprocessor directives.

Note - The preprocessing phase of a C++ program occurs before a program is compiled. The C++ preprocessor is a program that is executed before the source code is compiled.

Definition

#define is a preprocessor language. It is used to give a constant value to the name. 

Compiler replaces this code with the value.

Macro definitions are not variables because this can't be changed during coding/run-time.

Define is evaluated before compilation by the pre-processor, while variables are referenced at run-time. This means you control how your application is built (not how it runs). 

Usages

1) When you are also sick of writing a for loop every time, you can do like this. 

#define FORLOOP for (int i=0; i<=10; i++)

// some code...

FORLOOP {
    // do stuff to i
}

If you want something more generic, you can create preprocessor macros:

#define FORLOOP(x) for (int i=0; i<=x; i++)
// the x will be replaced by what ever is put into the parenthesis, such as
// 20 here
FORLOOP(20) {
    // do more stuff to i
}

It's also very useful for conditional compilation (the other major use for #define) if you only want certain code used in some particular build:

// compile the following if debugging is turned on and defined
#ifdef DEBUG
// some code
#endif

2) C language doesn't have consts, so the #define is the only way. 

int Marylyn[256], Ann[1024];                    

It is good coding style to use macro instead of magic numbers. We can also use #define for this purpose. 

 #define TWO_FIFTY_SIX 256
 #define TEN_TWENTY_FOUR 1024

 int Marylyn[TWO_FIFTY_SIX], Ann[TEN_TWENTY_FOUR];

#define can also be used at function scope.  

3) Another common usage is to use them as header guards.

4) 

#define min(i, j) (((i) < (j)) ? (i) : (j))


Disadvantages

There is no type-safety

You can't step through an #define in debugger, but you can step through an inline. 


References :

https://stackoverflow.com/questions/6004963/why-use-define-instead-of-a-variable

https://codescracker.com/cpp/cpp-hash-define-preprocessor-directive.htm

https://stackoverflow.com/questions/1137575/inline-functions-vs-preprocessor-macros?rq=1

Comments