An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. Instead of transferring control to and from the function code segment, a modified copy of the function body may be substituted directly for the function call. In this way, the performance overhead of a function call is avoided. Using the inline specifier is only a suggestion to the compiler that an inline expansion can be performed; the compiler is free to ignore the suggestion.
Any function, with the exception of main, can be declared or defined as inline with the inline function specifier. Static local variables are not allowed to be defined within the body of an inline function.
inline int add(int i, int j) { return i + j; }
The
use of the inline specifier does not change the meaning
of the function. However, the inline expansion of a function may not
preserve the order of evaluation of the actual arguments.The most efficient way to code an inline function is to place the inline function definition in a header file, and then include the header in any file containing a call to the function which you would like to inline.
// a.c
#include <stdio.h>
inline int foo(){
return 3;
}
void g() {
printf("foo called from g: return value = %d, address = %p\n", foo(), &foo);
}
// b.c
#include <stdio.h>
inline int foo(){
return 3;
}
void g();
int main() {
printf("foo called from main: return value = %d, address = %p\n", foo(), &foo);
g();
}
The output from the compiled program is: foo called from main: return value = 3, address = 0x10000580
foo called from g: return value = 3, address = 0x10000500
// a.c
#include <stdio.h>
inline int foo(){
return 6;
}
void g() {
printf("foo called from g: return value = %d\n", foo());
}
// b.c
#include <stdio.h>
int foo(){
return 3;
}
void g();
int main() {
printf("foo called from main: return value = %d\n", foo());
g();
}
Similarly, if you define a function as extern
inline, or redeclare an inline function
as extern, the function simply becomes a regular,
external function and is not inlined. If you specify the __inline__ keyword, with the trailing underscores, the compiler uses the GNU C semantics for inline functions. In contrast to the C99 semantics, a function defined as __inline__ provides an external definition only; a function defined as static __inline__ provides an inline definition with internal linkage (as in C99); and a function defined as extern __inline__, when compiled with optimization enabled, allows the co-existence of an inline and external definition of the same function. For more information on the GNU C implementation of inline functions, see the GCC information, available at http://gcc.gnu.org/onlinedocs/.