On 16 Jul 2003 18:52:18 -0700,
gu*********@verizon.net (Gus Tabares)
wrote:
Hello all,
I'm having a bit of trouble understanding a snippet of code in the
K&R book I'm reading. Basically it's something like this:
int ndigit[10];
for (i = 0; i < 10; i++)
ndigit[i] = 0;
int c;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
... The problem is with the last line here. Why is it that the
substraction is needed here? Why couldn't it just be ++ndigit[c]? I
may be missing something totally here.
The subtraction has the affect of converting the value in c which is
the character representation of a digit (in ASCII, '0' is 0x30 or 48)
to the numeric value of the digit. This is guaranteed to work because
the standard requires the representation of the 10 digits to be
sequential in the normal order.
Thus, if you type a two, c will be set to '2' and the statement in
question will increment the value of ndigit[2] by 1. Without the
subtraction, it would attempt to increment the value of ndigit[50] (or
ndigit[242] if your machine is EBCDIC) which doesn't exist.
<<Remove the del for email>>