雖然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) –