function behaves differently if included from header

Hi

I have a fairly simple function whose output appears to change depending upon whether the function is included in main.cpp directly or from a header.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

// main.cpp

#include <iostream>

using namespace std;

bool cmpd (double num1, double num2) {
  const double epsilon = 0.000001;
  if (abs(num1 - num2) <= epsilon)
    return true;
  return abs(num1 - num2) <= epsilon * std::max(abs(num1), abs(num2));
}

int main()
{
      double n1 = 40, n2 = 40.1000;
      std::cout << "\nTesting  "  << n1 << " and "<< n2 << " = " << cmpd(n1, n2) << "\n";   
   return 0;
}


The (correct) output of the above is 'Testing 40 and 40.1 = 0'.

However, the output is different when cmpd is included from a header:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

//main.cpp

#include <iostream>

#include "Test.h"

int main() {
      double n1 = 40.0, n2 = 40.1000;
      std::cout << "\nTesting  "  << n1 << " and "<< n2 << " = " << cmpd(n1, n2) << "\n";   
      return 0;
}

// Test.h

#ifndef TEST_H
#define TEST_H

bool cmpd (double num1, double num2) {
  const double epsilon = 0.000001;
  if (abs(num1 - num2) <= epsilon)
    return true;
  return abs(num1 - num2) <= epsilon * std::max(abs(num1), abs(num2));
}

#endif


The (incorrect) output of the above is 'Testing 40 and 40.1 = 1'.

Does anyone know why the output is different in the above cases? I am aware that typically a header shouldn't contain an implementation but I believe it is justified in my particular case (and I don't think that is relevant to why the output is different).

Thanks
Last edited on
Well the latter lacks a "using namespace std;".
So perhaps your 'abs' is different in both cases.

Make sure you have the right header files and namespaces for the abs you actually want.
ah, thanks that was it - my code doesn't have an abs function so there must be multiple functions in the std library
C++ 17 has std::abs(double), however in C there is no function overload so you have
abs(int), labs(long int), llabs(long long int) for integers and
fabs(double), fabsf(float), fabsl(long double) for floating point numbers
also, there are no namespaces

so, when you were doing abs(num1 - num2), you were calling ::abs(), that is abs(int)

perhaps should use fabs()


edit: misread the reference, seems that std::abs(double) exists from c++98
Last edited on
Topic archived. No new replies allowed.