Hello,
Could someone explain which of the two: Macros or Inline functions produces smaller sized object code and why?
Thanks!
Passionate Guy
Printable View
Hello,
Could someone explain which of the two: Macros or Inline functions produces smaller sized object code and why?
Thanks!
Passionate Guy
depends on your compiler.
Macros are bad.
Read this:
Inline functions and macros...
"they are different in some important ways. For example, since inline functions are part of the language, it is generally possible to step through them in a debugger, whereas macros are notoriously difficult to debug. Also, macro parameters that have side effects can cause surprises if the parameter appears more than once (or not at all) in the body of the macro, whereas inline functions don't have these problems. Finally, macros are always expanded, but inline functions aren't always inlined.
"
I think of macros as a simple text replace during preprocessing phase of compilation.
Look at this example of using macros:
Result is not what you expect is it?Code:#include <iostream>
using namespace std;
#define square(x) x*x
int main()
{
int x = 10;
int a = 3, b = 5;
cout<< square(x)<<endl;
cout<< square(a+b)<<endl;
return 0;
}
Solution to this problem is using:
And when you need to take care of such things every time, it is very easy to make mistake.Code:#define square(x) (x)*(x)
Cheers
- Micko
Thanks Micko for the detailed example. I understand the vulnerabilities of using Macros.
But as major_small has suggested even I guess that the size of object code will vary depending on the compiler.
Inline has a tendency to make code bigger, not smaller.
You're saving the cost of a function call by pasting the context of the function directly into the caller. If you call an inline function a lot, that's going to bloat the exe with lots of near-identical code.