Reputation: 47
I'm learning C from The C Programming Language, Second Edition. In it, there is the following code:
#include <stdio.h>
/* count digits, white space, others */
main() {
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);
}
Now, I can understand what this code is doing. It is counting how many times each digit appears in the input, and then putting that count into the index of the digit, ie 11123 = 0 3 1 1 0 0 0 0. I'm just curious about 1 line of it:
++ndigit[c-'0'];
This adds 1 to the index c of the array, but why does it subtract 0 from c? Surely that's pointless, right?
Upvotes: 1
Views: 1139
Reputation: 754715
The expression c - '0'
is converting from the character representation of a number to the actual integer value of the same digit. For example it converts the char '1'
to the int 1
I think it makes a bit more sense to look at complete examples here
int charToInt(char c) {
return c - '0';
}
charToInt('4') // returns 4
charToInt('9') // returns 9
Upvotes: 3
Reputation: 180788
It's not subtracting zero... It's subtracting the ASCII value of the character '0'.
Doing so gives you an ordinal value for the digit, rather than its ASCII representation. In other words, it converts the characters '0' through '9' to the numbers 0 through 9, respectively.
Upvotes: 1