Thread overview
Xor trick?
Jan 26, 2014
bearophile
Jan 26, 2014
Martin Cejp
Jan 26, 2014
Ali Çehreli
Jan 26, 2014
Adam D. Ruppe
Jan 26, 2014
bearophile
Jan 26, 2014
H. S. Teoh
January 26, 2014
Do you know how to perform the xor trick (http://en.wikipedia.org/wiki/XOR_swap_algorithm ) on two pointers in D?

This is a try:


void foo(T)(ref T x, ref T y) pure nothrow {
    x ^= y;
    y ^= x;
    x ^= y;
}
void main() {
    int* p, q;
    foo(p, q);
}


Currently that gives:

test.d(2): Error: 'x' is not of integral type, it is a int*
test.d(2): Error: 'y' is not of integral type, it is a int*
test.d(3): Error: 'y' is not of integral type, it is a int*
test.d(3): Error: 'x' is not of integral type, it is a int*
test.d(4): Error: 'x' is not of integral type, it is a int*
test.d(4): Error: 'y' is not of integral type, it is a int*
test.d(8): Error: template instance test.foo!(int*) error instantiating

Bye,
bearophile
January 26, 2014
That's what you get for trying to be a smartass!

Seriously though, why would you want to do this? It's not actually faster or anything, you know.
January 26, 2014
On Sunday, 26 January 2014 at 00:04:08 UTC, bearophile wrote:
> Do you know how to perform the xor trick (http://en.wikipedia.org/wiki/XOR_swap_algorithm ) on two pointers in D?

You don't; it is undefined behavior and could lead to crashes. Suppose another thread triggers a GC run right after the first xor. Then there may be no valid pointers to *x and the GC frees it, so then after the swap, *y points to something entirely different.

> test.d(2): Error: 'x' is not of integral type, it is a int*

You could cast it to size_t, then the compiler will let you do the operation, but casting pointers to and from integers means you take matters of correctness into your own hands.
January 26, 2014
Adam D. Ruppe:

> You could cast it to size_t, then the compiler will let you do the operation, but casting pointers to and from integers means you take matters of correctness into your own hands.

Right, so I have to carry around size_t instead of pointers.

Bye and thank you,
bearophile
January 26, 2014
On 01/25/2014 04:08 PM, Martin Cejp wrote:
> That's what you get for trying to be a smartass!
>
> Seriously though, why would you want to do this? It's not actually
> faster or anything, you know.

Yeah, surprisingly, it is not faster for integers either. It was probably faster for older CPUs.

Ali

January 26, 2014
On Sun, Jan 26, 2014 at 12:14:40AM +0000, bearophile wrote:
> Adam D. Ruppe:
> 
> >You could cast it to size_t, then the compiler will let you do the operation, but casting pointers to and from integers means you take matters of correctness into your own hands.
> 
> Right, so I have to carry around size_t instead of pointers.
[...]

And you can't use the GC since the GC won't be able to find your xor'd pointers.


T

-- 
WINDOWS = Will Install Needless Data On Whole System -- CompuMan