New 'n' Improved comp.lang.c FAQ List

Steve Summit scs at adam.mit.edu
Fri Apr 5 12:02:23 AEST 1991


I've been trying (well, actually, that's not *strictly* true :-) )
to stay out of this, but I'll mention a couple of things.

First of all, as should by now be obvious, if you haven't found
at least *five* reasons why

	char retbuf[5];		/* biggest int: 32769 */

is wrong, think some more, or read all the followups which have
been posted so far, and take the union.

In article <1780 at mti.mti.com> adrian at mti.UUCP (Adrian McCarthy)
touches on the least-observed problem by writing:
>If you want to make the code disgustingly portable (and assume an ANSI
>compiler), you can drop the assumption about the size of the largest int
>by using limits.h, sizeof, and a preprocessor trick (see below).

I wouldn't disparage this level of portability at all.  There's
no reason to assume that ints are 16 bits.  (If you want to
assume that a type is 16 bits, you can make your intentions
clearer by declaring it as a short.)

Some increasingly outlandish "solutions" to the problem of sizing
an int-to-ascii return buffer are being offered.  The variations
on sizeof(INT_MAX) are imaginative (and new to me), but, as Karl
has noted, they can't work, and they're too convoluted, anyway.
The explicit run-time log10() calculation, while on the right
track, is unnecessarily baroque.  Much the same thing can be
accomplished quite cleanly (he says) with

	static char retbuf[sizeof(int) * CHAR_BIT / 3 + 1 + 1 + 1];
					/* +1 for /3 truncation */
					/* +1 for leading - */
					/* +1 for trailing \0 */

This gives you a buffer big enough for a base-8 conversion, which
is marginally bigger than you need for a base-10 conversion.

(Side note: when sizing buffers like this, I usually *don't* fold
all the +1 fudge factors together, preferring to leave them
explicit and separately explained, as shown.)

                                            Steve Summit
                                            scs at adam.mit.edu



More information about the Comp.lang.c mailing list