GuGu wrote:
>>> int& func( int& i ) { return ++i; }
>>> A = B[ func(i) ] + B[ func(i) ];
>>>
>>> And they told me that write something similar is absolutely wrong.
>>> Mine is just a nightmare or what they are telling me is true?
>>
>> Yes, that code is horrible. When reading it without seeing the
>> declaration of func() in view, I would guess that it should yield the
>> same result both times, so you can extract the call to func() and store
>> it in a tem****ary.
>
> That's absolutely true, but nobody know what exactly func(i) do (what
> about this function returns random values?).
Huh? Here it is:
int& func( int& i ) { return ++i; }
> So my position is that the compiler cannot decide to optimize in "any
> way" this expression because it will be a huge error.
If a function's implementation isn't available to the compiler, it
obviously
must assume that the function returns different results on different
calls.
Even if it doesn't return anything, the compiler can't remove the calls
either, because it might have side effects.
If the compiler knows (how doesn't matter) that subsequent invocations
yield
the same results and not cause side effects (like e.g. for sin()), it is
allowed to optimise out calls. Why? Simply because you couldn't tell the
difference anyway. As soon as you start introducing side effects that
would
allow you to tell how often the function was called, the optimisation
would
not be legal anymore.
>> However, it could also first invoke the left hand side of the addition
>> and then the right one:
>>
>> int _1 = B[func(i)];
>> int _2 = B[func(i)];
>> A = _1 + _2;
>
> I agree with you that this is a better way to write the same code.
Sorry, but I'm afraid you don't understand. This might be a better way to
express what you want the code to do, but my point is that this code does
something very specific and well-defined while the original doesn't. IOW,
it is not just "a better way to write the same code". This code works
reliably, while the original doesn't.
Uli


|