Neil Butterworth, Mark and Paul are right.
SQUARE (++ y) expands to ++ y * ++ y, which doubles the value of y.
Another problem you might run into: SQUARE (a + b) expands to a + b * a + b, which is not (a + b) * (a + b), but a + (b * a) + b. You should take care to add parentheses around elements when necessary when defining macros: #define SQUARE (X) ((X) * (X)) is slightly less risky. (Ian Kemp wrote this first in his comment)
Instead, you can use the built-in template function (no less efficient at runtime), such as:
template <class T> inline T square(T value) { return value*value; }
You can check if it works:
int i = 2; std::cout << square(++i) << " should be 9" << std::endl; std::cout << square(++i) << " should be 16" << std::endl;
(no need to write
square<int>(++i)
because the int type is implicit for i)
moala source share