Search code examples
ckernighan-and-ritchie

Difference between assigning a int to getchar() and using getchar() without it


while doing a exercise in K&R book(The C programming language 2nd edition) i ran into a problem i do not seem to grasp and understand. Namely the exercise was to write a program that counts spaces,tabs and new lines(at the very beginning of the book). I am writing in debian/gedit(dunno if this is relevant).

The code that i wrote is:

#include <stdio.h>

int main(void)

{

int nb = 0;         
int nt = 0;         
int nl = 0;         

while(getchar() != EOF)

    {
    if(getchar() == ' ')
        ++nb;
    if(getchar() == '\t')
        ++nt;
    if(getchar() == '\n') 
        ++nl;
    }
printf("%d\n%d\n%d\n", nb, nt, nl);

return 0;
}

Now when i execute the program it does not count spaces or tabs and in general does not behave as intended.

Than i checked for the correct answer in the books and i saw that they have and int c assigned to getchar() namely

while((c = getchar()) != EOF)
    if(c == ' ')
     ++nb;

and so on.

Now what i don't understand is why is it important to assign a int in this case c to getchar() and than use it in IF brackets. Should the way i wrote it not work the same?

Now as i understand int c is not a definite value or an exact value so to me as a beginner it all seamed as the only purpose of assigning it is so we do not have to write getchar() every time and can simply write c.

Also is there a specific desired condition where you should or should not assign a int to getchar()?

Executing the code as they wrote it gives the expected result but to be honest i don't seem to understand what is really happening here.

Any kind of help is appreciated, and thanks in advance.


Solution

  • Now what i don't understand is why is it important to assign a int in this case c to getchar() and than use it in IF brackets.

    It is indeed important to assign c to getchar.

    while((c = getchar()) != EOF)
    

    what it actually does is three steps:

    • getchar() get a character from standard input stream (stdin).
    • The character read is then assign to c.
    • Then c is compared to EOF.

    Should the way i wrote it not work the same?

    while(getchar() != EOF)
    
        {
        if(getchar() == ' ')
            ++nb;
    

    No. Your code does not have expected behaviour because you call getchar several times inside your while loop. What your code actually does is:

    • Read the first char from standard input stdin.
    • Compare that first char to EOF.
    • Then if it's NOT EOF, read a second char from stdin.
    • Compare the second char to ' '.
    • And so on.

    You can see why it's not expected behaviour because what you need is to read a single char and compare to all values.