What is an inline function ?
A function declared with the function specifier "inline". It's
new in the C99 standard (but a lot of compilers allowed it as
an extension already prior to that).
When should we declare a particular function as inline ?
When you have a short function where the overhead of calling
the function is too large, i.e. if there's more time spend in
calling the function and returning from it than in what the
function actually does. Potential candidates could be e.g.
inline int_abs( int x ) {
return x >= 0 ? x : -x;
}
If a function is declared to be inline, does that mean
that the entire code for that function is subtituted there
Not necessarily. The only thing the standard says is that:
"Making a function an inline function suggests that calls to
the function be as fast as possible.". Please note the word
"suggests", i.e. the compiler is free to do nothing. So what
the compiler exactly does with inlined functions is left to
the discretion of the implementor. One way to do it is, of
course, to put the code for the function everywhere where
it's called.
just like macros? Then why not use macros ?
Functions and macros are completely different beasts. A
macro is nothing else than a text replacement that happens
at a very early stage of the compilation. Therefore macros
can lead to very strange results unless used very carefully.
Consider e.g.
#define ABS( x ) ( ( x ) >= 0 ? ( x ) : ( -x ) )
This looks quite nice and simple, doesn't it? But try to call
it like this
int a = -1;
int b = ABS( a++ );
and think about what's going to be the result. (Hint: you will end
up with 'b' set to 0 and 'a' being 1. You would expect it to be the
other way round, wouldn't you? To figure out why do the text replace-
ment for the macro by hand and see what's the resulting code.) That's
something that won't happen with a function (inlined or not), since
function arguments are evaluated before passed to the function.
Regards, Jens