spaces(n) macro
ebh at hou4b.UUCP
ebh at hou4b.UUCP
Thu Sep 13 00:30:59 AEST 1984
[send me mail if you don't see this line]
from Waiming Mok:
#define spaces(n) do {int i=(n);while (i--) putchar(' ');}while (0)
You don't need the do .. while construct, just make a compound
statement:
#define spaces(n) {int i=(n);while(i--) putchar(' ');}
Remember, anywhere <statement> can go, {<decl-list>; <statement> ...}
can go. One problem can crop up: what if i is used elsewhere in the
code? Imagine what spaces(i) would do. Therefore, it's wise to use
some name that you never use in regular coding, like _. Also, make _ a
register variable to avoid the overhead of allocating more stack space,
and for the obvious speed and space advantages. Thus the final version
looks like this:
#define spaces(n) {int _=(n);while(_--) putchar(' ');}
And yes, things like spaces(foo*2) do work.
-Ed Horch {houxm,ihnp4,akgua}!hou4b!ebh
p.s. On systems that support it,
#define spaces(n) printf("%*s", (n), "");
works just as well.
More information about the Comp.lang.c
mailing list