Inline Functions versus Macros
Collapse the table of content
Expand the table of content
The document is archived and information here might be outdated

Inline Functions versus Macros

Although inline functions are similar to macros (because the function code is expanded at the point of the call at compile time), inline functions are parsed by the compiler, whereas macros are expanded by the preprocessor. As a result, there are several important differences:

  • Inline functions follow all the protocols of type safety enforced on normal functions.
  • Inline functions are specified using the same syntax as any other function except that they include the inline keyword in the function declaration.
  • Expressions passed as arguments to inline functions are evaluated once. In some cases, expressions passed as arguments to macros can be evaluated more than once.

Example

The following example shows a macro that converts lowercase letters to uppercase:

#include <stdio.h>
#include <conio.h>

#define toupper(a) ((a) >= 'a' && ((a) <= 'z') ? ((a)-('a'-'A')):(a))

int main()
{
 printf("Enter a character: ");
 char ch = toupper( getc(stdin) );
 printf( "%c", ch );
}

Input

xyz

Sample Output

Z

The intent of the expression toupper( getc(stdin) is that a character should be read from the console device (stdin) and, if necessary, converted to uppercase.

Because of the implementation of the macro, getc is executed once to determine whether the character is greater than or equal to "a," and once to determine whether it is less than or equal to "z." If it is in that range, getc is executed again to convert the character to uppercase. This means the program waits for two or three characters when, ideally, it should wait for only one.

Example

Inline functions remedy the problem previously described.

#include <stdio.h>
#include <conio.h>

inline char toupper( char a )
{
    return ((a >= 'a' && a <= 'z') ? a-('a'-'A') : a );
}

int main()
{
    printf("Enter a character: ");
    char ch = toupper( getc(stdin) );
    printf( "%c", ch );
}

Input

a

Sample Output

Enter a character: A

See Also

inline, __inline, __forceinline

Show:
© 2016 Microsoft