As far as I know, impure functions are those which do not always return the same value when called with the same parameters (I must be missing something, or may be wrong, correct me if I am).
So why is printf()
considered to an impure function?
A "pure" function lacks side-effects too.
In other words, no matter how many times you call it, a pure function will affect nothing other than its output.
For example, foo
is impure, even though it return zero:
int x;
int foo() { x++; return 0; }
int bar() { return x; }
If foo
were pure, calling it would not affect the result of bar()
.
printf
is impure because its result has "side effects" -- specifically, it prints something on the screen (or in a file, etc).
If it were pure, then you could call it a billion times and be sure nothing bad would happen.
But if you actually call printf
a million times, there certainly is a difference to the user -- it fills up his screen (or disk space, or whatever). So clearly it's not pure.
Furthermore: If your output was redirected to be your own input (somewhat useless, but still), then calling printf
would affect what you would receive from getchar
. :) So it's directly observable that way, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With