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.
I would presume that to be because
j = 3
has the intended effect of assigning the value3
toj
but also has the side effect of returning the value ofj
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 ofj
as a side effect.A less trivial example:
j += 3
calculatesj + 3
, but it also setsj
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 value1
. 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.You can use an assignment expression as a value:
The value produced by
x = d
, is its main effect. The changing of the value ofx
is a side effect.