in reply to Re: Re: Re: Swapping two values
in thread Swapping two values

I think that the point the Anonymous Monk was making that it falls over badly if $a and $b refer to the same sequence of bits in memory. Consider:

# swap ($s, $p1, $p2, $n); # in $s swap the $n bits at bit $p1 and $p2 sub swap { vec($_[0],$_[1],$_[3]) ^= vec($_[0],$_[2],$_[3]); vec($_[0],$_[2],$_[3]) = vec($_[0],$_[1],$_[3]) ^ vec($_[0],$_[2], +$_[3]); vec($_[0],$_[1],$_[3]) = vec($_[0],$_[1],$_[3]) ^ vec($_[0],$_[2], +$_[3]); }; # swap first two and second two chars my $string = "ABCD"; print "$string\n"; swap($string, 0,16,16); print "$string\n";

The problem with code like this is that it falls down badly if the bits sequences being swapped overlap. Consider:

# swap first character with itself swap($string, 0, 0, 8);

Anything XORed with itself is zero. Oops :-)

Replies are listed 'Best First'.
Re: Re: Re: Re: Re: Swapping two values
by Anonymous Monk on Feb 16, 2003 at 03:30 UTC
    Exactly. The optimization assumes that changing one variable does not change the other and vice versa. When they overlap in memory, this stops being true.
Re: Re: Re: Re: Re: Swapping two values
by sauoq (Abbot) on Feb 16, 2003 at 00:34 UTC

    You're probably right. The post makes some sense in that context. It's true, of course, that you can't reliably swap a string's characters in place using the XOR method. You can, however, swap pointers that point into the same string in memory without any problems. In any case, the method does have merit as an optimization in C. But not Perl! :-)

    -sauoq
    "My two cents aren't worth a dime.";