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: Lambda A. Calculus 2012-09-11 22:09

>>2
The code c - '0' is equivalent to c - 48.

AAAAAAAAAAAAAAAAAAAAAAAAA

AIN'T RED DA STANDARD

AIN'T HERD OF EBCDIC

AIN'T KNOWIN' C

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