Re: Alternate sum mistake



On 10/17/2010 11:49 AM, superpollo wrote:
superpollo ha scritto:
Eric Sosman ha scritto:
[...]
There's at least one more bug in your code, a bug that a C test
framework might or might not reveal. Can you spot it? (Hint: What
sort of behavior gives rise to "might or might not" conditions in C?)

mmhhh... UB maybe?

but i cannot spot it at once... something related to the ++ operator?

as+=pow(-1,n)*a[n++]

there is no guarantee on the order of evaluation of the *, right? so
a[n++] could be evaluated prior to pow(-1,n), screwing up the sign.

close?

Extremely close indeed: congratulations! You've spotted the error,
and your only failing is that you've slightly mis-stated its effects.
It's not just that the order of evaluation is unspecified, but that it
is Undefined Behavior to both change the value of `n' and use it for
some other purpose without an intervening sequence point. In principle
anything at all could happen, although in practice the outcome is likely
to be as you describe: The second argument to pow() will be either the
original `n' or the incremented `n', unpredictably. ("Unpredictably"
not only from one program run to the next, but within a single run: If
an optimizer unrolls your loop so there are multiple copies of the
faulty expression in it, there's no surety that all of them behave the
same way.)

--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxxx
.