How do you implement strtol
under const-correctness?
You don't, because strtol
's definition is inherently not const
-correct.
This is a flaw in the C standard library.
There are several standard functions that take a const char*
argument (expected to point the beginning of a character array) and give back a non-const
char*
pointer that can be used to modify that array.
strchr
is one example:
char *strchr(const char *s, int c);
For example:
#include <string.h>
int main(void) {
const char *s = "hello";
char *ptr = strchr(s, 'h');
*ptr = 'H';
}
This program has undefined behavior. On my system, it dies with a segmentation fault.
The problem doesn't occur in strchr
itself. It promises not to modify the string you pass to it, and it doesn't. But it returns a pointer that the caller can then use to modify it.
The ANSI C committee, back in the late 1980s, could have split each such function into two versions, one that acts on const
character arrays and another for non-const
arrays:
char *strchr(char *s, int c);
const char *strcchr(const char *s, int c);
But that would have broken existing pre-ANSI code, written before const
existed. This is the same reason C has not made string literals const
.
C++, which inherits most of C's standard library, deals with this by providing overloaded versions of some functions.
The bottom line is that you, as a C programmer, are responsible for not modifying objects you've defined as const
. In most cases, the language helps you enforce this, but not always.
As for how these functions manage to return a non-const
pointer to const
data, they probably just use a cast internally (not a const_cast
, which exists only in C++). That's assuming they're implemented in C, which is likely but not required.