I’m trying to understand how this exactly works (I know what it does, I just don’t understand how).
As far as I know, this reads a char until EOF is reached, and if its a digit, put it in the array:
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
I understand I can index an array like this:
some_array[1] = 12;
which will put 12 in the second element.
What does the c-'0' do ?
(I got this from the book The C programming language 2nd edition from K&R)
‘0’ is a
charwhich has a decimal value of 48 when coerced to an integer. It works because char is a built-in ordinal type.If you look at the disassembly, you can see this in action:
Notice we’re comparing against 30 hex and 39 hex, not ‘0’ and ‘9’.