Programmers toolkit - Sign of an integer

Articles: 

Back in October, 2018, a discussion in the usenet comp.lang.c newsgroup addressed (among other things) the original poster's complaint about the return value of the C standard strcmp() function. The poster contended that the strcmp() function should return one of three values: -1 if the first string was lexically "less than" the second string, 0 if the strings were lexically "equal", and +1 if the first string was lexically "greater than" the second string. The more knowledgable of the comp.lang.c crowd explained why strcmp() behaves the way it does, how strcmp() works, and what alternatives the poster had to work with.

The poster did not impress me; it seemed to me that, since the C standards and decades of common use had already dictated the behaviour of strcmp(), and the poster could realize his requirement with a single line of code, the poster had voiced his contrarian opinion just to make noise.

But, that lead me to another realization; I had not ever seen an integer "signof()" function. And so, from hints in that discussion thread, I wrote my own:


/*
** Returns -1 if argument < 0, 0 if argument == 0, 1 if argument > 0
*/
int iSignOf(int valu)
{
  return ((valu > 0) - (valu < 0));
}

And, to satisfy the conversation in comp.lang.c and my own curiosity, I wrote a "range-limited" strcmp():


/*
** return +1 if first string > second string,
**         0 if first string == second string, or
**        -1 if first string < second string
*/
int Strcmp(const char *one, const char *two)
{
  int r = strcmp(one,two);

  return ((r > 0) - (r < 0));	
}

I consider these functions (and the underlying expression that makes them work) both trivial and obvious. I relinquish any and all rights of ownership that I may have on them; use them in good health.

Happy programming.