Loading....
Coupon Accepted Successfully!

 

Differences Between Templates And Macros

  1. Macros are not type safe; that is, a macro defined for integer operations cannot accept float data. They are expanded with no type checking.
  2. It is difficult to find error in macros.
  3. In case a variable is post-incremented or decremented, the operation is carried out twice.
Consider the following macro:
 

# define max(a) a + ++a

void main()

{

int a=10, c;

c=max(a);

cout<<c;

}

 
The macro defined in the above macro definition is expanded twice. Hence, it is a serious limitation of macros. The limitation of this program can be removed using a template as shown below.
 
17.17 Write a program to increment the value of a variable using template.
#include<iostream.h>
#include<constream.h>
template<class T>
T max(T k)
{
++k;
return k;
}
void main()
{
clrscr();
int a=10, c;
c=max(a);
cout<<c;
}
OUTPUT
11
 
Explanation: In the above program, the template function max() is defined. An integer value is passed to this function. The function max() increments the value and returns it.




Test Your Skills Now!
Take a Quiz now
Reviewer Name