Pergunta

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 what I wanted to ask is why when I ask to return yesno(c) I have to press the button only once, while when I use return yesno(getch()) I have to press the button one two or three more times?

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

Foi útil?

Solução

because when you use

yesno(getch());

It expands to :

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

When the macro is expanded like this, it means that getch() could actually 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 your macro expands to by using the -E flag:

gcc -E myprog.c -o mprog.m

Outras dicas

C uses short-circuit evaluation. The expression you get from your macro:

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

gets a character, sees if it's equal to ENTER (which you've presumably defined as \n. If it is, the whole expression is going to end up true and so the function returns true without testing the other two cases. If not, though, the function then gets another character, tests whether that second character equals ' ', and returns true if it does. Only after testing all three cases on different characters, and getting false each time, is the whole expression known to be false.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top