Side effects in C

2019-08-12 01:30发布

I thought that my understanding of side effects in programming languages was OK.

I think this is a great definition from wikipedia:

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

However, I read this in the same link(yes, I know that is probably not the best place to look for examples):

"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;

Why do they consider that a side-effect? It is the same as two simple assignment statements to 2 local variables.

Thanks in advance.

3条回答
对你真心纯属浪费
2楼-- · 2019-08-12 01:57

I would presume that to be because j = 3 has the intended effect of assigning the value 3 to j but also has the side effect of returning the value of j

查看更多
SAY GOODBYE
3楼-- · 2019-08-12 02:04

If the state of the world, for example the value of a variable, is modified in a calculation, it's a side effect.

For example, j = 3 calculates 3, but it also modifies the value of j as a side effect.

A less trivial example: j += 3 calculates j + 3, but it also sets j to this new value.

The semantics of C muddle the waters: in C the main point of writing i = 1 is to get the side effect of the variable assignment; not calculating the value 1. The talk about assignments as side effects makes more sense with functional programming languages such as Haskell or Erlang, where variables can only be assigned once.

查看更多
SAY GOODBYE
4楼-- · 2019-08-12 02:09

You can use an assignment expression as a value:

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

The value produced by x = d, is its main effect. The changing of the value of x is a side effect.

查看更多
登录 后发表回答