1

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?

NAME__
  • 625
  • 1
  • 7
  • 17
  • Its not an answer, but questions: why are you storing a value in `ch` and then never using that value? Why do you make the return value of your function `_Bool` yet you always return the same thing. Why are you not making use of the return value in the caller? I would make sure the logic is solid before you ask this kind of detail question about the code. – Brandin Jan 17 '14 at 07:35
  • You probably meant to print 'ch1' rather than 'c'. – kusma Jan 17 '14 at 14:06

1 Answers1

0

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.

Chris J. Kiick
  • 1,487
  • 11
  • 14