且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么printf()的不纯的功能?

更新时间:2023-11-06 09:47:16

没有,一个不纯功能的是一款具有的副作用功能

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.

例如, 不纯 即使返回零的:

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 是不纯的,因为它的结果有副作用 - 具体而言,它打印屏幕上的内容(或文件等)结果。
如果是纯粹的,那么你可以把它叫做一个十亿倍,并确保没有什么不好会发生。结果
但是,如果你实际调用的printf 一万次,有一定的的用户的不同 - 它填补了他的屏幕(或磁盘空间,管他呢)。所以很明显它不是纯粹的。

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.

另外:如果你的输出重定向到是自己的输入(有点没用,但仍),然后调用的printf 会影响您会收到来自的getchar 。 :)所以这是直接观察到的那样了。

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.