Phil Dreizen

some very clever code to print an integer
June 6, 2013, 8:56 pm

While reading Microprocessors: A Programmers View, a very old book on different computer architectures, I came across this really clever bit of code for printing out an integer to ascii:

void itoa(unsigned int i){
    if(i >= 10) itoa(i/10);
    putchar('0' + i%10);
}

(I modified the name of the function, and the style of the parameters)

It's just a really nice example of recursion. (Of course, it appeared in an example about how SPARC's "register window" method of doing procedure calls would potentially perform poorly in code like this (this was in 1990)).