问题描述
维基百科说:
在计算机科学中,如果操作、函数或表达式在其本地环境之外修改某些状态变量值,则称其具有副作用,也就是说具有除了向操作的调用者返回一个值(主要效果)之外,还有一个可观察的效果.
但是我们如何访问一个变量在其本地环境之外,有没有人能通俗地解释一下这种情况、副作用、主效应和序列点?
But how can we access a variable outside its local environment, can anyone explain this situation, side effect, main effect and sequence point comprehensibly?
推荐答案
一个函数是(应该)一个黑盒子,其中返回值,或者通过引用传递的变量的值,应该是唯一的东西可能会因输入参数而异.
A function is (should be) a black box, in which the return value, or the value of a variable passed by reference, should be the only thing that may change depending upon the input parameters.
函数在这些情况之外产生的任何其他可观察到的变化都是副作用.最著名的例子可能是 printf()
函数,它除了返回写入的字符数外,还改变标准输出的内容,这意味着改变一些与管道相关的内存缓冲区,一个文件或屏幕,例如,不属于函数的本地环境.
Any other observable change that the function produces outside these cases, is a side-effect. The most well-known example may be the printf()
function which, besides returning the number of written characters, changes the contents of the standard output, which means altering some memory buffer associated with a pipe, a file, or the screen, for instance, and which doesn't belong to the local environment of the function.
这篇关于C中的副作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!