Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

++ndigit[c - '0'];

Name: Anonymous 2012-09-11 14:05

So, I'm workin on the book "The C Programming Language" when this code comes up under the chapter for character arrays:


#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);
        getchar();
}


It all makes sense, expect for the "++ndigit[c - '0'];" in line 14. I don't understand what this is doing, or why it has to do it. Shouldn't the program run the same if you didn't add the " - '0'" part? But when I take out that part, the program will compile, but it will return all '0' for every number, even if they are present.

So what exactly does subtracting '0' do for this program?

Name: Anonymous 2012-09-11 14:38

'0' does not refer to a numerical 0, but the value of the ASCII character '0', which has a decimal value of 48. Since characters and integers are more or less interchangeable (this is a simplification) in C, when you subtract a character from an integer, the character is converted to an integer. The code c - '0' is equivalent to c - 48.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List