I am learning about side-effects and pure functions. I know that pure functions have no side-effects and their return value is the same for the same arguments. I would like to know whether the C function strcmp()
is a pure function. I believe that it is pure, due to the fact that given the same two strings as parameters, the result will always be the same. Furthermore, strcmp()
does not modify any variables or call any functions, thus it does not have any side effects.
However I am not sure whether my reasoning is correct.
strcmp()
is a pure function, since the result is dependant solely on the parameters and in addition, it does not modify a global state.
Of course, improper use of strcmp()
may invoke undefined behaviour, but this is not relevant for it being pure or impure.
Edit:
A pure function only yields the same results, when the global memory referenced is also the same. Functions, which do not require that are called constant functions.
GCC documentation provides strlen() as an example of a pure function. Indeed, this function takes a pointer as a parameter, and accesses it to find its length. This function reads global memory (the memory pointed to by parameters is not considered a parameter), but does not change it, and the value returned derives from the global memory accessed.