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

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Dec 23 16:48:20 PST 2013


On Mon, Dec 23, 2013 at 04:12:05PM -0800, Charles Hixson wrote:
> On 12/23/2013 12:39 PM, David Held wrote:
[...]
> >int mightUpdate(int& x)
> >{
> >    ...
> >    return x;
> >}
> >
> >{
> >    ...
> >    a[mightUpdate(i)] = mightUpdate(i);
> >    ...
> >}
> >
> >Is this also a bug?  How would the compiler know whether to emit a
> >diagnostic for this case?
> >
> >Dave
> >
> >
> Yes, that should be an error.  And the compiler could notice that the
> function parameter values are allowed to be modified, and forbid such
> use.  As it should.  After all, who's going to know which call would
> modify the value of i?  Of course, it could be protocol that the
> functions included within the statement are all called before the
> local values are calculated, and that if the same syntax appears
> twice, the final value of the syntax is the value used...but that,
> while reasonable for the compiler, is hell on people reading the code.
> 
> Note that one can make several different plausible arguments as to
> the order in which the code should be evaluated.  When such is
> possible, the code should be an error.  And when it relies on rarely
> used rules, it should probably be an error.  (E.g., if you define
> that the location into which values will be stored must be evaluated
> before the expression to be stored is evaluated, you have a case
> that would be well defined, but it's a "rare event" kind of rule,
> and unless there's good reason, it should be an error.)
[...]

Agreed. Note that introducing assignment into the mix may not help
matters, but complicate them even more. For example:

	int x=1, y=0;
	writeln((y = ++x) + (++y--) * (x=y)); // what does this print?

Or worse yet:

	int func1(int x) { ... }
	int func2(int x) { ... }
	int func3(int x) { ... }

	int function(int)[] funcptrs = [ &func1, &func2, &func3 ];

	int x=0, y=0;
	y += funcptrs[++x--](y = --x++); // what does this do?

The only place I can see where you'd even *want* to write code like this
is in an entry to the IOCCC. Make it refuse to compile, I say.


T

-- 
"Holy war is an oxymoron." -- Lazarus Long


More information about the Digitalmars-d-learn mailing list