Macros with Arguments

Have a look at the following code:


  #include<iostream.h>

#define MAX 10

void main(void)
{
for(int i=1;i<=MAX;i++)
cout<<i<<endl;
}

Above we have used the type of macro expansion that we learnt in the article

Introduction to C++ Preprocessor Directives


Do you know that just like functions we can have arguments in the macros too!
The following code shows how:


  #include<iostream.h>

// this is how macros with
// arguments are defined
// NOTE: THERE SHOULD NOT BE
// ANY SPACE BETWEEN THE
// MACRO TEMPLATE (i.e. AREA)
// AND THE PARANTHESIS
// CONTAINING THE ARGUMENTS
// (i.e. (x))

#define AREA(x) (x*x)

void main(void)
{
// calling a macro
// is almost similar
// to calling a function
cout<<AREA(10);
}

It is that simple! However, keep one thing in mind as stated in the comments
not to put any space between the macro template and the braces containing the
argument.


   #define AREA(x) (x*x) //correct
#define AREA (x) (x*x) // incorrect

Why use Macros


While function can do the same thing, still there are times when macros preferred
over function.


As a general rule, using macros increases the execution speed of a program
but at the same time increase the file size of the program. On the other hand
using functions decreases the speed of execution of program but also decreases
the file size.


Therefore, macros are used in time critical programs where execution speed
must be as fast as possible no matter what the file size is, in all other cases
functions are generally used.


Good-Bye!


Related Articles:


Introduction
to C++ Preprocessor Directives

Check out this stream