I am confused by the guarantees GCC makes about optimizing pure functions (from online docs):
pureMany functions have no effects except the return value and their return value depends only on the parameters and/or global variables. (...)
Interesting non-pure functions are functions with infinite loops or those depending on volatile memory or other system resources, that may change between two consecutive calls (such as
feofin a multithreading environment).
And for const:
constMany functions do not examine any values except their arguments, and have no effects except the return value. Basically, this is just slightly more strict class than the pure attribute below, since the function is not allowed to read global memory.
Note that a function that has pointer arguments and examines the data pointed to must not be declared
const. Likewise, a function that calls a non-const function usually must not be const.
So, I tried creating a function which does accept a pointer parameter, and tried marking it pure. However, I tried compiling this function using GCC online (I tried both const and pure):
typedef struct
{
int32_t start;
int32_t end;
}
Buffer;
inline __attribute__((pure,always_inline)) int32_t getLen(Buffer * b)
{
return b->end - b->start;
}
And noticed that GCC (at least the several online compiler versions I've tried):
- doesn't optimize calls to this function (i.e. calls it multiple times) if the passed
Buffer*parameter is pointing to a global value, - optimizes calls to this function (i.e. calls it only once), if the passed pointer is pointing to a local (stack) variable.
- both cases work the same even if I mark the function
constinstead ofpure, but presumablyconstis ignored if there is a pointer argument?
This is a good thing, because a global Buffer might change by a different thread/interrupt at any time, while a local Buffer is perfectly safe for optimizations.
But I am completely confused by the remarks regarding passing pointers. Is there a place where the behavior of the GCC is explicitly defined for pure functions accepting pointer arguments?