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
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
The character values of '0' to '9' are guaranteed to be sequential values in all character sets in C.
(C99, 5.1.2p3) "In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous."
It means for example that '1' == '0' + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With