Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Side effects in C

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.

like image 590
Cacho Santa Avatar asked Nov 30 '25 11:11

Cacho Santa


2 Answers

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.

like image 84
Eric Postpischil Avatar answered Dec 03 '25 00:12

Eric Postpischil


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.

like image 25
Joni Avatar answered Dec 03 '25 01:12

Joni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!