A lot of the functions from the standard C library, especially the ones for string manipulation, and most notably strcpy(), share the following prototype:
char *the_function (char *destination, ...)
The return value of these functions is in fact the same as the provided destination
. Why would you waste the return value for something redundant? It makes more sense for such a function to be void or return something useful.
My only guess as to why this is is that it's easier and more convenient to nest the function call in another expression, for example:
printf("%s\n", strcpy(dst, src));
Are there any other sensible reasons to justify this idiom?
strcpy doesn't have any way to check errors itself. Also, it's required to always return dest , so it can only return NULL if it already tried to write into a NULL pointer, so a hypothetical system that catches SIGSEGV in strcpy and returns NULL would be violating that contract.
The strcpy() function shall return s1; no return value is reserved to indicate an error.
strcpy() — Copy Strings The strcpy() function copies string2, including the ending null character, to the location that is specified by string1. The strcpy() function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string.
Return value of strcpy() This function returns the pointer to the destination string or you can say that it returns the destination string str1.
as Evan pointed out, it is possible to do something like
char* s = strcpy(malloc(10), "test");
e.g. assign malloc()ed
memory a value, without using helper variable.
(this example isn't the best one, it will crash on out of memory conditions, but the idea is obvious)
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