总是返回常量的C函数
问题描述:
在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
似乎并没有削减它,或者至少在例子我试过了。
答
我不是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
}
内联你的函数或定义一个宏代替'#定义that_const_value()((ro_register >> 16)&0xff的)' –
因为宏只是文本替换,所有你需要的就是这样。一个宏,将允许你想要的语法和你真正想要的结果。 –
GCC有'__attribute __((__纯__))'这个。 – melpomene