JohnF <> writes:
> Anything wrong with that, i.e., with #define BYTES *8
> to multiply by 8? It looked a little weird to me, but
> the more obvious #define BYTES(x) ((x)*
isn't what
> I wanted to write. This was to express units of measurement,
> e.g., int bits = so_many BYTES; rather than
> int bits=BYTES(so_many); . I just wanted to read and write
> it the first way, and my test program
> #define BYTES *8
> #include <stdio.h>
> int main ( int argc, char *argv[] ) {
> int bytes=(argc<2?1:atoi(argv[1])),
> bits = bytes BYTES;
> printf("%d bytes = %d bits\n",bytes,bits);
> return(0); }
> works fine (and compiles with no -pedantic warnings).
> But that #define BYTES *8 still looks a little funky to me.
> I realize 2+2 BYTES must be written (2+2)BYTES, but is there
> any other kind of "gotcha"?
I'd say it violates the principle of least surprise. Seeing an
identifer used that way, effectively as a postfix unary operator, is
confusing; it's very difficult to understand unless you examine the
definition of the macro.
Most macros can be understood, in terms of their meaning if not their
implementation, by looking at their names and arguments.
Something similar: Years ago, I thought that this:
#define EVER (;
was clever, because I could write:
for EVER {
/* ... */
}
I still think it's clever. I just no longer think that's a good thing.
And as Mark Bluemel indicates, the name doesn't convey the meaning well.
It says that you're working with bytes somehow, but it doesn't imply
anything about a conversion to bits.
If you want to compute the number of bits in a given number of bytes,
and you're using the word "byte" as it's defined by the C standard, then
you need to multiply by CHAR_BIT, defined in <limits.h>:
bits = bytes * CHAR_BIT;
That's clear enough that no additional macro is needed.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Will write code for food.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"