pure是一个函数属性,表示函数不会修改任何全局内存.
const是一个函数属性,表示函数不读取/修改任何全局内存.
鉴于该信息,编译器可以进行一些额外的优化.
GCC示例:
float sigmoid(float x) __attribute__ ((const));
float calculate(float x, unsigned int C) {
float sum = 0;
for(unsigned int i = 0; i < C; ++i)
sum += sigmoid(x);
return sum;
}
float sigmoid(float x) { return 1.0f / (1.0f - exp(-x)); }
Run Code Online (Sandbox Code Playgroud)
在该示例中,编译器可以将函数计算优化为:
float calculate(float x, unsigned int C) {
float sum = 0;
float temp = C ? sigmoid(x) : 0.0f;
for(unsigned int i = 0; i < C; ++i)
sum …Run Code Online (Sandbox Code Playgroud) 如何在Windows上使用预处理器执行log(x)?
喜欢:
#define A log(4)/log(2)
Run Code Online (Sandbox Code Playgroud)
在我的代码之后的数组
int b[A]; // A=2 will be computed with the preprocessor ! not in run time
Run Code Online (Sandbox Code Playgroud)