Pure / const attributes in different compilers

clean is an attribute of a function that says that the function does not modify any global memory.
const is an attribute of a function that says that the function does not read / do not modify any global memory.

Given this information, the compiler can make some additional optimizations.

Example for 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)); } 

In this example, the compiler can optimize the function to calculate:

 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 += temp; return sum; } 

Or, if your compiler is smart enough (and not very strict in swimming):

 float calculate(float x, unsigned int C) { return C ? sigmoid(x) * C : 0.0f; } 

How can I mark a function this way for different compilers, i.e. GCC, Clang, ICC, MSVC or others?

+28
c ++ gcc const
May 09 '10 at 15:49
source share
1 answer

In general, it seems that almost all compilers support GCC attributes. MSVC is the only compiler that does not support them (and which also has no alternative).

+26
May 09 '10 at 17:32
source share



All Articles