bit-based swaping operation


I recently read a function that swaps two variable based on bit operation
1
2
3
4
5
6
void swap(int &i, int &j)
{
     i = i ^ j;
     j = j ^ i;
     i = i ^ j;
}


Will this operation support generic data types or just work for integer type?
Thanks!
Last edited on
It will work for anything that is the same size and memory alignment.
(But it isn't a good idea for anything but integers.)
Duoas,

Can you explain more why it isn't a good idea for anything but integers? Thanks.
Because when you start subverting the type safety built into the language then all bets are off.
(and anything that supports a bit-wise XOR operation).

Duoas is answering the question based on the fact that your swap() function takes two ints,
rather than being a template that can take any arbitrary type. If you make it a template,
then your swap works for any type that supports a bit-wise XOR operation. If you don't,
then you have to cast the types to int first, then call the function, at which point Duoas'
answer applies.
Topic archived. No new replies allowed.