虽然C没有constexpr
函数,但GCC和Clang都可以在编译时使用-O1
来评估简单函数。相关优化被称为constant folding。
以下C代码:
#include <stdio.h>
static inline unsigned int findRange(unsigned int x)
{
if (x > 16)
return 32;
else if (x > 8)
return 16;
else if (x > 4)
return 8;
else if (x > 2)
return 4;
else if (x > 1)
return 2;
return 1;
}
int main(void)
{
unsigned int i = findRange(7);
printf("%u\n", i);
return 0;
}
结果转换成x86-64的汇编代码(参考:godbolt.org/g/kVYe0u):
main:
sub rsp, 8
mov esi, 8
mov edi, OFFSET FLAT:.LC0
mov eax, 0
call printf
mov eax, 0
add rsp, 8
ret
正如你可以看到,到findRange
呼叫由值替代内容,这是在编译时计算的。
即使当findRange
被定义为具有外部链接的正常(非内联)功能时,该功能仍然有效。
AFAIK你不能做到这一点标准的C或C++,但gcc的预处理器有[this](https://gcc.gnu.org/onlinedocs/cpp/Directives-Within-Macro-Arguments.html#Directives-Within-Macro-Arg ),也许这可以帮助: –
'(x> 16? 32:x> 8? 16:x> 4? 8'等 –
它看起来像你想[围绕2的下一个力量](http://stackoverflow.com/questions/466204/rounding-up-to-nearest-power-of-2),或[特别是例如](http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2) –