为什么printf()的不纯的功能? [英] Why is printf() an impure function?

查看:130
本文介绍了为什么printf()的不纯的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,非纯函数是那些并不总是返回时使用相同的参数调用相同的值(我必须失去了一些东西,也可能是错的,纠正我,如果我)。

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).

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

So why is printf() considered to an impure function?

推荐答案

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

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 会影响您会收到来自<$ C $什么C>的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.

这篇关于为什么printf()的不纯的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆