Search code examples
cgetchar

Behaviour of getchar() in a while loop


I am running this c program in the terminal

#include <stdio.h>

int main() {
    int result = 0;

    while(result <= 0) 
    {
        int result = (getchar() != EOF);
        result = 2;
        printf("x");        
    }

    printf("out\n");
}

After that I type in the word "hello" followed by a return. The result is that I get multiple 'x' characters.

Why doesn't this terminate after the first 'x'?


Solution

  • You're re-declaring (shadowing result) inside the while loop. The result that is used in while(result <= 0) is the one that is declared outside the loop.