theo_vvv
theo_vvv

Reputation: 43

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'?

Upvotes: 2

Views: 65

Answers (2)

Luis Colorado
Luis Colorado

Reputation: 12645

Well,

#include <stdio.h>

int main() {
    int result = 0;  /* here *OUTER* result gets the value 0 */

    while(result <= 0) /* THIS MAKES THE While to execute forever */
    {
        int result = (getchar() != EOF);  /* THIS VARIABLE IS ***NOT*** THE outside result variable */
        result = 2; /* external block result is not visible here so this assign goes to the above inner result */
        printf("x");        
        /* INNER result CEASES TO EXIST HERE */
    }

    printf("out\n");
}

As you can deduct from the comments, the result variable that is compared in the while test is the outer one, while the inner one hides the outer one, no assignations can be made to it in the body of the loop, so the loop runs forever. You get an infinite string of xs printed on stdout.

Upvotes: 0

Kon
Kon

Reputation: 4099

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.

Upvotes: 5

Related Questions