Ben said:
Over the last couple of years, and especially recently, I've
built up a few "stock" answers that supplement the C FAQ. If
anyone wants to review and comment on them, I've just now put
them up on my webpage, at
http://benpfaff.org/writings/clc
In "Why should toupper()'s argument be cast to unsigned
char?" the second (?) bulleted exception appears garbled:
. But these implementations are invariably free-
standing, meaning that they don't implement the
character handling functions anyway.)
In "How should malloc()'s return value be used?" the
second argument against casting is beginning to lose its
force. As of C99, the cast cannot mask the error.
In "How should sizeof be used in malloc()'s argument?"
the second reason given isn't quite right. It's not "the
sizeof syntax" that is self-evidently correct (the compiler,
after all, will complain loudly about syntax errors), but
the agreement between the type pointed to and the type of
sizeof's operand.
In "How can I shuffle the contents of an array?" I'm
not sure why shuffle() uses `j = i + rand() % (n - i)'
instead of the apparently simpler `j = rand() % (i + 1)'.
The important thing, of course, is *not* to use the still
simpler but biased `j = rand() % n'.
Also, the discussion might be improved (or might not;
de gustibus) by making two additional points:
- `rand() % N' is not an especially good idiom for
a random integer in [0,N). The FAQ suggests one
alternative; rejection is another.
- For the particular case of shuffling a simulated
deck of 52 playing cards, note that rand() can
deliver no more than UINT_MAX distinct sequences.
UINT_MAX is about 4e9 on most implementations but
52 factorial is about 8e67, so the vast majority
of shuffled decks are unattainable. (A 226-bit
or wider `unsigned' would overcome this problem.)