The missing SGN function

Both C and C++ lack a sgn (short for signum apparently!) function (unless C++ has added it in recent changes. It’s also available in Boost but this blog is not about C++ so who cares!

Sgn() for those who don’t know is a function that returns -1 if the passed in int value is negative, 1 if the value was positive or 0 otherwise. Even BASIC includes it but not C.

However it’s easy to add. Something like

int sgn(in x) {
  if (x=0) return 0;
  if (x>0) return 1;
    return -1;

Of course if you are using longints or floats or doubles, you have to write those as well. However an alternative is to make it into a macro.

#define sgn(x) (x < 0) ? -1 : (x > 0)
int a = sgn(10);

The only downside if you make lots of calls to sgn() is that it will slightly bulk up your code compared to calling it as a function but it will run fractionally faster!