Because were to:do: not inlined the expression passed as the to: actual
argument would be evaluated exactly once (bound to the formal argument for to:)
and so assigning to a temporary preserves the semantics in the most direct way.
If the expression has side effects then those side effects must occur only
once.
Note that were the to: expression merely another variable then the compiler
could only substitute the original variable if it's value could not change,
e.g. in
exampleToDoArgumentLimitIsExpression
| count sum |
count := 10.
sum := 0.
1 to: count do: [ :each | sum := sum + each].
^sum
It is ok to use count directly as the limit variable, but in this it is not:
exampleToDoArgumentLimitIsExpression
| count sum |
count := 10.
sum := 0.
1 to: count do: [ :each | sum := sum + each. count :=
#somethingElseEntirely].
^sum
_,,,^..^,,,_ (phone)
> On Nov 19, 2015, at 1:14 PM, Nicolai Hess <[email protected]> wrote:
>
> What is the purpose of replacing expressions, used as limits in a
> to:do: call with by a new temporary variable?
>
> For example:
>
> OCOpalExamples>>#exampleToDoArgumentLimitIsExpression
> the code is
>
> exampleToDoArgumentLimitIsExpression
> | count sum |
> count := 10.
> sum := 0.
> 1 to: count - 1 do: [ :each | sum := sum + each].
> ^sum
>
> the decompiled bytecode :
>
> exampleToDoArgumentLimitIsExpression
> | tmp1 tmp2 tmp3 |
> tmp1 := 10.
> tmp2 := 0.
> tmp3 := tmp1 - 1.
> 1 to: tmp3 do: [ :tmp4 | tmp2 := tmp2 + tmp4 ].
> ^ tmp2
>
> So, the expression (count - 1) in the to:do: loop is replaced by a new
> temporay (tmp3).
>
> Ok, but why ?