macros in c++

what is Macros in c++ with programs

Macros in c++ are designed to reduce function call overhead in case of a small functions. Concept of macros are not new  to C++, they are also supported by C language. Macros are defined by using hash sign because they are processed by micro-processor not by compilers.

Why we use macros in c++?

Function call is costly operation, During the function call and it’s execution our system takes overheads. Like: saving the value of Registers, saving the return address, pushing the argument in the stack, jumping to the called function,  reloading the register with new values, returning to the calling function and reloading the register with previously stored values.  Function overhead is negligible but for a small function taking such large overhead is not justifiable. so we use macros in c++.

Program by using a macros in c++

#include<iostream>
#include<conio.h>
#define mul(a,b) a*b //macro definition
#define div(a,b) a/b
using namespace std;
int main ()
{
int x=4,y=3;
float n=5.0,m=2.0;
cout<<mul (x,y); //macro call
cout<<"\n";
cout<< div(n,m); //macro call
cout<<"\n";
return 0;
}

Output
12
2.5

All macro call statements are replaced by their definition by micro-processor and then after completion of program is performed. Therefore control needs not to be transferred to the Macro definition at the time of program execution. But main drawback of macros is that macros are not checked for errors they are substituted by microprocessor as it is.

What are pitfalls of macros in c++ ?

The key to the problems of preprocessor macro is that you can be fooled into thinking that the behavior of the preprocessor is the same as the behavior of the compiler.  Of course it was intended that are micro look and act like a function call, so it’s quite easy to fall into this function. If we use expression as arguments to the macros, result generated by macros may be quite different from our expectation.

Program showing limitation of macro in c++

#include<iostream>
#include<conio.h>
#define mul(a,b) a*b
using namespace std;
int main ()
{
int result;
result=mul(2+4,5);
cout<<"result="<<result<<endl;
cout<<"\n";
return 0;
}

Output
22
when macro call mul(2+4,5) is made, rather than multiplying 6 and 5 macro is expand as “2+4*5” and thus result becomes 22.

Related term in c++

What is jump statement in C++?
Ans: Jump statements in c++ are use to transfer control of program execution Unconditionally from one part of the program to another….Read more
What is type conversion in c++?
Ans:Sometimes, a program needs to convert a value from one tab to another in a situation where the compiler will not do it automatically. This is the forceful conversion from…Read more

1 thought on “what is Macros in c++ with programs”

Leave a Comment

Your email address will not be published. Required fields are marked *