现在的位置: 首页 > 综合 > 正文

Inline Functions versus Macros

2017年03月13日 ⁄ 综合 ⁄ 共 1694字 ⁄ 字号 评论关闭

本文转载至:http://msdn.microsoft.com/en-us/library/bf6bf4cf.aspx

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:

// inline_functions_macro.c
#include <stdio.h>
#include <conio.h>

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

int main() {
   char ch;
   printf_s("Enter a character: ");
   ch = toupper( getc(stdin) );
   printf_s( "%c", ch );
}
Sample 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.

Inline functions remedy the problem previously described:

// inline_functions_inline.cpp
#include <stdio.h>
#include <conio.h>

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

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

Sample Output: A

抱歉!评论已关闭.