Getch expects an extra character

Hello, I am new to programming and I am writing a program in C.

In my header file, I have this macro:

#define yesno(c) (c==ENTER || c==' ' || c=='\t') ? ENTER : ESC 

In my program, I have this code

 char keypressed() { char c; c =getch(); return yesno(getch()); } 

So I wanted to ask why, when I ask to return yesno(c) , I have to press the button only once, and when I use return yesno(getch()) , should I press the button one or two times more?

Is there a problem with getch() when called from a macro?

+4
source share
2 answers

because when you use

 yesno(getch()); 

It expands to:

 (getch()==ENTER || getch()==' ' || getch()=='\t') ? ENTER : ESC` 

When a macro expands, it means that getch() could be called 1, 2, or 3 times because the logical || means:

 getch() == '\n' ? if true return ENTER, false test next one getch() == ' ' ? if true return ENTER, false test next one getch() == '\t' ? if true return ENTER, false return ESC 

If you use the gcc compiler, you can find out what extends your macro using the -E flag:

 gcc -E myprog.c -o mprog.m 
+5
source

C uses a short circuit rating . The expression received from your macro:

 (getch()==ENTER || getch()==' ' || getch()=='\t') ? ENTER : ESC` 

receives the character, sees that it is equal to ENTER (which is supposedly defined as \n ). If so, the whole expression will end with true, and therefore the function returns true without checking the other two cases. If not, the function then receives another character, checks whether this second character is equal to, ' ' and returns true if it does. Only after testing all three cases on different characters and receiving false each time is this whole expression known as false.

0
source

Source: https://habr.com/ru/post/1446291/


All Articles