Search code examples
cnullcharactercharactercount

C - How do I make this null statement work?


I am following "The C Programming Language. 2nd Edition", and have got up to "1.5.2 Character Counting".

The code provided for a character counter that uses a null statement is this:

#include <stdio.h>

main() {
    double nc;
    for(nc = 0; getchar() != EOF; ++nc)
        ;
    printf("%.0f\n", nc);
}

Yet the program does not output the number of characters of the input:

input
input

Whereas if I included curly brackets and ignored the null statement:

#include <stdio.h>

main() {
    double nc;
    for (nc = 0; getchar() != EOF; ++nc) {
        printf("%.0f\n", nc);
    }
}

...it provides the correct output:

input
0
1
2
3
4
5
input
6
7
8
9
10
11

How do I make the null statement version of the program work?


Solution

  • You have plenty of issues in your code, but none of them is related to the empty statement:

    1. main type and arguments are wrong
    2. Pressing ENTER does not close the stdin and function will not return EOF.

    Check for EOF and new line.

    int main(void) {
        int nc,ch;
        for(nc = 0; (ch = getchar()) != EOF && ch != '\n'; ++nc)
            ;
        printf("%d\n", nc);
    }
    

    https://godbolt.org/z/Yc1c3K