Today i was reading about pure function, got confused with its use:
A function is said to be pure if it returns same set of values for same set of inputs and does not have any observable side effects.
e.g. strlen()
is a pure function while rand()
is an impure one.
__attribute__ ((pure)) int fun(int i)
{
return i*i;
}
int main()
{
int i=10;
printf("%d",fun(i));//outputs 100
return 0;
}
The above program behaves in the same way as in the absence of pure
declaration.
What are the benefits of declaring a function as pure
[if there is no change in output]?
__attribute__((pure))
is present or not. (gcc 4.4.5, with or without -O3). I suspect that gcc can figure out himself thatfun()
is pure. (Note that I also tried with your example). – Disjunctivefunction attributes
can be found here: gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html – Devonnaprintf
, for example, would qualify (calling it twice with the same arguments yields the same return value), but it is not pure. – Skyros...and no side-effects...
part. – Embreyprintf
gives the same output for the same input, yet it is not pure. I agree with this - hence I wrote that the definition ofpurity
given in the question should mention that a function must not have side-effects. With that addition,printf
would no longer be pure. – Embreystrlen()
isn't a pure function. I can modify the perceived length of a string at runtime, yet pass the same pointer. – Farisstrlen
’s result, for instance when used in a loop (for (i = 0; i < strlen(str); ++i)
) but not because it’s pure (it isn’t – you’re right), but because it’s a builtin that gets special treatment from the compiler (-fno-builtin
disables this). I’m assuming that the compiler does this only for string literals where it can be sure that the string isn’t modified (that’s UB), otherwise it’d have to trace aliases to the memory location to prove that it’s not modified through any pointer. – Module