O'Reilly logo

Just Enough C/C++ Programming by Guy W. Lecky-Thompson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Code Sample 8.5: Integer Comparison Function

int IntegerCompare ( int nA, int nB )
{
  // Should nA be before nB?
  if ( nA < nB )
  {
    return -1;
  }

  // Should nA be after nB?
  if ( nA > nB )
  {
    return 1;
  }

  // They must be equal
  return 0;
}

You could have reduced this to a single statement:

return nA - nB;

However, this would return a number less than 0, equal to 0, or greater than 0, which might not follow the same behavior as, for example, strcmp. It is preferable, therefore, to perform an explicit comparison.

With this function defined, you can set up a memory block of 100 integers:

int * pIntegerArray;
pIntegerArray = (int * ) malloc (sizeof (int) * 100);

Once you have populated it with values, you can sort them:

qsort ( pIntegerArray, 100, sizeof ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required