Sunday, April 6, 2014

Introduction to C Preprocessor Directives

As the name suggest, C++ Preprocessor is an integrated program in C++ that
preprocesses every program we write before compilation.


Preprocessor commands or directives are special functions that are executed
or processed before the compilation of the program.


Although we can write program without the knowledge of preprocessor directives
but why underutilize features when we have them?


Every preprocessor directive starts with a # symbol. While
we can have them anywhere in the program but they are almost always used at
the starting of the program before any function is defined.


Knowingly or unknowingly, we have been using one preprocessor directive. It
is the #include directive, which is most commonly used to include
header files in the program.


While there are many types of preprocessor directives, here we will only be
discussing about Macro Expansion directives and that also in the simplest sense!


Macro Expansion Directives


Have a look at the code below:


  #define MAX 10
cout<<MAX;

Here, MAX is known as ‘Macro Template’ and 10,
Macro Expansion’.


Upon preprocessing every instance of the word MAX is replaced with 10 and only
then is the program executed.


It is just like search and replace, in which every word defined as macro template
(in this case MAX) is replaced by the corresponding macro expansion (in this
case 10).


It is the common way of defining constants that doesn’t needs to be change
throughout.


A few points to note:




  • Please note that it is necessary not to end directives with semicolon (;).




  • While it is not necessary to use ALL-CAPS for macro template but it has
    become the standard.




Below is a simple example program that illustrates macro expansion directives:


  // example program in c++ to show
// the use of macro directives
#include<iostream.h>
// below is the macro, which can be
// changed to change the behaviour
// of the whole program
// DONT END WITH ;
#define MAX 3

void main(void)
{
int arr[MAX];
int i;

cout<<"enter elements of the array:";
for(i=0;i<MAX;i++)
cin>>arr[i];

cout<<"elements are:";
for(i=0;i<MAX;i++)
cout<<"
"<<i<<":"<<arr[i];
}

Good-Bye!


Related Articles:


Related Posts by Categories

0 comments:

Post a Comment