When Timothy stumbled across a function that had a vague name, no comments, and variables, he took a few minutes to try to break it down in his head.

static char *nice_num(long n)
    int neg = 0, d = 3;
    char *buffer = prtbuf;
    int bufsize = 20;

    if (n < 0)
        neg = 1;
        n = -n;
    buffer += bufsize;
    *--buffer = '\0';

        *--buffer = '0' + (n % 10);
        n /= 10;
        if (--d == 0)
            d = 3;
            *--buffer = ',';
    while (n);

    if (*buffer == ',') ++buffer;
    if (neg) *--buffer = '-';
    return buffer;

Got that? Yeah, it takes a few minutes to figure out. The function that this, er, function is trying to accomplish is to add commas at the thousands, millions, etc. places.

It works backwards, starting with the string terminator, then setting the one, ten, hundred, etc. digits using goofy modulus math. The function divides by ten with each iteration (rather than 1,000 for some reason), stopping at every third to stick a comma in. And if it was negative to begin with, it mashes a minus sign back on to the string before returning it.

Personally, I would've called the function "nice_num,horrible_implementation", but I'm pretty sure commas aren't legal in C++ function names.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!