Strange behavior with function parameters and getc

2019-08-04 00:39发布

I am running in to some strange behavior with calling functions with parameters that contain getch().

Take the following code for example:

_Bool IsKeyDown(char c)
{
    if(!kbhit())
        return 0;
    char ch1 = getch();

    printf("%c\n", c);

    return 0;
}

/*
 * 
 */
int main(int argc, char** argv) {
    while(1)
    {
        IsKeyDown('a');
        IsKeyDown('b');
        Sleep(100);
    }
    return (EXIT_SUCCESS);
}

When a key is pressed with this code, no matter what, it will always print 'a', which is the parameter of the first function. The issue is, 'a' is not the parameter of the second function being called, yet 'a' is still printed instead of 'b'. Why is this occuring?

1条回答
家丑人穷心不美
2楼-- · 2019-08-04 00:57

Think about it: what is your program doing? You hit a character on the keyboard. When main finishes sleeping, it calls the function with 'a'. Since kbhit is true, it will print 'a'. Then, immediately, it calls IsKeyDown() again. Since kbhit is now false, it returns without printing anything. Then main sleeps again, and it starts over.

To test this, change IsKeyDown to return 1 if it gets a character. Then in main, test the return value to see what is happening.

查看更多
登录 后发表回答