Well I'm following up to my own post because neither of the other
replies have castigated me
Wow, I think I have spotted two mistakes in one of Richards posts.
(Mind you the next reply to this will have Richard spotting four
mistakes in my post
Firstly, I think either the USHRT_MAX should be SHRT_MAX or
shortVal should be unsigned.
Well, I was ok until here.
Secondly, if doubleVal1 - doubleVal2 is greater than USHRT_MAX but is
less than USHRT_MAX+1 then the if will result in the "Can't assign"
message while the assignment will be fine.
And ok to here as well. If only I had stopped at this point
So the if needs to read:
if((unsigned short)(doubleVal1 - doubleVal2) < USHRT_MAX)
Well.... I _think_ this is utter rubbish :-( Richards code at least
worked except for a corner case.
First of all the < should be <=. But even after that the cast will
force the value to be 0..USHRT_MAX.
I'm not sure this can be solved (in clc talk). If you make the assumption
that UINT_MAX>USHRT_MAX then I think
if(doubleVal1 - doubleVal2 <= USHRT_MAX+1) would do the trick.
Maybe if(floor(doubleVal1 - doubleVal2) <= USHRT_MAX) is sufficient but I
always start getting nervous when worrying about corner cases and floating
point in the same breath .... especially if this has to work on the DS9000.
I think this is still safe if shortVal is signed giving:
if((short)(doubleVal1 - doubleVal2) < SHRT_MAX)
And I don't know whether this is safe but I think not. Surely there is
no difference between
short s;
double d=get_number_too_big_for_short();
s=d; /*and*/
s=(short)d;
So both are demon fodder to a DS9000.
Tim.