|Fundamental C- Side Effects, Sequence Points And Lazy Evaluation|
|Written by Harry Fairhead|
|Monday, 11 February 2019|
Page 1 of 3
Operators are one of C's strong points and it is important to know how to use them - but what are side effects and who ordered sequence points!? It all can seem confusing. This extract, from my new book on programming C in an IoT context, provides a very helpful explanation.
Fundamental C: Getting Closer To The Machine
Now available from Amazon.
Also see the companion volume: Applying C
Covered in the chapter but not included in this extract.
An important idea in C is that assignment is treated as a dyadic operator with the lowest precedence. The operator = stores the value on the right-hand side in the variable on the left-hand side and then its result is the value of the right-hand side.
Put more academically you can say that the result of A=B is B but the operator has a side effect of storing the value of B in A.
In general side effects are bad ideas because they spoil the purity of the picture of an operation that combines a number of values to give a result.
For example, in A=B+C the + has a higher priority so B+C is evaluated and then the result is used in A=result.
Treating assignment as an operator means that you can, if you really want to, write expressions like:
which first evaluates A=B to give B and as a side effect stores this in A and then adds C to B and assigns this to D.
Notice that == is the test for equality in C and so:
assigns C to B and tests if C is equal to A in a single expression. The brackets are necessary because == has a higher priority than =.
Taking this a little further, C also allows other operators to be combined with the assignment operator.
translates to A=A+1.
Another subtle point concerns what:
Is it (A*2)+3 or is it A*(2+3)?
The answer is that it is A*(2+3) even though the * should have a higher priority than the +. The reason is of course that the *= operator has a lower priority than * or +.
Once you have introduced the idea of a side effect as part of the assignment operator you might as well carry on and introduce other operators with side effects.
For example, the unitary operator ++ when used as a postfix operator in A++ returns current value of A. That it is the same as just writing A, but as a side effect it increments A. In other words, if A is 3 then after B=A++, B is set to 3 and A is set to 4.
Notice that this is quite different from ++A, the corresponding unary prefix operator, the result of which is A+1 and which has the side effect of incrementing A. So, if A is 3 then, after B=++A, B is set to 4 and so is A. Notice that the ++ postfix operator has the highest priority and associates from left to right, whereas as a prefix operator it has a priority of 2 and associates from right to left. Also notice that A++ has the same meaning as A+=1.
|Last Updated ( Sunday, 17 March 2019 )|