Strcpy () return value

Many functions from the C standard library, especially those used to process strings, and in particular strcpy (), use the following prototype:

char *the_function (char *destination, ...) 

The return value of these functions actually matches the return value of destination . Why would you spend the return value on something redundant? This means that such a function is invalid or returns something useful.

My only suggestion why this is so is it is easier and more convenient to insert a function call into another expression, for example:

 printf("%s\n", strcpy(dst, src)); 

Are there any other reasonable reasons to justify this idiom?

+22
c function strcpy
Aug 24 2018-10-10T00:
source share
5 answers

as Evan pointed out, you can do something like

 char* s = strcpy(malloc(10), "test"); 

eg. set malloc()ed memory to a value without using an auxiliary variable.

(this example is not the best, it will come out of a state of low memory, but the idea is obvious)

+18
Aug 24 2018-10-10T00:
source share

I believe your guess is correct, this makes the nested call easier.

+3
Aug 24 '10 at 10:10
source share

It is also very easy to code.

The return value usually remains in the AX register (this is optional, but it often happens). And the destination is placed in the AX register when the function starts. To get the destination back, the programmer needs to do ... nothing at all! Just leave the value where it is.

The programmer can declare the function as void . But this return value is already in the right place, just waiting for the return, and does not even require additional instructions to return it! No matter how small this improvement is, in some cases it is convenient.

+1
Aug 24 '10 at 22:21
source share

Same concept as Free Interfaces . Just make the code faster / easier to read.

0
Aug 24 '10 at 10:22
source share

I don’t think it is really set up that way for nesting purposes, but more for error checking. If the memory does not serve any of the standard library functions, they do a lot of error checking themselves, and therefore it makes sense that this will determine that something was wrong with the strcpy call.

 if(strcpy(dest, source) == NULL) { // Something went horribly wrong, now we deal with it } 
0
Feb 29 '16 at 13:34
source share



All Articles