内联函数VS宏功能 [英] inline function vs macro function

查看:249
本文介绍了内联函数VS宏功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  内联函数VS preprocessor宏

我想知道内联函数和宏功能之间的差异。

I want to know the difference between the inline function and macro function.

1)是内联的功能是相同的宏功能的

1) is inline function is the same of macro function ?

2)我知道这两个不叫,但他们是通过在编译阶段其code取代。是不是?

2) I know that both are not called but they are replaced by its code in the compilation phase. is not?

3)如果有差别,你能指定它?

3) If there is difference, Could you specify it?

推荐答案

内联替换与函数体函数的调用,但是,内联仅仅是一个的要求的编译器,可以被忽略(你仍然可以通过一些标志编译器强制内联或使用* always_inline *与海湾合作委员会的属性)。

Inline replaces a call to a function with the body of the function, however, inline is just a request to the compiler that could be ignored (you could still pass some flags to the compiler to force inline or use *always_inline* attribute with gcc).

在另一方面宏,是由 preprocessor ​​的编译之前,所以它就像文本替换,宏也没有类型检查扩大,内联函数。有一个在维基的比较。

A macro on the other hand, is expanded by the preprocessor before compilation, so it's just like text substitution, also macros are not type checked, inline functions are. There's a comparison in the wiki.

为了完整起见,你仍然可以有某种与宏类型安全的,使用gcc的 __的typeof __ 例如,下面的产生几乎一模一样code和如果都用错误的类型使用导致的警告:

For the sake of completeness, you could still have some kind of type safety with macros, using gcc's __typeof__ for example, the following generate almost identical code and both cause warnings if used with the wrong types:

#define max(a,b) \
  ({ __typeof__ (a) _a = (a); \
      __typeof__ (b) _b = (b); \
    _a > _b ? _a : _b; })

__attribute__((always_inline)) int max(int a, int b) {
   return (a > b ? a : b);
}

请注意:有时无类型的宏只是需要些什么,比如看看 uthash 如何使用宏来做出任何的C结构哈希而不诉诸强制转换。

Note: sometimes typeless macros are just what's needed, for example, have a look at how uthash uses macros to make any C structure hashable without resorting to casts.

这篇关于内联函数VS宏功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆