B
BartC
Malcolm McLean said:And you very rarely want to call strchr with an explicit string literal,
but
you quite often want to parse a string literal passed from above.
The poor rules for string literals are seldom much of a practical problem,
because if in a real program a function modifies a string passed to it,
the
caller is going to want to examine the result. So he can't pass a string
literal.
const rules mean that you have to have two versions of strchr, which isn't
too bad. But they also mean that anyone writing a strchr-like function to
parse a string needs to write two versions. That's unacceptable.
In general, you need one function taking const char*, as that will accept,
without errors, either char* or const char* arguments.
The problem in this example, is when you return the same input string, or a
slice of it, then you want the output type to match that of the argument:
either const char* or char*. That's tricky to do with just the one function
and its one return type.
This is a more general problem with 'const': it can quickly turn into a
nuisance, if you strive to do the right thing everywhere, and possibly
distract you from other things. Perhaps better to just accept that you are
programming in C, after all, where you need to live a little more
dangerously.)
It doesn't help that as C implements it (a necessity, given its fairly low
level and its role in implementing everything else), any type (parameter
type etc) can be arbitrary complex and 'const's can appear anywhere in the
type structure: const/non-const pointers to arrays of const/non-const
elements, or to structs of a mix of const/non-const elements including
const/non-const pointers to other const/non-const structs and arrays...
Even if a compiler can untangle it all, frequently a human can't!