Click to See Complete Forum and Search --> : Programming question in C
Concrete Geist
11-22-2001, 06:44 PM
This question has got me baffled, and I want to know how it would be done, so could an experienced programmer show how this is accomplished?? thanks.
Define a preprocessor macro swap(t, x, y) that will swap two arguments x and y of a given type t.
x ^= y
y ^= x
x ^= y
swaps two variables using xor.
as for the type, i'm not quite sure what would be necessary for that.
#define swap(x,y) x^=y;y^=x;x^=y
pinoy
11-22-2001, 07:23 PM
#define swap(t, x, y) \
do { t tmp = x; x = y; y = tmp; } while(0)
bdg1983
11-22-2001, 10:03 PM
:cool: c++ template functions :cool:
pinoy
11-22-2001, 10:56 PM
template <typename T> swap(T a, T b) { T c = a; a = b; b = c; }
jemfinch
11-23-2001, 01:55 AM
Originally posted by pinoy:
template <typename T> swap(T a, T b) { T c = a; a = b; b = c; }
Shouldn't those function arguments be passed by reference?
Jeremy
pinoy
11-23-2001, 03:39 AM
Originally posted by jemfinch:
<STRONG>
template <typename T> swap(T a, T b) { T c = a; a = b; b = c; }
<HR></BLOCKQUOTE>
Shouldn't those function arguments be passed by reference?
Jeremy</STRONG>
You're right, they should be. Most of my code posted here are not tested :(
Thanks for pointing that out.
pinoy
11-23-2001, 03:41 AM
Originally posted by jkm:
<STRONG>x ^= y
y ^= x
x ^= y
swaps two variables using xor.
as for the type, i'm not quite sure what would be necessary for that.
#define swap(x,y) x^=y;y^=x;x^=y</STRONG>
This only works for integral type. and doesn't work when used in an unbracketed if block.