Why doesn't have the c standard a memswap function, which would probably look like:
int memswap(void *ptr1, void *ptr2, size_t nbytes)?
I know it'd be easy to write, but i think the libc could do some awesome tricks to speed it up like some implementations do it for memcpy.
I think because it's not needed very often. However, there is an easy way to do this in C++:
#include <algorithm>
swap_ranges(ptr1, ptr1 + nbytes, ptr2)
It's it may not be quite as optimized as a compiler built in, but it has the potential of being faster than a loop you write for yourself, since it may have platform specific optimization that you would not implement.
You do need to be careful with the above, because it assumes that ptr1 and ptr2 are char pointers. The more canonical way to do this is:
#include <algorithm>
swap_ranges(ptr1, ptr1 + num_items, ptr2)
This isn't something that is routinely required.
The ideas may have been considered and discarded because it is quite difficult to come up with an algorithm that is general purpose. Don't forget that C is an old language and extensions need to be generally useful.
Possible error conditions :-
The best algorithm might also depend upon what you are doing, and so could be better coded directly by you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With