According to http://en.cppreference.com/w/cpp/string/byte/memcpy C++’s memcpy takes three parameters: destination, source and size/bytes. It also returns a pointer.
void* memcpy( void* dest, const void* src, std::size_t count );
Why is that so? Aren’t the parameters enough to input and copy data?
Am I misunderstanding something? The examples don’t use the return value.
If a function has nothing specific to return, it is often customary to return one of the input parameters (the one that is seen as the primary one). Doing this allows you to use “chained” function calls in expressions. For example, you can do
specifically because
strcpyreturns the originaldstvalue as its result. Basically, when designing such a function, you might want to choose the most appropriate parameter for “chaining” and return it as the result (again, if you have noting else to return, i.e. if otherwise your function would returnvoid).Some people like it, some people don’t. It is a matter of personal preference. C standard library often supports this technique,
memcpybeing another example. A possible use case might be something along the lines ofIf
memcpydid not return the destination buffer pointer, we’d probably have to implement the above aswhich looks “longer”. There’s no reason for any difference in efficiency between these two implementations. And it is arguable which version is more readable. Still many people might appreciate the “free” opportunity to write such concise one-liners as the first version above.
Quite often people find it confusing that
memcpyreturns the destination buffer pointer, because there is a popular belief that returning a pointer form a function should normally (or always) indicate that the function might allocate/reallocate memory. While this might indeed indicate the latter, there’s no such hard rule and there has never been, so the often expressed opinion that returning a pointer (likememcpydoes) is somehow “wrong” or “bad practice” is totally unfounded.