Wednesday, June 20, 2018

c - What is the purpose of returning a char* in strcat, strcopy, (etc), when there is a destination variable?



Just a silly but quick question: Why do some functions that work with c style strings such as: fgets, strcpy, strcat, etc, have a return type of char* when there is a variable in the parameter list that stores the output? ie, why is it:



char *strcat ( char *dest, const char *src );


and not




void strcat ( char *dest, const char *src );


or even just returning the result by doing



char *strcat (const char *src );


I mean I can see how this would be useful if you are nesting calls to these functions (which is dangerous) but I don't see why you need to have both a destination variable AND returnt he result...




I'm reviewing some c programming stuff and can't believe how much I forgot!


Answer



For the sake of ease of usage, so that these functions can be used in larger expressions or can be nested.



Something like:



strcat(path, strcpy(file, "foo.txt")); 



or



printf("[%s]\n", strcat(string1, string2));


Needless to say these usages can and should be avoided.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...