Macro help
James Wilbur Lewis
jwl at ernie.Berkeley.EDU
Fri Mar 9 07:38:20 AEST 1990
In article <8284 at hubcap.clemson.edu> grimlok at hubcap.clemson.edu (Mike Percy) writes:
-Awhile back I saw some code which used a macro that had a do...while(0)
-loop in it. At the time I thought, hey that's a good idea, but now that I need
-to do something while could use this I'm stuck.
-
-Here's my situation:
-I am reading chars. When I hit '\n' I need to skip the first 6 chars on
-the next line ( anyone guess why?) and return the next char. Effectively this
-removing all "\nxxxxxx" from the stream.
-
-I tried this:
-
-#define input(ch) \
- ((ch) = getchar) != '\n' ? (ch) : \
- (do { int i = 5; while(i--) (void) getchar(); } while(0);), getchar()
-
-But this doesn't seem to work. Anyone that can help me out there?
How about this?
#define INPUT(ch) while ( ((ch) = getchar()) == '\n') \
{ \
int i; \
for(i=1; i <= 6; i++) (void) getchar(); \
}
(It compiles; I haven't tested it.) Your version has several problems:
the () is missing from the first call to getchar(), the final call to
getchar() doesn't assign anything to (ch), and worst of all, you are trying
to use a statement like do ... while within an expression, which is a
syntactic no-no.
(Do you always want to return the _next_ character after skipping? What
if it's another '\n'?)
I used an upper-case name to warn future maintainers that this is a macro
and not a function, so they won't be tempted to use an expression with
side effects like buf[i++] in place of ch, since the possibility of multiple
evaluation exists. (The fact that a character is being passed instead of
a char * _should_ tip them off if they're on the ball, but better safe
than sorry, right?)
-- Jim Lewis
U.C. Berkeley
More information about the Comp.lang.c
mailing list