Creating Inline Functions

New to C99 is the ability to create inline functions: user-defined functions that will, theoretically, perform faster. Inline functions are normally defined before the main function and are preceded with the keyword inline. For example:

#include <stdio.h>
inline int my_func() {
   // Function content.
}
int main (void) {...

Inline functions do not require the prototype, because they are defined before the main function.

These types of function definitions have the potential to be faster because the compiler treats them differently. Instead of setting aside the resources necessary for defining a new function, the compiler will go through an application's code, replacing calls to the inline function with the function code itself. This way, you have the benefit of managing repeated tasks in one space without the overhead of an extra function.

The catch to inline functions is that they must be relatively simple in order for there to truly be a benefit. As an example of this, you'll now rewrite the factorial example, adding the discard_input() function created earlier as an inline function.

To define and use inline functions

1.
Open return_factorial.c (Script 7.3) in your text editor or IDE.

2.
After the function prototype for return_factorial(), define discard_input() as an inline function (Script 7.4):

inline void discard_input (void) {
     char junk;
     do {
        junk = getchar();
     { while (junk != '
'),
}

Script 7.4. Rewritten as an inline function, discard_input() may work slightly faster.


The bulk of the code is taken directly from the earlier example where the discard_input() function was first defined. The significant addition here is the use of the word inline, at the beginning of the function definition.

3.
After the program's primary conditional, call the discard_input() function.

Calling inline functions is no different than calling any other functions. Here, the discard_input() will get rid of any extraneous input before the user has to press Return or Enter to finish executing the application.

4.
Save the file as inline.c.

5.
Compile, debug, and run (Figure 7.8).

Figure 7.8. Inline functions shouldn't change the functionality of your applications, but they may improve their performance.


✓ Tip

  • Whether or not inline functions are faster than standard user-defined ones depends on the environment in question. The best way to test their effectiveness is by benchmarking—timing the execution speed—of your application with and without using a function inline.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset