Re: brain teasers
- From: Daniel Rudy <spamthis@xxxxxxxxxxxx>
- Date: Thu, 05 Apr 2007 05:27:18 GMT
At about the time of 4/4/2007 11:43 AM, Martin Ambuhl stated the following:
rohitjogya@xxxxxxxxx wrote:
a = a^b;
b = a^b;
a = a^b;
So you know the stupid XOR trick. So what? Don't perpetuate this.
Just because every class of beginners has someone who thinks this is
cool doesn't mean that it is worth bothering with. And you neither
answered the question about what happens with non-integer variables nor
demonstrated why you think the compiler doesn't generate a hidden third
variable. If your trick doesn't work with non-integers (it doesn't),
then the original question has not been answered. If the compiler might
generate a hidden third variable, then the original question has not
been answered.
I agree. I didn't even know what the XOR trick was before this.
Looking at that code, I can't tell what it is or what it does without
getting a pencil and some paper and working it out manually.
To the OP:
#define MAXSWAP 32 /* maximum size of variable swap */
int swap(void *a, void *b, int size)
{
char temp[MAXSWAP]; /* temp buffer */
if (size > MAXSWAP) return(-1);
memcpy(temp, a, size);
memcpy(a, b, size);
memcpy(b, temp, size);
return(0);
}
Now what's wrong with that? That's a universal swap function that will
work with *ANY* datatype in any configuration (as far as I know) up to
32 bytes in size (int, long, float, double, char, signed, unsigned,
struct, etc...). Hell, this will work as is on any machine no matter
what the endian is (big, little, pdp, etc...). In fact, just changing
the MAXSWAP define, you can swap data of ANY size, and it's portable.
To use it?
int a, b;
....
swap(&a, &b, sizeof(int));
--or--
double x, y;
....
swap(&x, &y, sizeof(double));
It's that simple.
(Of course I probably made a simple mistake that the regulars are going
to jump all over me about.) :-)
--
Daniel Rudy
Email address has been base64 encoded to reduce spam
Decode email address using b64decode or uudecode -m
Why geeks like computers: look chat date touch grep make unzip
strip view finger mount fcsk more fcsk yes spray umount sleep
.
- Follow-Ups:
- Re: brain teasers
- From: Ian Collins
- Re: brain teasers
- From: Richard Heathfield
- Re: brain teasers
- References:
- brain teasers
- From: viv342
- Re: brain teasers
- From: Martin Ambuhl
- Re: brain teasers
- From: rohitjogya@xxxxxxxxx
- Re: brain teasers
- From: Martin Ambuhl
- brain teasers
- Prev by Date: Re: An interesting C problem
- Next by Date: Re: Memory leak when internal pointer passed out as parameter
- Previous by thread: Re: brain teasers
- Next by thread: Re: brain teasers
- Index(es):
Relevant Pages
|