Trouble with curses
Mark W. Schumann
catfood at NCoast.ORG
Tue Oct 30 01:40:20 AEST 1990
In article <1990Oct27.173826.29771 at NCoast.ORG> ramsey at NCoast.ORG
(Connie using Cedric Ramsey's account) writes:
>Hi, this is Connie. I'm accessing this net with a friends account.
... and welcome. Too bad about the Browns the other day, huh?
>I have a question about the curses package. Heres the skeletal code:
> [Much deleted for brevity]
>do_escape() {
> switch(tolower(getch())) {
> case 'e':
> do_exit();
> break;
> [ ... irrelevant stuff deleted ... ]
> }
>Basically what is happening is the the user presses ESCAPE key follow by
>'E' key to exit. But I have to press 'E' twice after pressing ESCAPE
>to get an exit. I can't figure out why. Does anybody know ?
Betcha your tolower is implemented as a macro, something like this:
#define tolower(c) (isupper (c) ? c + 'a' - 'A' : c)
(Portability purists will quibble with this, but what the hey it works
in DOS. My point is this:) Notice that there is no way for this macro
to help but evaluate the argument 'c' twice. The code generated in your
case would be:
do_escape() {
switch (isupper (getch()) ? getch() + 'a' - 'A' : getch()) {
case 'e':
....dah dah dah...
}
So your object code evaluates isupper(getch()) [gets a keystroke here],
then depending on the result it evaluates getch() + 'a' - 'A' OR
plain getch() [gets *a new* keystroke here in either case].
Your problem is the usual macro yuckies--expanding code inline causes
this type of re-evaluation. Try this instead:
do_escape() {
int c;
c = getch();
switch (tolower (c)) {
.........
}
}
The variable 'c' of course gets evaluated only once as 'getch().' THEN
you process its value without risking the side effects.
Alternative:
do_escape() {
switch (getch()) {
case 'e':
case 'E':
do_exit(); /* K & R says be careful, but it works */
break;
......
Hope this helps and that I wasn't over-explaining.
--
============================================================
Mark W. Schumann 3111 Mapledale Avenue, Cleveland 44109 USA
Domain: catfood at ncoast.org
UUCP: ...!mailrus!usenet.ins.cwru.edu!ncoast!catfood
============================================================
More information about the Comp.lang.c
mailing list