So, I know the differences between char const *, char * const, and char const * const. Those being:
char* the_string : I can change the char to which the_string points, and I can modify the char at which it points.
const char* the_string : I can change the char to which the_string points, but I cannot modify the char at which it points.
char* const the_string : I cannot change the char to which the_string points, but I can modify the char at which it points.
const char* const the_string : I cannot change the char to which the_string points, nor can I modify the char at which it points.
(from const char * const versus const char *?)
Now, my question is: Let's say I'm writing a function that would not modify the C string that is passed to it, for example:
int countA(??? string) {
int count = 0;
int i;
for (i=0; i<strlen(string); i++) {
if (string[i] == 'A') count++;
}
return count;
}
Now, what should the header be?
int countA(char const * string);
int countA(char const * const string);
My feeling is that I should use the second one, because I'm not going to modify the pointer itself, neither the contents of the array. But when I look to the header of standard functions they use the first one. Example
char * strcpy ( char * destination, const char * source );
Why?
(In fact char const *
doesn't really make sense to me, because if you're thinking about the abstract string, either you are not modifying the string (so, char const * const
because you are not modifying the pointer, neither the contents) or you will modify the string (so just char *
because, you may modify the contents and you may need to allocate more memory, so you may need to modify the pointer)
I hope someone can make all this clear to me. Thanks.