1

I'm currently reading the K&R book. Page 22, Arrays 1.6

int c, i, nwhite, nother; int ndigit[10]; nwhite = nother = 0; for (i = 0; i <10; ++i) ndigit[i] = 0; while ((c = getchar()) != EOF) if(c >= '0' && c<= '9') ++ndigit[c-'0']; else if (c == ' ' || c == '\n' || c == '\t') ++nwhite; else ++nother; printf("digits ="); for(i = 0; i < 10; ++i) printf(" %d", ndigit[i]); printf(", white space = %d, other = %d\n", nwhite, nother); 

It says chars are considered integers. I tried removing the '0' in the first if satement. However, the array stopped working. If chars are considered to be integers, why is the '0' required for the program to function properly

6
  • 1
    0 is not '0' Commented May 16, 2017 at 14:50
  • c-'0' is the short-hand way to get the digit from the ASCII digit. Since '0' is the lowest ASCII value, and digits are continuous in the ASCII encoding, subtracting '0' from a digit character gives you its value. Commented May 16, 2017 at 14:53
  • 1
    The character '0' (zero) has ASCII value 48 and is different from the NUL character '\0' which does have the numerical value 0. NB: C isn't bound to the ASCII standard but if you're using a computer that isn't someone should have told you. Commented May 16, 2017 at 14:59
  • @DanAllen he subtracted '0' so that chars taken in as input actually represent the numbers they display. Commented May 16, 2017 at 15:19
  • @AppWriter But isn't that the point? Grayson doesn't know why this code (which presumably isn't theirs) needs to subtract '0' from something and thinks it's doing nothing because they think '0' is zero. Commented May 16, 2017 at 15:30

1 Answer 1

0

Chars are numbers but '0' is not 0, but (in most cases) 48, '1' is not 1 but (in most cases) 49, and so on.

Here is the detailed explanation of it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.