Phil Dreizen

some very clever code to print an integer

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)).

Comments:

kupad

June 6, 2013, 10:56 pm

For all those times you can use putchar but can't use printf!