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
Yes you need to define it yourself.
void swap(void* a, void* b, size_t length)
, but unlike std::swap
, it's not type-safe.inline
keyword).We could also define a macro like
#define SWAP(a,b,type) {type ttttttttt=a;a=b;b=ttttttttt;}
but it shadows the ttttttttt
variable, and you need to repeat the type of a
. (In gcc there's typeof(a)
to solve this, but you still cannot SWAP(ttttttttt,anything_else);
.)
And writing a swap in place isn't that difficult either — it's just 3 simple lines of code!