Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!sdd.hp.com!spool.mu.edu!snorkelwacker.mit.edu!bloom-picayune.mit.edu!news From: scs@adam.mit.edu (Steve Summit) Newsgroups: comp.lang.c Subject: Re: New 'n' Improved comp.lang.c FAQ List Message-ID: <1991Apr5.020223.25656@athena.mit.edu> Date: 5 Apr 91 02:02:23 GMT Article-I.D.: athena.1991Apr5.020223.25656 References: <1991Apr1.203024.19679@unlv.edu> <31946@shamash.cdc.com> <1780@mti.mti.com> Sender: news@athena.mit.edu (News system) Reply-To: scs@adam.mit.edu Organization: Thermal Technologies, Cambridge, MA Lines: 44 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@mti.mti.com> adrian@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@adam.mit.edu