I want to calculate x[i]-y[i] only once and save it in a variable and use it.
You already do only calculate it once. This is all pointless.
If you still insist, then the error you name does not exist in this code.
However, you do have a problem with the content of the macro, which both reads from and writes to a single variable within an expression. The result is undefined:
#include <iostream>
#include <cmath>
#include <array>
#ifndef pow2C
double __tmpDouble__;
#define pow2C(a) ((__tmpDouble__=(a))*(__tmpDouble__))
#endif
inline double calculateDistance(double *x, double *y, int NDims)
{
double d = 0;
for (int i = 0; i < NDims; i++)
// it is faster to calculate the difference once
d += pow2C(x[i] - y[i]);
return sqrt(d);
}
int main()
{
const size_t NUM_DIMS = 3;
std::array<double, NUM_DIMS> x{{5.0, 6.0, 7.0}};
std::array<double, NUM_DIMS> y{{1.2, 1.5, 9.0}};
std::cout << "Distance between x and y is: " << calculateDistance(&x[0], &y[0], NUM_DIMS) << '\n';
}
// g++-4.8 -std=c++11 -Wall -pedantic -pthread main.cpp && ./a.out
// main.cpp: In function 'double calculateDistance(double*, double*, int)':
// main.cpp:16:31: warning: operation on '__tmpDouble__' may be undefined [-Wsequence-point]
// d += pow2C(x[i] - y[i]);
// ^
// Distance between x and y is: 6.22013
So, really, we're back to don't do this.
If you're still desperate to avoid evaluating x[i] - y[i]
twice:
inline double calculateDistance(double* x, double* y, int NDims)
{
double d = 0;
for (int i = 0; i < NDims; i++) {
const double diff = x[i] - y[i];
d += diff * diff;
}
return sqrt(d);
}
You can pass off the multiplication work to another inline
utility function if you like, but there is no need for a macro here.