tags:

views:

103

answers:

4

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?

+2  A: 

I believe that your guess is correct, it makes it easier to nest the call.

Evan Teran
+4  A: 

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)

Yossarian
`char *s = strcpy(xmalloc(10, my_jmpbuf), "test");` with an `xmalloc` that performs `longjmp` on failure would make this idiom sane.
R..
Thank you Yossarian, this way it makes a lot of sense. In general, if the destination argument is an expression, then the return value could be useful as it would be the evaluated result of that expression.
Blagovest Buyukliev
Possible, yes, very silly, certainly. The desire to avoid a helper variable is far outweighed by the fact that your program will bomb badly. You'd be better off using (or even writing if you don't have one) `strdup`: http://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c/252802#252802.
paxdiablo
+1  A: 

Its also extremely easy to code.

The return value is typically left in the AX register (it is not mandatory, but it is frequently the case). And the destination is put in the AX register when the function starts. To return the destination, the programmer needs to do.... exactly nothing! Just leave the value where it is.

The programmer could declare the function as void. But that return value is already in the right spot, just waiting to be returned, and it doesn't even cost an extra instruction to return it! No matter how small the improvement, it is handy in some cases.

abelenky
Funny, I can find no mention of an AX register in the ISO C standards documents :-)
paxdiablo
A: 

Same concept as Fluent Interfaces. Just making code quicker/easier to read.

palswim