Generic swap: Difference between revisions

→‎{{header|C}}: simplify; remove comments that basically described the second example
(→‎{{header|Delphi}}: Does not implement anything generic.)
(→‎{{header|C}}: simplify; remove comments that basically described the second example)
Line 99:
 
=={{header|C}}==
This has a restriction that a and b must be the same size.
This has a restriction that a and b must be the same size. I think you could do better with preprocessor voodoo, but I am not enlightened enough to use it. I'm being cute here, so please don't hate me too much, and if a C guru could check it, I'd appreciate it (I tried it and it worked for me). It won't work for something like a linked list if you want all references to middle nodes to be translated, but it'll swap the heads just fine.
 
<lang c>void swap(void *ava, void *bvb, size_t sizes)
{
char t, *caa = (char*)va, *cbb = (char*)vb;
while(--s)
int i;
ca t = (chara[s], *)a[s] = b[s], b[s] = t;
cb = (char *)b;
for(i=0;i<size;*(ca+i)^=*(cb+i),*(cb+i)^=*(ca+i),*(ca+i)^=*(cb+i),++i);
}</lang>
 
You could also do it with a third buffer but then it wouldn't work for extremely large void pointers. It'd be faster to use a larger pointer than char *, but I wanted to keep it simple.
 
==={{works with|gcc}}===
Anonymous user