Serious problem with opCmp

Bill Baxter dnewsgroup at billbaxter.com
Sun Mar 2 13:24:17 PST 2008


kov_serg wrote:
>> void chk(S *a, S *b) {
>> 	int  z=a.opCmp(b);
>> 	char c0=z<0?'<': z>0?'>' : '=';
>> 	char cc=a<b?'<': a>b?'>' : '=';
>> 	printf("%11d %c %11d (%11d%c0)\n",a.b,cc,b.b,z,c0);
>> }
> One answer I've found. This code compares addresses of a and b. But I suppose it will use opCmp(T*) to compare them. But it compares something else.
> 
> But more general problem still remain:
> If I use opCmp for sort algorithm or for some kind of ordered stucture. Every thing will works untill I tring to use wide spead values for example hash codes. Hash values may have any aceptable values. And program will work incorrect and unpredictable. And will be hard to locate problem and will be hard explain this problem to everyone how followed the wrong example without any doubt in its validity.
> 
> Here the instance of such inherience http://team0xf.com:8080/omg?f=1b291ae58034;file=core/Fixed.d;style=gitweb
> ...
> 127 int opCmp(fixed32T rhs) {
> 128 return store - rhs.store;
> 129 } 
> ...
> 
> Or am I panic without reason?

Nope. I think you've got a good point.  I was lured in by the 'just do 
subtraction' thing too.  Not a horrible hack if you expect all the 
values to be smallish, but even then statistically there's a peak in the 
distribution of values used at Type.max and Type.min because these can 
be useful a bogus marker values to forcing an always greater or always 
less result.  Or at least you would think so, until you actually tried 
to compare with them.

It's definitely an accident waiting to happen.

--bb



More information about the Digitalmars-d mailing list