Recursive atoi

One site I visit often is the , a web site discussing really bad programming (as seen in real everyday life). Today’s thread is about a bad implementation of the string to interger function atoi. A friend of mine dared me to do a recursive implementation of atoi. Doing this would be very stupid and innefficient, so it is really an exercice in futility. Of course I could not resist. So here it is, this is not nice code, simply something I whipped out to show it is possible.

long ratoi(const char* string) {
    if (NULL!=string) {
	const char c = *string ; 
	const char *tail = ++string ; 
	if ('-' == c) {
	    return -1 * ratoi(tail) ; 
	} else if (('+' == c) || isspace(c)) {
	    return ratoi(tail); 
	} else if (isdigit(c)) {
	    long value = c - '0' ; 
	    if (isdigit(*(tail))) { // rest of string is number 
		const long recurse = ratoi(tail) ; 
		const int digits = (int) log10((double) recurse) ; 
		// we shift to match the tail's result
		for(int i=0;i<digits+1;i++) {  
		    value*=10 ; 
		} // for 
		return value + recurse ; 
	    } else { 
		return value ; 
	} // isdigit
    } // not null 
    return 0 ; 
} // ratoi

3 thoughts on “Recursive atoi”

  1. Il me semble que ce code accepte qqch du genre de “–+ +—+-1”. Bon, c’est vrai que ça fait la reduction de signe, mais les espaces au milieu, pas top.
    Enfin c’est juste pour faire mon chieur, mais faut dire qu’après avoir lu 10 pages sur DailyWTF, c’est presque une réaction normale ;-)

  2. On peut corriger ça en ajoutant un isdigit avant l’appel récursif, mais bon…

  3. You may say this is an exercise in futility, but in reality, this is remarkably elegant. With proper tail-call optimization, this code would be very nearly as efficient as an imperative solution.

    I never would have thought to use log10() to determine the number of digits in the result; I would have attempted to do strlen(tail) instead. However, that would have been buggy, as that would work only if tail didn’t include bad characters after the last legal digit.

    Hmm…I shall have to try my hand at writing a recursive atoi function now. :)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: