tags:

views:

62

answers:

2
+1  Q: 

inline functions

Possible Duplicate:
Inline functions vs Preprocessor macros

hello can somebody please explain what exactly does it mean, and what is the difference from regular macro(I know that it works during compile time and not preprocessor but so what?) thanks in advance for any help, looked in google but didn't find something understandable

+1  A: 

(Assuming here that you're talking about C/C++.)

An inline function has its code copied into the points where it's called, much like a macro would.

The big reason you would use inline functions rather than macros to accomplish this is that the macro language is much weaker than actual C/C++ code; it's harder to write understandable, re-usable, non-buggy macros. A macro doesn't create a lexical scope, so variables in one can collide with those already in scope where it's used. It doesn't type-check its arguments. It's easy to introduce unexpected syntactic errors, since all a macro does is basically search-and-replace.

Also, IIRC, the compiler can choose to ignore an inline directive if it thinks that's really boneheaded; it can't do that with a macro.

Or, to rephrase this in a more opinionated and short way: macros (in C/C++, not, say, Lisp dialects) are an awful kludge, inline functions let you not use them.

Also, keep in mind that it's often not a great idea to mark a function as inline. Compilers will generally inline or not as they see fit; by marking a function inline, you're taking over responsibility for a low-level function that most of the time, the compiler's going to know more about than you are.

ngroot
+1  A: 

There is a big difference between macros and inline functions:

  • Inline is only a hint to the compiler that function might be inlined. It does not guarantee it will be.
  • Compiler might inline functions not marked with inline.
  • Macro invocation does not perform type checking, so macros are not type safe.
  • Using function instead of a macro is more likely to give you a nice and understandable compiler output in case there is some error.
  • It is easier to debug functions, using macros complicates debugging a lot. Most compilers will give you an option of enabling or disabling inlining, this is not possible with macros.

The general rule in C++ is that macros should be avoided whenever possible.

Vlad Lazarenko