Search code examples
catoi

How does atoi() actually work


This is the Code :

#include <ctype.h>

/* atoi:  convert s to integer; version 2 */
int atoi(char s[])
{
int i, n, sign;

for (i = 0; isspace(s[i]); i++)  /* skip white space */
    ;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')  /* skip sign */
    i++;
for (n = 0; isdigit(s[i]); i++)
    n = 10 * n + (s[i] - '0');
return sign * n;
}

Q1) The first line of code counts white space? That means it counts spaces, enter, return etc? Say my string starts after two spaces is it? And after counting white spaces i value has been incremented?

Q2) the next sign line calculates if string is like -234? or 234?

Q3) next line if it has + or - sign count them in i which has already been incremented by calculated white spaces? is it?

Q4) next line calculates the number in the string say 234. n= 10*n+ ('2'-'0') => i get 2 => n= 10*2 + ('3'-'0') => i get 23 and at last i get number 234

and in the last line multiply 234 with -1 or +1 whatever the answer is*

Do I understand this code correctly?


Solution

  • A1) No, it counts only white spaces in the beginning of line (white spaces in standard isspace() implementation are ' ', '\t', '\n', '\v', '\f', '\r'; i.e. space, tabs, newline, feed and carriage return).

    A2) Yes, it determines sign of value.

    A3) If value is "234" it will not increment i. But if value is "+234" or "-234" we need to increment i (to recognize digits after it).

    A4) Yes. But not '24' (it looks like misprint; there must be '23').