NoName - 3 months ago 26

C++ Question

So i'm using a preprocessing macro for this basic square function :

`#define SQUARE(a) a*a`

it is then passed to these functions, to perform these tasks respectively:

`double f(double x) {`

return SQUARE(x);

}

double g(double x) {

return SQUARE(1-x);

}

double h(double x) {

return 1/SQUARE(x);

}

with such functions, for g(x) and h(x) i'm getting results such as:

`g(2) = -3, h(2) = 1`

g(3) = -5, h(3) = 1

g(4) = -7, h(4) = 1

etc...

I have changed the functions to get their expected results, but I'm curious as to what is happening in the above functions to give me such strange results?

Answer

`SQUARE(1-x)`

will be expanded to `1-x*1-x`

which is not correct at all.

It would be much better to use a function instead of a macro. A function only evaluates the parameter once.

```
double square(double a)
{ return a * a; }
```