type conversion C, atoi()

In the book "The C programming language"; second edition, chapter 2.7 there is a snippet which is supposed to:
"convert a string of digits into its numeric equivalent".

int atoi(char s[])
{
    int i, n;

    n = 0;

    for ( i = 0; s >= '0' && s <= '9'; ++i)
        n = 10 * n + (s - '0')

    return n;
}

What is the purpose to run

10 * n

if n is 0 ?

thanks

Simplifies the code. If not done this way, you would have to have extra code to handle the n = 0 case.

1 Like

Ok, thanks. What i don't understand: Is there a difference between

0  * 0 
 1 * 0 
... 
10 * 0 

in C ? Different: is the 10 arbitrary, or is it chosen for a reason?

Hi friend,

   The code is not only for n=0, its in a for loop. Let me explain with an example.

If s contain a string "5270", then the loop continue for 4 times:

1st : 100 + 5 = 5
2nd : 10
5 + 2 = 52
3rd : 1052 + 7 = 527
4th : 10
527 + 0 = 5270
which is the n value and a number instead of string.

Try to use some debugging tools and check the variables, u will understand it clearly...

1 Like

Thanks to both of you, i understand it much better now (now fully, but i am on my way). Yes, siva shankar, what you just explained is exactly what i did not see.