New 'n' Improved comp.lang.c FAQ List
Adrian McCarthy
adrian at mti.mti.com
Thu Apr 4 06:00:25 AEST 1991
In article <31946 at shamash.cdc.com> bls at u02.svl.cdc.com (Brian Scearce) writes:
>grover at big-joe.cs.unlv.edu (Kevin Grover) writes:
>> Apparently non-obvious April Fool's Day bogus account posts:
>>...
>Almost, but not quite, Mr. Grover. The *really* correct version of this:
>
> char *itoa(int i)
> {
> static char retbuf[5]; /* biggest int: 32768 */
> sprintf(retbuf, "%d", i);
> return retbuf;
> }
I'm not sure if people are really trying to clear this up, or if they're
just trying to propagate the joke. At the risk of being a fool...
We still haven't got it. Since the biggest int may be five (5) characters,
retbuf should be at least size (6) characters long to hold the '\0'
character at the end. Then again, since this int isn't unsigned, you
really need another character to make sure you can hold the minus sign.
This is a common mistake.
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).
To keep lint quiet, you might want to explicity ignore the return value
of sprintf by placing "(void)" before it. If you are suspicious of your
C run-time library, check the return for reasonable ranges:
(r > 0) && (r < sizeof(retbuf))
(Remember that sprintf doesn't include the '\0' terminator in its return
value.)
#include <limits.h>
#define QUOTE(a) #a
char *itoa(int i)
{
static char retbuf[sizeof(QUOTE(INT_MIN))];
/*
* I *think* the above is a legitimate use of sizeof. Can
* any standard gurus confirm or deny this?
*/
(void) sprintf(retbuf, "%d", i);
return retbuf;
}
Aid. (adrian at gonzo.mti.com)
More information about the Comp.lang.c
mailing list