Now I've read yesterday that using const as the return value of the function, the program is told that this part within memory cannot be modified by the programmer hence it may be overridden. But is this really true? |
If any variable is declared as const, it's an indication that its value cannot be changed, and the compiler will stop you if you mistakenly attempt to change the value. It's a safety feature designed to catch programmer errors.
A function can return nothing or it can return something. Consider this example from the C standard library:
|
const char* strcpy(char* s1, const char* s2);
|
That means the function takes a string that can be modified, a string that will not be modified and returns non-modifyable string. That means if your write code like:
1 2 3 4 5 6 7 8
|
#include <string.h>
int main()
{
char name[32];
const char *s = strcpy(name, "Lua");
strcpy(s, "Ruby"); // can't do this: s is const
return 0;
}
|
I like to know how people before C++ arrived did it |
You'll have to remember two things.
1. The memory buffer that the string is in is just large enough for the string (includin the null terminator).
2. The user of the string must free the memory.
A standard function that works in this way is strdup().
http://pubs.opengroup.org/onlinepubs/007908799/xsh/strdup.html
An example of a function that concatenates two strings is:
1 2 3 4 5 6 7 8 9 10 11 12
|
char* mystrcat(const char *s1, const char *s2)
{
size_t len = strlen(s1) + strlen(s2) + 1;
char* s = malloc(len);
if (s)
{
strcpy(s, s1);
strcat(s, s2);
}
return s;
}
|
The user has to "know" that the string must be deleted when done with it.
And it's this "knowing" that makes its use error-prone.