问题
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?
回答1:
No, an "impure" function is a function with side-effects.
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.
回答2:
There are two parts to being a pure function. The first, as you stated, is that the function must consistently return the same value for the same input parameters. The second criterion, which printf
does not fulfill, is that the function must not have side effects like I/O or object mutation.
回答3:
Simply put, printf
is impure because it does I/O
. I/O
by definition is impure because of the presence of external state of the I/O
device (state which may vary from execution to execution).
回答4:
The significance of pure functions in programming is that the implementation can optimize out a call of a pure function if it already has the result of a call of that function with the same parameters. Clearly that cannot be done for calls to printf.
P.S. Even by your definition, printf is impure because it can return one value when it succeeds and a different value if there's an I/O error, e.g., out of space on the output device.
回答5:
printf()
is impure because it causes output to an I/O device as a side effect.....
回答6:
A lot of the answers explain that printf
has I/O as a side-effect, but printf
can have other side-effects too. For example, the %n
specifier allows printf
to write to a specified address (and is the cause of some security vulnerabilities).
来源:https://stackoverflow.com/questions/11919894/why-is-printf-an-impure-function