I'm a python programmer getting to learn C from the K&R book. This will seem like an awfully trivial question, but I'm stumped nonetheless. Attached below is a snippet of code from the K&R (RIP Ritchie!) book which implements the atoi() function.
atoi(s) /*convert s to integer */
char s[];
{
int i, n, sign;
for (i=0; s[i]==' '||s[i] == '\n' || s[i] == '\t'; i++)
; /* skip whitespace */
sign = 1;
if (s[i] == '+' || s[i] = '-') /* sign */
sign = (s[i++] == '+') ? 1 : -1;
for (n=0; s[i] >= '0' && s[i] <= '9'; i++)
n = 10 * n + s[i] - '0';
return (sign * n);
}
My questions:
1) Does the first 'for' loop serve any purpose besides counting the number of valid characaters?
2) If (1) is true, the first loop sets the value of 'i' to the number of valid characters - how does the second for loop work without reseting i to 0?
Say for example I enter '2992' as an input to the function. The first for loop sets i to 3, so how does the rest of the function work? I may have my basics all messed up but any help would be really appreciated. Thanks, -Craig