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

• 05-16-2011
cb0ardpr0gr^mm3r
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.
• 05-16-2011
Salem
Well if you have a character, say '5'

Then '5' - '0' will give you the numeric value 5
• 05-16-2011
cb0ardpr0gr^mm3r
What is the point of including - '0', if I'm just looking for the value of whatever is stored in s[i]?
• 05-16-2011
laserlight
Quote:

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.
• 05-16-2011
Salem
> 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.
• 05-16-2011
cb0ardpr0gr^mm3r
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.
• 05-16-2011
CommonTater
Quote:

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