type_size_sort

3 messages, 2 authors, 2016-06-15 · open the first message on its own page

type_size_sort

From: Morten Welinder <hidden>
Date: 2016-06-15 22:42:14

static int type_size_sort(const struct object_entry *a, const struct
object_entry *b)
{
...
  return a < b ? -1 : (a > b);
}

This does not look valid.  the standard says you must not depend on the
location:


       [#4] When  the  same  objects  (consisting  of  size  bytes,
       irrespective  of  their  current positions in the array) are
       passed more  than  once  to  the  comparison  function,  the
       results  shall be consistent with one another.  That is, for
       qsort they shall define a total ordering on the  array,  and
       for  bsearch  the  same object shall always compare the same
       way with the key.


M.

Re: type_size_sort

From: Andreas Ericsson <hidden>
Date: 2016-06-15 22:42:14

Morten Welinder wrote:
static int type_size_sort(const struct object_entry *a, const struct
object_entry *b)
{
...
  return a < b ? -1 : (a > b);
}

This does not look valid.  the standard says you must not depend on the
location:


       [#4] When  the  same  objects  (consisting  of  size  bytes,
       irrespective  of  their  current positions in the array) are
       passed more  than  once  to  the  comparison  function,  the
       results  shall be consistent with one another.  That is, for
       qsort they shall define a total ordering on the  array,  and
       for  bsearch  the  same object shall always compare the same
       way with the key.
It's perfectly correct. If the same list was to be passed to 
create_sorted_list() twice it will come out exactly the same the second 
time as it did the first. The only thing to remark on is that the return 
above could be written as below instead:

	return a - b;

-- 
Andreas Ericsson                   andreas.ericsson@op5.se
OP5 AB                             www.op5.se
Tel: +46 8-230225                  Fax: +46 8-230231

Re: type_size_sort

From: Morten Welinder <hidden>
Date: 2016-06-15 22:42:14

It's perfectly correct. If the same list was to be passed to
create_sorted_list() twice it will come out exactly the same the second
time as it did the first. The only thing to remark on is that the return
above could be written as below instead:

        return a - b;
That is not what the part  of the standard I quoted says.  It very
clearly forbids the sorting function from depending on the pointers'
values.  I can even see an implementation actually using this
requirement.

And it is well known that some qsort implementations will do nasty
things if the sorting order is not consistent.  I've seen Perl core
dumps on that account, although that is a while ago.

M.
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help