Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!jarthur!mti!adrian From: adrian@mti.mti.com (Adrian McCarthy) Newsgroups: comp.lang.c Subject: Re: New 'n' Improved comp.lang.c FAQ List Message-ID: <1780@mti.mti.com> Date: 3 Apr 91 20:00:25 GMT References: <910401.0xf001@etiquette.uu.net> <1991Apr1.203024.19679@unlv.edu> <31946@shamash.cdc.com> Reply-To: adrian@mti.UUCP (Adrian McCarthy) Organization: Micro Technology, Anaheim, CA Lines: 50 In article <31946@shamash.cdc.com> bls@u02.svl.cdc.com (Brian Scearce) writes: >grover@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 #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@gonzo.mti.com)