Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is function with useless isolated `static` considered impure?

In Wikipedia article on Pure function, there is an example of impure function like this:

void f() {
  static int x = 0;
  ++x;
}

With the remark of "because of mutation of a local static variable".

I wonder why is it impure? It's from unit type to unit type, so it always returns the same result for same input. And it has no side effects, because even despite it has static int variable, it's unobservable by any other function than this f(), so there is no observable mutation of global state that other functions might use.

If one argues that any global mutations are disallowed, regardless of whether they are observable or not, then no real life function can be considered pure ever, because any function would allocate its memory on stack, and allocation is impure, as it involves talking to MMU via OS, and allocated page might be residing in a different physical page, and so on, and so on.

So, why does this useless isolated static int makes function impure?

like image 676
toriningen Avatar asked Mar 03 '23 17:03

toriningen


1 Answers

The result of a pure function is fully defined by its input arguments. Here, the result means not only the returned value, but also the effect in terms of the virtual machine defined by the C/C++ standard. In other words, if the function occasionally exhibits undefined behavior with the same input arguments, it cannot be considered pure (because the behavior is different from one call to another with the same input).

In the particular case with the static local variable, that variable may become the source of a data race if f is called concurrently in multiple threads. Data race means undefined behavior. Another possible source of UB is signed integer overflow, which may eventually happen.

like image 136
Andrey Semashev Avatar answered Mar 05 '23 17:03

Andrey Semashev