[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [Fun With Perl] Re: How to swap $p and $q without $tmp




> > > > > >    $q^=$p^=$q^=$p
> Would that really be undefined in C?  The RHS of an assignment has to be
> evaluated before the assignment is performed.

When the RHS contains side effects, these side efficts might occur
before, during, or after the assignment takes place.  Specifically,
the C standard says that if you modify the same object twice with no
intervening sequence point, the result is undefined.

This is because computers with multiple processors may try to to
various reads and writes simultaneously. For example, in

	x = y = EXPR;

a multiple-processor compiler may try to store into x and y
simultaneously.  Another example:  

	x = y = z++;

might compile to the following sequence of instructions:

	STO z temp
	STO temp x; STO temp y; INC z

Where the last three occur simultaneously.  Now consider:	

	x = y = x++;

The instruction  pattern above becomes:

	copy x to TEMP
	copy TEMP to x  | copy TEMP to y | increment x

We see that one processor is trying to copy TEMP to x while another
processor is trying to increment x.  Depending on the hardware, the
result of this could be any of:

	1. x doesn't change
	2. x is incremented
	3. x gets a garbage value
	4. The program causes a hardware fault and aborts
	5. Conceivably, the computer might burst into flames

The X3J11 committee did not want to rule out this sort of
optimization, so instead they ruled out dubious constructions like (x
= x++) which were not historically well-defined anyway.



==== Want to unsubscribe from this list? (Don't you love us anymore?)
==== Well, if you insist... Send mail with body "unsubscribe" to
==== fwp-request@technofile.org