Re: Macros
- From: roberson@xxxxxxxxxxxxxxxxxx (Walter Roberson)
- Date: Tue, 28 Nov 2006 20:05:49 +0000 (UTC)
In article <1164738830.085064.131700@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
John Bode <john_bode@xxxxxxxxxxx> wrote:
Harry wrote:
# define prod(a,b)=a*b
You want to rewrite
this as
#define prod(a,b) (a)*(b)
double x = 3.14159;
int half = (int) prod(0.5,x);
With your #define, this would expand to (int)(0.5)*(x)
which is ((int)0)*(x) which will become ((double)(int)0)*(x) by
promotion, which will become (double)0 after the mutiplication,
and then the (double) will be implicitly cast to int for the assignment.
If, though, you had used #define prod(a,b) ((a)*(b)) then
(int)((0.5)*(x)) which would do the multiplication as a double,
take the 1.57<whatever> result and explicitly cast that to int, yielding
1 in this example, which would then be assigned into half.
I would suggest to you that most people would find it unacceptably
surprising that prod(0.5,x) can produce different results depending
on what happens to be before the prod() invocation. The principle
of Least Surprise would thus suggest that your suggested #define
is not the best one.
--
There are some ideas so wrong that only a very intelligent person
could believe in them. -- George Orwell
.
- References:
- Macros
- From: Harry
- Re: Macros
- From: John Bode
- Macros
- Prev by Date: Re: Casting malloc (was: Reading a string of unknown size)
- Next by Date: Re: Casting malloc (was: Reading a string of unknown size)
- Previous by thread: Re: Macros
- Next by thread: Pointers and nested structures
- Index(es):
Relevant Pages
|