Search code examples
cgetchar

What does this not work for getchar() method?


This was my own experiment to understand what goes under the hood, what does this program mean to the compiler?

main()
{
  int c;
  printf("%d\n",c);
  printf("%d ", getchar());


  while ((c == getchar()) != EOF){
    putchar(c);
  }
}

When I say c must equal getchar() (c == getchar()), does it not proceed through the while loop? Now I am really confused of my own code, of what c must mean!

Also, in this code:

main()
{
int c;
c = getchar()
while ((c = getchar()) != EOF)
putchar(c);
}

if we modify the int c to int c = getchar(), why cannot we somply write like this:

while (c != EOF)(
    putchar(c);
    c = getchar();
    }

The compiler should know from the previous statement that c = getchar(), why have to write the statement again? Sorry, if I am confused.


Solution

  • while ((c==getchar()) != EOF) {
      ...
    }
    

    is a while loop. It evaluates the condition for each iteration of the loop and terminates only if the condition is false.

    In your case, the condition is:

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

    which is a nonsensical expression, but let's examine it anyway:

    First, the program will evaluate:

        getchar()
    

    This grabs a keystroke from standard input. The value of the expression is the value of the key.

    Then:

     c==getchar()
    

    This takes the result of getchar() and compares it to whatever is currently in c. In your first program, c is uninitialized, so its value is indeterminate. If c had a defined value, then c==getchar() would evaluate to either true or false. Since c had no defined value, c==getchar() also has no defined value.

    Now the program evaluates:

    (c==getchar())
    

    Which would still be true or false, except that in your case it is undefined.

    The program next considers:

    (c==getchar()) != EOF
    

    That is, it compares the true-false value to EOF; this makes no particular sense, and in your case we still have the undefined behavior of an uninitialized c.

    In sum, if c were initialized, the expression would fetch a key from standard input and then compare either true or false to EOF. As I said, it is a nonsensical expression.