/* aliasing example */

/* dot_prod(a, b, n, r)
 * assume a[n] and b[n]; compute sum a[i]*b[i] and deposit result in r
 */
void dot_prod_1 (double* a, double* b, long n, double* r) {
  int i;
  *r = 0.0;
  for (i = 0; i < n; i++)
    *r += a[i]*b[i];
}

/* avoid repeated memory references by creating local variables */
void dot_prod_2 (double* a, double* b, long n, double* r) {
  int i;
  double sum = 0.0;
  for (i = 0; i < n; i++)
    sum += a[i]*b[i];
  *r = sum;
}

/* these two can give different result if one elements of the
 * input vectors is aliased to the output vector
 * probably the second one is not only faster, but more oftent
 * the desired behavior
 */
int main () {
  double a[3] = {1.0, 2.0, 3.0};
  double b[3] = {4.0, 5.0, 6.0};
  double r = 0.0;
  dot_prod_2(a, b, 3, &r);
  dot_prod_1(a, b, 3, &a[1]);	/* this one last because it alters a[1] */
  printf("dot_prod_1 = %f\ndot_prod_2 = %f\n", r, a[1]);
}
