Search code examples
cwhile-loopgetchar

What's wrong with my C character and line counting program?


I was reading Kernighan Ritchie and there's this Character counting program, so I tried implementing

#include <stdio.h>
#include <stdlib.h>

int main()
{
char c;
int i;
c = getchar();
while (c != EOF)
    i= i + 1;
printf("%d",i);
}`

When I compile and run this code, after I enter some characters there's no output after that. No number is printed and I can't figure out why. The code looks fine. I also tried using scanf() but the same thing happened.

The next example was for counting lines in input and the same problem was there too.


Solution

  • In your code, when you're hitting

     i= i + 1;
    

    the initial value of i is indeterminate. So, the whole program invokes undefined behavior. You need to initialize i.

    To elaborate, i being an automatic local variable, unless initialized explicitly, the content is indeterminate. Using an indeterminate value in this case will lead to UB.

    That said, a char is not able to hold a value of EOF, change the type to int.


    After that, you're wrong in the logic. getchar() is not a loop on it's own, you need to keep calling getchar() inside the while loop body to update the value of c, used in the condition check in while.