# Problems interpreting simple syntax construct and explanation from K&R

This is a discussion on Problems interpreting simple syntax construct and explanation from K&R within the C Programming forums, part of the General Programming Boards category; This is excerpted from K&R pages. 42-43 The explanation reads that this function coverts a string of digits into its ...

1. ## Problems interpreting simple syntax construct and explanation from K&R

This is excerpted from K&R pages. 42-43

The explanation reads that this function coverts a string of digits into its numeric equivalent.

Do they explicitly mean numbers by saying digits? If so, what does it's numeric equivalent mean if digits are already numbers?

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

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

return n;

}```
I'm having problems understanding what is happening here:

Code:
`(s[i] - '0');`
It says that this gives the numeric value of the character stored in s[i], because the values of '0', '1', etc, form a contiguous increasing sequence.

I really don't understand that construct or what this is saying.

Help would be greatly appreciated.

2. Well if you have a character, say '5'

Then '5' - '0' will give you the numeric value 5

3. What is the point of including - '0', if I'm just looking for the value of whatever is stored in s[i]?

4. Originally Posted by billybob2020
What is the point of including - '0', if I'm just looking for the value of whatever is stored in s[i]?
Ah, but you are not "looking for the value of whatever is stored in s[i]". Suppose '2' is stored in s[i]. Then the value of s[i], assuming ASCII, is 50. However, what you want is 2, not 50, so you subtract '0', which in ASCII has a value of 48. Even if you are not dealing with ASCII, it is guaranteed that the digits will be in order in the character set, as a contiguous sequence, so this method will always work.

5. > What is the point of including - '0'
Hey, you can try it without the -'0' if you want, and see if the code still functions as atoi() as most people understand it.

Go on, try it, see what happens.

6. Woah. I was really confused. I didn't realize that '0' was an ASCII character that had an internal value, so it read as just zero to me. Laser cleared that up for me.

Thanks to all of you guys though, and the speedy replies.

7. Originally Posted by billybob2020
Woah. I was really confused. I didn't realize that '0' was an ASCII character that had an internal value, so it read as just zero to me. Laser cleared that up for me.

Thanks to all of you guys though, and the speedy replies.
Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion