why doesn't strlen (..) expect const char* const str instead of const char*

c++, string

Solution

If you really read that discussion, you should understand that the second `const` has no effect on the external behavior of the function. For you, the user of `strlen`, It simply doesn't make any difference whether it is declared with `const char *` or `const char *const` parameter. As you correctly noted, any modifications that `strlen` might do to the pointer are only affecting the internal, local copy of the pointer inside `strlen`. Your argument pointer that you pass to `strlen` will remain unchanged regardless of whether the parameter is declared with second `const` or not. (Your argument pointer doesn't even have to be an lvalue.)

The second `const` will only have effect on the internal behavior of the local parameter variable inside the function, preventing the authors of `strlen` from 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 of `strlen` in any way.

In fact, since top-level `const` qualifiers have no effect on function type, it is typically possible to declare a function with `const char *` parameter and then define it with `const char *const` parameter. The compiler (linker) will still treat these declarations as "matching". It means that if the library authors so desired, they could actually define `strlen` with `const char *const` parameter. They are simply not telling you about that, since this is effectively an implementation detail or `strlen`, i.e. something you don't need to know.

Problem

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.. ??

Original source

Related problems