Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C character values arithmetic

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

like image 588
hakuna matata Avatar asked Jun 04 '26 08:06

hakuna matata


2 Answers

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

like image 56
Ant's Avatar answered Jun 06 '26 23:06

Ant's


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

like image 34
ouah Avatar answered Jun 06 '26 23:06

ouah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!