如果我在#define 中使用固定公式,它是否比使用数字效率低?

If I use a fixed formula in a #define, is it less efficient than using a number?

我正在研究 Cortex-M3 的一些遗留代码,这些代码是在 Keil µVision 上用 C 语言编写的。

在记录 ADC 值的函数中,比例因子用于将位转换回伏特。

我的问题围绕着头文件中定义的比例因子:

#define INPUT_VALUE_MAX (uint16_t)((1<<12)-1)

所以这等于 4095,这是有道理的,因为它是一个 12 位 ADC。我的问题是,把"INPUT_VALUE_MAX"这个值定义成一个公式,是不是意味着每次使用,单片机都要重新计算这个值。

简单地说,确实:

#define INPUT_VALUE_MAX (uint16_t)((1<<12)-1)

处理时间比:

#define INPUT_VALUE_MAX (uint16_t)4095?

提前感谢任何人可以提供的帮助!

不,它不需要任何 运行 时间的处理时间。整个宏是一个 整数常量表达式 ,这意味着它将在编译时计算。

如果您查看生成的程序集,您会发现该表达式已被常量 4095 替换。


常量表达式在C中是这样定义的,C11 6.6:

A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be.

Constraints

Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except when they are contained within a subexpression that is not evaluated.

Each constant expression shall evaluate to a constant that is in the range of representable values for its type.

/--/

An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof or _Alignof operator.