Inline Functions versus Macros
来源:互联网 发布:网络大电影宣发公司 编辑:程序博客网 时间:2024/06/10 03:22
本文转载至: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: xyzSample 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: aSample Output: A
- Inline Functions versus Macros
- Choosing Between Functions and Macros
- Inline Functions in C++
- Inline Virtual Functions
- C++ inline functions
- Inline Functions (C++)
- Assembly Intro - Inline Assembly Versus Non-Inline Assembly
- c++ friend functions and inline functions
- Scala Macros - scalamela 1.x,inline-meta annotations
- Kotlin-23.内联函数(Inline Functions)
- C++对象模型——Inline Functions(第四章)
- Kotlin语法(十九)-内联函数(Inline Functions)
- functions
- functions
- Functions
- Functions
- Functions
- Functions
- LeetCode | Consecutive Numbers
- CentOS安装sendmail及设置
- Java正则表达式详解
- 粒子系统
- Microsoft Linux ?
- Inline Functions versus Macros
- myeclipse创建的工程eclipse无法正常部署
- POJ2299(归并排序求逆序对)
- Bootstrap--对移动设备友好的布局
- 博客工具写博客--Zoundry
- view 事件分发机制
- 贵在有恒
- linux telnet 使用
- ZOJ Problem Set - 2947 Abbreviation