NoName - 3 months ago 26
C++ Question

# Preprocessor behind the scenes, how does it interpret the following lines of code C++

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:

$\dpi{150}&space;f(x)&space;=&space;x^2,&space;g(x)&space;=&space;(1-x)^2,&space;h(x)&space;=&space;1/x^2$

``````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?

`SQUARE(1-x)` will be expanded to `1-x*1-x` which is not correct at all.
``````double square(double a)