Implementation of itoa() How can this solution be improved?

#include &lt;limits.h&gt;

void itoa(int n, char s[])
{
    int min_int = 0;
    int i, sign;
    if (INT_MIN == n) {
        min_int = 1;
        n++;
    }

    if ((sign = n) &lt; 0)
        n = -n;
    i = 0;
    do {
        s[i++] = n % 10 + '0';
    } while ((n /= 10) &gt; 0);

    if (sign &lt; 0)
        s[i++] = '-';

    s[i] = '\0';

    if (min_int)
        s[0]++;

    reverse(s);
}
I think I'd break this up into a few separate routines, each with a single more specific intent. I think the easiest way to do this is probably to start by taking the absolute value of the input (represented as an unsigned type), something like this:

unsigned iabs(int input) { 
    if (input &gt;= 0)
        return (unsigned)input;
    return (UINT_MAX - (unsigned)input)+1U;
}


I believe C's requirements for converting a signed to unsigned ensure that this produce correct results for all inputs (including INT_MIN).

With that, nearly everything else can deal with an unsigned number. Personally, I also prefer to generate the result in order instead of generating in reverse, then reversing it. One fairly simple way to do that is with recursion, with each step first generating previous numerals (if any), then adding its own numeral to the end of the string. I'd have the recursive function deal only with an unsigned type (as produced above). Of course, like nearly everything that manipulates data in a buffer in C, you should also pass the maximum buffer length for it to use, to prevent buffer overruns. For the sake of generality, I've also made it accept the base for the conversion as a parameter instead of always assuming base 10.

char *itoa_internal(char *buffer, size_t len, unsigned input, int base) { 
    static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char *pos = buffer;
    if (input &gt;= base)
        pos = itoa_internal(buffer, len, input/base, base);

    if (pos-buffer &lt; len-1)
        *pos++ = digits[input % base];
    return pos;
}


Then I'd have a small wrapper function that puts in a - if the input is negative, invokes the function above with the absolute value of the input, and terminates the string after the internal function returns.

char *itoa(char *buffer, size_t len, int input, int base) {
    char *pos = buffer;

    if (base &lt; 2 || base &gt; 36 || len &lt; 1)
        return NULL;

    if (input &lt; 0)
        *pos++ = '-';

    pos = itoa_internal(pos, len, iabs(input), base);
    *pos = '\0';
    return buffer;
}


This should also make it pretty trivial to write a utoa that handles unsigned inputs -- it would be like itoa without the code to deal with negative numbers. As a minor refinement, I'd probably also make iabs and itoa_internal static functions to minimize the chances of them interfering with other names.