Re: Macros



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
.



Relevant Pages

  • Re: unsigned short addition/subtraction overflow
    ... unsigned short widens to either ... unsigned int or signed int. ... turns out to be *more* surprising. ... >with unsigned types, but it's possible for unsigned types that are ...
    (comp.lang.c)
  • Re: Segmentation fault - interesting problem with array
    ... > My source code is, ... > int i; ... After this it is giving Segmentation fault. ... It's not surprising that an implementation would impose a limit on the ...
    (comp.lang.c)
  • Re: peculiar problem with expression evaluation
    ... I observed something surprising: ... Here is code snippet ... int i = 5; ... Please see the scores of previous postings about this form of undefined ...
    (comp.lang.c)
  • Re: Boxing
    ... Well it's surprising because 't.a' is already on the heap, ... It would be intresting to look at the rotor sources to ... > There's nothing surprising about a box happening here - adding an int ...
    (microsoft.public.dotnet.general)
  • Re: whats wrong with atof() and casting?
    ... Infact for me I got some surprising results. ... Following is the piece of code which I compiled using gcc:- ... int main(int argc,char** argv) ...
    (comp.lang.c)