Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

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!

like image 424
Jake Vizzoni Avatar asked May 07 '12 04:05

Jake Vizzoni


People also ask

What is the purpose of strcat () function?

strcat() — Concatenate Strings The strcat() function concatenates string2 to string1 and ends the resulting string with the null character. The strcat() 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.

What is the return type of strcat?

Return Value The strcat() function returns a pointer to the concatenated string ( string1 ).

What is the return of strcpy?

In the C Programming Language, the strcpy function copies the string pointed to by s2 into the object pointed to by s1. It returns a pointer to the destination.

Can you strcpy a char?

char* strcpy(char* destination, const char* source); The strcpy() function copies the string pointed by source (including the null character) to the destination. The strcpy() function also returns the copied string.


1 Answers

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.

like image 165
Alok Save Avatar answered Sep 29 '22 19:09

Alok Save