内联函数与宏

虽然内联函数类似于宏 (因为函数代码在编译时调用展开),内联函数由编译器分析,,而宏由预处理器展开。因此,具有几个重要的差异:

  • 内联函数按照正常功能强制的类型安全所有协议。

  • 内联函数指定使用语法和其他功能相同,只不过它们在函数声明中包括 内联 关键字。

  • 作为参数传递给方法的表达式对内联函数一次计算。有时,作为参数传递给方法的表达式添加到宏可以多次计算。

示例

下面的示例演示转换小写字母转换为大写的宏:

// 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 );
}
  
  

该表达式 toupper(getc(stdin)) 的目的是应从控制台设备 (stdin) 读取,并且,如果需要,在中,将字符转换为大写。

由于宏的实现, getc 执行一次确定字符是否大于或等于 “a”,以及一次以确定它是否小于或等于 “z”.如果它在该范围内, getc 再次执行将字符转换为大写。这意味着程序等待两个或三个字符,同时,在理想情况下,它只应等待的输出。

内联函数更正前面所述的问题:

// 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 );
}
  
  

请参见

参考

内联, __inline, __forceinline