I’m learning the C language.
My question is:
Why is the param of strlen a “const” ?
size_t strlen(const char * string);
I’m thinking it’s because string is an address so it doesn’t change after initialization. If this is right, does that mean every time you build a function using a pointer as a param, it should be set to a constant ?
Like if I decide to build a function that sets an int variable to its double, should it be defined as:
void timesTwo(const int *num)
{
*num *= 2;
}
or
void timesTwo(int *num)
{
*num *= 2;
}
Or does it make no difference at all ?
C string is a pointer to a zero-terminated sequence of characters.
constin front ofchar *indicates to the compiler and to the programmer calling the function thatstrlenis not going to modify the data pointed to by thestringpointer.This point is easier to understand when you look at
strcpy:its second argument is
const, but its first argument is not. This tells the programmer that the data pointed to by the first pointer may be modified by the function, while the data pointed to by the second pointer will remain constant upon return fromstrcpy.