I was reading though this: const char * const versus const char *?
in string.h, strlen is defined as:
size_t strlen ( const char * str );
If I understand this correctly, strlen expects a pointer to a char that is const. Shouldn’t it be:
size_t strlen ( const char* const str );
This would make sure that strlen cannot modify the pointer to point to a different pointer ?
Or, is this the case:
Since str pointer will be passed by value to strlen, any changes to this pointer in the function will not change the source pointer, and hence it’s okay..
??
If you really read that discussion, you should understand that the second
consthas no effect on the external behavior of the function. For you, the user ofstrlen, It simply doesn’t make any difference whether it is declared withconst char *orconst char *constparameter. As you correctly noted, any modifications thatstrlenmight do to the pointer are only affecting the internal, local copy of the pointer insidestrlen. Your argument pointer that you pass tostrlenwill remain unchanged regardless of whether the parameter is declared with secondconstor not. (Your argument pointer doesn’t even have to be an lvalue.)The second
constwill only have effect on the internal behavior of the local parameter variable inside the function, preventing the authors ofstrlenfrom modifying that local variable. Whether they want to restrict themselves in that way or not is, informally speaking, their own business. It doesn’t concern the users ofstrlenin any way.In fact, since top-level
constqualifiers have no effect on function type, it is typically possible to declare a function withconst char *parameter and then define it withconst char *constparameter. The compiler (linker) will still treat these declarations as “matching”. It means that if the library authors so desired, they could actually definestrlenwithconst char *constparameter. They are simply not telling you about that, since this is effectively an implementation detail orstrlen, i.e. something you don’t need to know.