user923005 <> writes:
> On Mar 17, 3:29*pm, "Bartc" <ba...@freeuk.com> wrote:
>> <blm...@myrealbox.com> wrote in message
[...]
>> Create a small macro or function to calculate squares or cubes of integers.
>>
>> The result will be as clear or clearer than using pow(), can probably be
>> optimised, and you run no risk of activating the floating point unit.
>
> Function macros are evil.
>
> #define SQUARE(x) (x*x)
> #define CUBE(x) (x*x*x)
I think you mean:
#define SQUARE(x) ((x)*(x))
#define CUBE(x) ((x)*(x)*(x))
though the parentheses don't help the following:
> ...
> y = SQUARE(x++); // undefined behavior
> z = CUBE(++x); // ditto
However, the use of an all-caps name should warn the programmer that
this is a macro, and that arguments with side effects are to be
avoided.
Of course you can use an inline function if your compiler supports it.
> The floating point unit is not a penalty like it was in the old days.
True (though I suppose it might be on some systems), but there's
still the risk of roundoff error. On any sane implementation,
pow(2.0, 2.0) == 4.0, but implementations aren't required to be sane.
It's conceivable that pow(2.0, 2.0) could yield 3.999999999...;
then this:
int two_squared = pow(2, 2);
would set two_squared to 3.
Perhaps no current real-world systems have this problem, but
personally I'd rather write ``2 * 2'' than have to think about whether
pow() is going to do what I want after all the implicit conversions
settle out.
--
Keith Thompson (The_Other_Keith)
<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"