Matt said:
I have 2 questions:
1. strlen returns an unsigned (size_t) quantity. Why is an unsigned
value more approprate than a signed value? Why is unsighned value less
appropriate?
You have a very good point here.
The obvious but simplistic reason is that negative string lengths are
meaningless. But then wouldn't it make sense for strlen(NULL) to be -1 ?
With the current C spec, it is undefined behaviour, and most implementations
will crash...
The decent but somewhat optimistic explanation is that it allows for strings
to be as large as the largest object (size_t). But I have seen
implementations where the largest objects were larger than size_t could
handle, and strings were still limited to 64KB.
On a 32 bit system, defining strlen as returning an int would make it
inconsistent with C99 but would prevent signed/unsigned clashes resulting in
hard to find bugs such as this one:
int n = -1;
const char *str = "Hello, world\n";
if (strlen(str) > n) {
// why does this test fail?
printf("OK\n");
}
2. Would there be any advantage in having strcat and strcpy return a
pointer to the "end" of the destination string rather than returning a
pointer to its beginning?
For some uses, it would be advantageous for strcpy or strcat to return a
pointer to the end of the string, or the length of the string, or nothing at
all. People can define their own alternatives and some are quite common
albeit not standard. The C string functions were defined a LONG time ago,
changing the semantics is impossible without breaking millions of lines of
existing code.
Chqrlie
PS: talking about string functions, I strongly advise against any use of
strncpy and strncat, whose semantics are IMHO quite broken and *very* error
prone.