0

Possible Duplicate:
Inline functions vs Preprocessor macros

what is the use of inline function and how it works? Are inline and macro different?

Community
  • 1
  • 1
ankit
  • 877
  • 3
  • 9
  • 14
  • 2
    There are tons of questions about inline in c++, just look at this list of tagged questions. http://stackoverflow.com/questions/tagged/inline%20c%2b%2b – CB Bailey Sep 25 '10 at 09:07

1 Answers1

1

An inline function evaluates it arguments the same way a function does (or at least you can think of it that way). That prevents the typical macro-errors to occurs. On the other hand, by stating that a function is inline you hint the compiler to avoid the function call and just insert the instructions inplace in the code (just like a macro).

So in short, it's safer than a macro, but just a hint to the compiler. The compiler isn't forced to avoid the function call (at least if I recall it correctly).

By the way, example of a "typical macro error":

#define SQUARE(a) (a*a)

int x = 10;
int square = SQUARE(++x); // this turns out to be 11 * 12, instead of 11 * 11

An inline function would have performed 11 * 11 instead.

Jakob
  • 24,154
  • 8
  • 46
  • 57
  • 2
    Actually the result here is undefined. – Martin York Sep 25 '10 at 18:34
  • @MartinYork Please explain. Code substitution occurs before compilation, therefore it would evaluate as `int square = ++x*++x;`, which is 11*12. How is this undefined? – FalcoGer Apr 02 '19 at 06:30
  • 1
    @FalcoGer A variable is only allowed to be updated once between sequence points. Here `x` is updated twice between sequence points (and thus has undefined behavior). Have a look at nearly any question about why `++ ++ x` does not work on this site. Note: I notice you use C#: in that language it is well defined but in C++ this is not allowed. – Martin York Apr 02 '19 at 15:32
  • https://stackoverflow.com/questions/4638364/undefined-behavior-and-sequence-points-reloaded – Martin York Apr 02 '19 at 15:43