N = 1;
A[N++] = N++;
I'd expect that to evaluate to a[1]=2 and n winds up being 3. But I'm weird.
This simple code snippet invokes "undefined behaviour" because:
'N' is modified twice within a single sequence block.
'N' is referenced within a sequence block separately from a modification
occuring within the same sequence block.
One might expect:
N = 1
Save address of A[1]
++N
(address of A[1]) = 2
++N
Which gives you the result you expected, however a compiler is free to
perform the side effects occuring within a sequence block at any time it
wishes, as long as it observes the charactistics of the operator causing
the side effect. (ie: one instance of N++ cannot increment N before
retrieving it's value, although the other instance of N++ could have
incremented it).
N = 1
A[1] = 1
N += 2
A[1] = 1, N = 3
N = 1;
++N (the second one)
A[2] = 1 (saved from above ++N)
++N (the first one)
A[2] = 1, N = 3
N = 1
Set temp to replace N to N+1
A[1] = 1
Set temp to replace N to N+1
N = temp to replace N
A[1] = 1, N = 2
You get the idea - run the above sequence without violating
the terms I mentioned at the beginning (ie: use separate
variables) and the same answer occurs in all cases.
Btw, technically, according to the standard, the compiler is
free to say:
N = 1
Humm... undefined behaviour...
A[500] = 9999
N = -1
Although I've never seen an implementation which actually
does this - usually you can fine some logical reason for the
results.
Dave
--
dave06a (at) Dave Dunfield
dunfield (dot) Firmware development services & tools:
www.dunfield.com
com Collector of vintage computing equipment:
http://www.classiccmp.org/dunfield/index.html