I know how to swap 2 variables in c++ , ie you use std::swap(a,b)
.
question:
Does the C
standard library have a similar function
In C this is often done using a macro,
there are very simplistic examples, eg:#define SWAP(type,a,b) {type _tmp=a;a=b;b=_tmp;}
... but I wouldn't recommend using them because they have some non-obvious flaws.
This is a macro written to avoid accidental errors.
#define SWAP(type, a_, b_) \
do { \
struct { type *a; type *b; type t; } SWAP; \
SWAP.a = &(a_); \
SWAP.b = &(b_); \
SWAP.t = *SWAP.a; \
*SWAP.a = *SWAP.b; \
*SWAP.b = SWAP.t; \
} while (0)
SWAP(a[i++], b[j++])
doesn't give problem side effects.SWAP
, so as not to cause bugs if a different name happens to collide with the hard-coded name chosen.memcpy
(which in fact ended up doing real function calls in my tests, even though a compiler may optimize them out).