C character values arithmetic

hakuna matata picture hakuna matata · Apr 10, 2012 · Viewed 11.1k times · Source

I have been reading from the book "The C Programming Language" learning C, and I stumbled upon the arithmetic s[i] - '0' which they said that it gives the numeric value of the character stored in s[i]. I didn't quite understand it, how could it give the value by subtraction? Note This is used in the atoi function, which converts a string of digits into its numeric equivalent. Thanks

Answer

Ant's picture Ant's · Apr 10, 2012

Possible duplicate : See here

Well '0' represent 48 in character set. So subtracting it('0') with any other character value like this '1','2' will give respective number, so '9' - '0' will give you 9.

Note the difference we are sub both chars : '9' - '0', here both are char