如果要在C函数宏 [英] When to use function-like macros in C

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

问题描述

我是读今晚C语言编写的一些code,并且在顶部
该文件是函数宏HASH:

I was reading some code written in C this evening, and at the top of the file was the function-like macro HASH:

#define HASH(fp) (((unsigned long)fp)%NHASH)

这让我疑惑,为什么会有人选择实现
使用函数宏,而不是实施运作这种方式
它作为一个普通香草的C函数?有什么优点和
每个实现的缺点是什么?

This left me wondering, why would somebody choose to implement a function this way using a function-like macro instead of implementing it as a regular vanilla C function? What are the advantages and disadvantages of each implementation?

感谢一大堆!

推荐答案

这样的宏避免函数调用的开销。

Macros like that avoid the overhead of a function call.

这看起来可能不是很多。但是,在你的榜样,宏变成1-2机器语言指令,这取决于你的CPU上:

It might not seem like much. But in your example, the macro turns into 1-2 machine language instructions, depending on your CPU:


  • 获取FP的值超出内存并把它放在一个寄存器

  • 取值​​寄存器,做模量(%)计算通过一个固定的值,并留下了同一个寄存器

而功能相当于将是一个很多机器语言指令,一般像

whereas the function equivalent would be a lot more machine language instructions, generally something like


  • 坚持在堆栈上FP值

  • 通话功能,这也将下一个(返回)地址堆栈

  • 也许建立在函数中堆栈帧,根据不同的CPU架构和ABI约定

  • 获取FP值从堆栈并把它放在一个寄存器

  • 取值​​寄存器,做模量(%)计算通过一个固定的值,并留下了同一个寄存器

  • 也许需要从寄存器的值,并把它放回堆栈上,这取决于CPU和ABI

  • 如果栈帧建成,放松它

  • 弹出堆栈中的返回地址,并恢复执行指令有

一个很多code,是吗?如果你正在做这样的事情在GUI渲染数以万计的像素中的每一个在一个窗口,如果你使用宏东西运行一个可怕的快很多。

A lot more code, eh? If you're doing something like rendering every one of the tens of thousands of pixels in a window in a GUI, things run an awful lot faster if you use the macro.

就个人而言,我使用C preFER ++内联作为是更具可读性和更不容易出错,但内联也真多一个暗示,它没有必须采取的编译器。 preprocessor宏是一个大锤编译器不能争辩。

Personally, I prefer using C++ inline as being more readable and less error-prone, but inlines are also really more of a hint to the compiler which it doesn't have to take. Preprocessor macros are a sledge hammer the compiler can't argue with.

这篇关于如果要在C函数宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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