Group: comp.lang.c++
From: Joe Greer
Date: Thursday, November 29, 2007 12:21 PM
Subject: Re: Swap two integers without using temporary variable

Kai-Uwe Bux wrote in
news:fimnp4$jb1$1@murdoch.acc.Virginia.EDU:

> terminator wrote:
>
>> On Nov 29, 12:52 pm, James Kanze wrote:
>>> Juha Nieminen wrote:
>>> > James Kanze wrote:
>>> > > ns per machine memory
>>> > > iter. instr. accesses
>>> > > SwapperClassic: 1.7 5 5
>>> > > SwapperXor: 2.5 9 7
>>> > Couldn't the compiler recognize the "I'm trying to outsmart the
>>> > compiler when swapping these integers by using the xor trick"
>>> > idiom and change it to the classic swapping code?
>>>
>>> Only if it could prove that the swap didn't involve the same
>>> objects. Since swapping usually takes place through references
>>> and pointers, this would be non-trivial (and not applicable in
>>> most of the really critical cases, in sort, for example). So
>>> you have an optimization that is expensive to check, can rarely
>>> be applied, and would never be applicable to well written code
>>> anyway. Not very interesting.
>>>
>>> > After all, many compilers detect quite some idioms. For example
>>> > many
>>> > compilers detect that something like "a = (a << 8) | (a >> 24);"
>>> > is actually a rotation and compile that as one single opcode.
>>>
>>> That's because such an expression is *always* a rotation.
>>
>> old C books say that it is shift,is the behavoir changed since then?
>
> I thaught a << 8 is a shift and a >> 24 is a shift. So,
>
> ( a << 8 ) | ( a >> 24 )
>
> would be a rotation assuming a bitlength of 32.
>
>
> [snip]
>
>
> Best
>
> Kai-Uwe Bux
>
>

I don't know about now, but in the olden days, << always 0 filled and >>
was machine dependent. On the machines I used back then, if a were
signed, then >> 1 filled that is, the sign bit got carried so that a >>
1 was always equivalent to a / 2. That would mean that the above would
generate a mess for a signed a rather than a rotation.

joe

Safety Articles | Usenet Groups | Usenet News | Bluegrass