One way could involve passing the length of the digit as an argument so we can read backwards efficiently:
int strtoi(char *c, size_t l)
{
return l ? c[l-1] - '0' + 10 * strtoi(c, l - 1) : 0;
}
Then call it like this:
int i = strtoi("432", 3);
Or:
char *c = "432";
int i = strtoi(c, strlen(c));
But it's not always optimal to bother with the length of a string. Plus, if a string has characters after a number, we'd have to factor that in manually, because this function won't do it for us. We can't (shouldn't) use strlen()
inside our function to avoid having to pass arguments, because that can cause a considerable slowdown to recalculate the string's length every time. Surely there must be a way to do this from the beginning, even if we have to bring out the heavy artillery:
int strtoi(char *c)
{
if(!isdigit(*c)) return 0;
int i = strtoi(c + 1);
return i + pow(10, (int)(log(i + 1)/log(10)) + (i != 0)) * (*c - '0');
}
And no, that (int)
cast isn't optional. Basically, all of that math calculates the power of 10 we need to multiply our current digit by, based on the number returned by the last recursive call.
I understand this is probably a learning exercise, but recursion is not the be-all, end-all of programming. In some languages, and for some tasks, it is what some, myself included, would call beautiful, but from the looks of it this is not one of those cases.