tags:

views:

387

answers:

5

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.

+2  A: 

Probably because it's not needed very often - I memset and memcpy reasonably often, but I don't know that I'd ever have used memswap if it was available.

Colen
+5  A: 

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)
dvorak
+1  A: 

It probably isn't required very often in C programming, in C++ where swap is a regular thing to do on class members there's the std::swap algorithm which is highly optimized for different types.

Alaric
+2  A: 

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 :-

  • behaviour when the ranges being swapped overlap
  • length of zero
  • running out of memory (an optimal implementation might allocate memory to do this)
  • null pointer

The best algorithm might also depend upon what you are doing, and so could be better coded directly by you.

  • swapping structures likely to be quicker using a temp structure and assignment
  • small lengths - may be better allocating temporary memory
  • long lengths - 'section' by section swap (where section is some optimal length)
  • use of hardware copy functions
itj
The best algorithm isn't necessarily yours. GCC has `memset` as a keyword, and based on what it is you are memsetting, it might leave the function call, or have a for loop, or have an unrolled for loop, etc. compilers are smart these days.
Claudiu
A: 

have you looked at swab?

man swab

Yes, but that function does something else. It copies the content of the first array to the second and swaps the byte order at the same time.
quinmars