0

I defined a function to calculate the distance between 2 points in 2D, these points being arrays of 2 elements. My "distance" function gives me different results when passing the arrays as constant, or not, in the function.

Here is my code:

#include <iostream>
#include<math.h>

using namespace std;

double distance(const double *x1,const double *x2)
{
double dist;
dist=sqrt((x1[0]-x2[0])*(x1[0]-x2[0]) + (x1[1]-x2[1])*(x1[1]-x2[1]));
return dist;
}

double distance1(double *x1,double *x2)
{
double dist;
dist=sqrt((x1[0]-x2[0])*(x1[0]-x2[0]) + (x1[1]-x2[1])*(x1[1]-x2[1]));
return dist;
}

int main() {
double x1[2],x2[2];
double val;
x1[0]=1;x1[1]=0;
x2[0]=0;x2[1]=1;

val=distance(x1,x2);
cout << val << endl;
val=distance1(x1,x2);
cout << val << endl;


return 0;
}

Doing so I get :

-2

1.41421

I don't understand why the "distance" function does not do the same as "distance1". I would expect the same result but "distance" preventing me from modifying the content of the x1 and x2 arrays.

Also, when naming both function "distance", I get the expected results (1.41421), which function is then called in that case ?

Any help would be appreciated.

1 Answers1

0

In the first case will be called the function std::distance that returns the distance between iterators:

template<class InputIterator>
  typename iterator_traits<InputIterator>::difference_type
    distance (InputIterator first, InputIterator last);

Just a bad name choice for a function ;)

[EDITED] As Evert pointed, please take a look at Why is “using namespace std;” considered bad practice?

Community
  • 1
  • 1
Leo Chapiro
  • 13,678
  • 8
  • 61
  • 92
  • 1
    See also http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice –  Oct 01 '14 at 09:46