gpt4 book ai didi

c++ - C 中的副作用

转载 作者:太空狗 更新时间:2023-10-29 23:24:50 24 4
gpt4 key购买 nike

我认为我对编程语言中的副作用的理解还可以。

我认为这是来自 wikipedia 的一个很好的定义:

"in addition to returning a value, it also modifies some state or has an observable interaction with calling functions or the outside world."

但是,我在同一个链接中读到了这个(是的,我知道这可能不是寻找示例的最佳位置):

"One common demonstration of side effect behavior is that of the assignment operator in C++. For example, assignment returns the right operand and has the side effect of assigning that value to a variable. This allows for syntactically clean multiple assignment:"

int i, j;
i = j = 3;

为什么他们认为这是副作用?它与对 2 个局部变量的两个简单赋值语句相同。

提前致谢。

最佳答案

您可以使用赋值表达式作为值:

double d = 3.5;

int x, y;

printf("%d", x = d); // Prints "3".

y = (x = d) * 5; // Sets y to 15.

double z = x = d; // Sets z to 3 (not 3.5).

x = d 产生的值是它的主要作用。 x 值的改变是一个副作用。

关于c++ - C 中的副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16221359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com