c++cmath

Is there a standard sign function (signum, sgn) in C/C++?


I want a function that returns -1 for negative numbers and +1 for positive numbers. http://en.wikipedia.org/wiki/Sign_function It's easy enough to write my own, but it seems like something that ought to be in a standard library somewhere.

Edit: Specifically, I was looking for a function working on floats.


Solution

  • The type-safe C++ version:

    template <typename T> int sgn(T val) {
        return (T(0) < val) - (val < T(0));
    }
    

    Benefits:

    Caveats: