0

What is the difference between using the std scope resolution for cmath methods and not using it?

#include <cmath>
double a = std::atan(0);

vs.

#include <cmath>
double a = atan(0);

The reason why I ask is because I'm building a custom 'atan' static method, and when calling it from within the static method it obviously clashes with the name of the static method itself. So here I avoid the clash by using 'std::' but it does make me think what is happening below the hood.

Header file:

class MathCustom
{
public:
  static double atan(int x, int y);
};

cpp file:

#include <cmath>

double MathCustom::atan(int x, int y)
{
  if (x == 0 && y == 0) { return 0; } // undefined angle, but will be set to 0;
  if (x == 0) { // y != 0
    return (y > 0) ? std::atan(INFINITY) : std::atan(-INFINITY);
  } else { // x != 0 && y: any value
    return std::atan(static_cast<double>(y) / static_cast<double>(x));
  }
}

Appreciated!

Michel H
  • 317
  • 3
  • 10
  • 1
    The second one may or may not compile. You need to include `math.h` or use `using` to use `atan` without `std::` portably. – Marc Glisse Mar 18 '21 at 20:30
  • 1
    You can add your own namespace or use `::atan` to force the `atan` defined in your file. – erip Mar 18 '21 at 20:32
  • Off topic (might come in handy someday): You can avoid the clash by explicitly specifying global scope (`a = ::atan(x);`) – IWonderWhatThisAPIDoes Mar 18 '21 at 20:32
  • `::atan` has the least chance of success, as the global (C-compatible) `atan` can be a macro. – rustyx Mar 18 '21 at 20:34
  • The second one does not compile on my machine, because `atan` is not in the global namespace. Adding a `using std::atan;` before will allow it to compile. Adding `#include ` ought to allow it to compile (but not on my machine, since I intentionally don't have the C header files in the compiler's include system path). – Eljay Mar 18 '21 at 22:23
  • I suggest using `std::numeric_limits::infinity()` instead of `INFINITY` – phuclv Mar 19 '21 at 01:18

0 Answers0