ba******@gmail.com writes:
Is this a stupid hack or a clever hack?
Is it a "hack" at all?
====================
#include <stdio.h>
/* !!HACK!! */
/* no parenthesis on the #define'd expression */
#define MY_FLOAT_CONSTANT_HACKED 15 / 4
int main(void)
{
printf("The value is %d.\n", 100 * MY_FLOAT_CONSTANT_HACKED); /* !!
HACK!! */
return 0;
}
================
It's a stupid hack.
Is it so much better to do it the proper way, which implies a few type
conversions, implicit and explicit?
#define MY_CONSTANT 3.75
printf( "%d\n", (int)(100 * MY_CONSTANT) );
With your version of the macro, the expression
100 * MY_FLOAT_CONSTANT_HACKED
expands to
100 * 15 / 4
which is really
(100 * 15) / 4
Using a macro to violate operator precedence is a bad idea.
What would make sense is to put the entire expression into a macro:
#define WHATEVER (100 * 15 / 4)
Or, if you want to parameterize it, perhaps something like this:
#define WHATEVER(x, y) (100 * (x) / (y))
BTW, here's my example of How Not To Use Macros (designed for Douglas
Adams fans):
================================
#include <stdio.h>
#define SIX 1+5
#define NINE 8+1
int main(void)
{
printf("%d * %d = %d\n", SIX, NINE, SIX * NINE);
return 0;
}
================================
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"