"a[++i] = i" vs "a[i] = ++i"

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Dec 20 15:07:08 PST 2013


On Fri, Dec 20, 2013 at 11:29:54PM +0100, Ivan Smirnov wrote:
> I was wondering if this behavior is actually documented anywhere?
> Let's say we want to increment i and store the new value at the
> index equal to the new (incremented) value.
> 
> 	int[int] a;
> 	int i = 1;
> 	a[++i] = i;
> 	writeln(a);
> 	a[i] = ++i;
> 	writeln(a);
[...]

In C/C++, the evaluation order in this case is unspecified, so you're in
the territory of undefined behaviour. Whatever you observe will be
specific to the compiler (and version) you're using, and you cannot
depend on getting the same result across different compilers (or even
different versions of the same compiler, or even different compiler
flags -- using -O may change the behaviour in some cases).

Now, in D, I believe this is currently also undefined behaviour,
although Walter did mention at some point that he wanted to fix
evaluation order in these cases. But I don't know if that has happened
yet. Either way, you're treading on dangerous ground, since the spec
currently doesn't say one way or another, so different compilers could
have different interpretations of what the above code means. So the
runtime behaviour could change from compiler to compiler, or from
version to version, or from specifying -O or not.

Mixing side-effects in an expression that references the changed value
multiple times should be avoided in general because of these kinds of
ambiguity. For example, what should the following code do?

	int a = 1;
	int b = ++a * --a + --a * ++a;

(N.B. * must be evaluated before +. So does ++/-- get evaluated before
or after *, or something else?)


T

-- 
Государство делает вид, что платит нам зарплату, а мы делаем вид, что работаем.


More information about the Digitalmars-d-learn mailing list