2017-02-24 56 views
2

在C語言中表達語義「這個函數總是要返回一個常量值」的好方法是什麼?總是返回常量的C函數

我正在考慮內聯彙編函數,它讀取只讀寄存器,並可能移位和/或屏蔽它們。顯然,在運行時,函數的返回值不會改變;因此編譯器可能會始終避免內聯或調用該函數,而是旨在重複使用給定作用域中第一個調用的值。

const int that_const_value() 
{ 
    return (ro_register >> 16) & 0xff; 
} 

我可以存儲該值並重新使用它。但是可以通過其他宏觀擴展來間接調用這個函數。

#define that_bit() that_const_value() & 0x1 
#define other_bit() that_const_value() & 0x2 

... 
if (that_bit()) { 
    ... 
} 
... 
if (other_bit()) { 
    ... 
} 

定義原來的功能const似乎並沒有削減它,或者至少在例子我試過了。

+4

內聯你的函數或定義一個宏代替'#定義that_const_value()((ro_register >> 16)&0xff的)' –

+2

因爲宏只是文本替換,所有你需要的就是這樣。一個宏,將允許你想要的語法和你真正想要的結果。 –

+3

GCC有'__attribute __((__純__))'這個。 – melpomene

回答

0

我不是100%的確信我正確地理解你的問題,但你在找這樣一個解決方案:

#define that_const_value ((ro_register >> 16) &0xff) 
#define that_bit   (that_const_value & 0x1) 
#define other_bit  (that_const_value & 0x2) 

這只是在compille時間「取代」一切,所以你可以這樣做:

if(that_bit) 
{ 
    //Do That 
} 
if(other_bit) 
{ 
    //Do Other 
}