In computer programming, a pure function is a function that has the following properties: the function return values are identical for identical arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams), and the function has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or input/output streams). Some authors, particularly from the imperative language community, use the term "pure" for all functions that just have the above property 2 (discussed below). The following examples of C++ functions are pure: The following C++ functions are impure as they lack the above property 1: The following C++ functions are impure as they lack the above property 2: The following C++ functions are impure as they lack both the above properties 1 and 2: I/O is inherently impure: input operations undermine referential transparency, and output operations create side effects. Nevertheless, there is a sense in which a function can perform input or output and still be pure, if the sequence of operations on the relevant I/O devices is modeled explicitly as both an argument and a result, and I/O operations are taken to fail when the input sequence does not describe the operations actually taken since the program began execution. The second point ensures that the only sequence usable as an argument must change with each I/O action; the first allows different calls to an I/O-performing function to return different results on account of the sequence arguments having changed. The I/O monad is a programming idiom typically used to perform I/O in pure functional languages. Functions that have just the above property 2 allow for compiler optimization techniques such as common subexpression elimination and loop optimization similar to arithmetic operators. A C++ example is the length method, returning the size of a string, which depends on the memory contents where the string points to, therefore lacking the above property 1.
Martin Odersky, Dmytro Petrashko, Allan Vincent Roger Renucci