Reputation: 26501
Why does strcpy(3)
(and strncpy(3)
) return their first argument? I don't see how this does add any value. Instead, frequently I'd rather have the number of copied bytes returned.
Addendum: What am I supposed to do when I need also the length of the resulting string? Do I really have to implement my own version?
Upvotes: 6
Views: 1726
Reputation: 51
Most of the string functions in the C library have been designed by amateurs. For instance, in my 25 years of my career, I never used the strcat() function, yet I concatenate strings all the time. Also, if you think the printf(), there is little documentation if you pass NULL for a %s argument. The same goes for for the %c passing a '\0', or a malloc(0).
Sadly, the most useful strcpy() should return a pointer to the end of the destination buffer to chain copying.
Upvotes: 1
Reputation: 363597
For historical reasons. strcpy
and friends date back to the early seventies, and I guess the intended use case for the return value would be a kind of chaining:
// copy src into buf1 and buf2 in a single expression
strcpy(buf1, strcpy(buf2, src));
Or
char *temp = xmalloc(strlen(const_str) + 1);
function_that_takes_mutable_str(strcpy(temp, const_str));
Upvotes: 4
Reputation: 14039
So that you can do something like
char * str = strcpy(malloc(12), "MyNewString");
Upvotes: 1