Pop Quiz what is wrong with this code?

Steven Schveighoffer schveiguy at gmail.com
Mon Jun 22 13:24:32 UTC 2020


On 6/22/20 9:02 AM, WebFreak001 wrote:
> On Monday, 22 June 2020 at 12:42:26 UTC, Steven Schveighoffer wrote:
>> On 6/20/20 11:22 PM, Danni Coy wrote:
>>> On Sun, Jun 21, 2020 at 9:40 AM Avrina via Digitalmars-d
>>> <digitalmars-d at puremagic.com> wrote:
>>>>
>>>> On Saturday, 20 June 2020 at 18:15:27 UTC, Steven Schveighoffer
>>>> wrote:
>>>>> On 6/20/20 12:00 PM, Danni Coy wrote:
>>>>>
>>>>>> I tried explicitly making x and y ints and I got a
>>>>>> depreciation warning.
>>>>>
>>>>> foreach(ptrdiff_t y, ref row; offsetMap)
>>>>>
>>>>> is that what you wanted?
>>>>>
>>>>> ptrdiff_t is the signed version of size_t. The complaint is not
>>>>> that you are converting from unsigned to signed, but that you
>>>>> are converting from 64-bit to 32-bit.
>>
>>>> Why isn't that deprecated as well? implicitly converting from
>>>> ulong to long is an error as much as ulong to uint.
>>>
>>> It turns out this line is the bigger problem.
>>>
>>>   immutable SDL_FPair offset  = { center.x - x, y - center.y };
>>> FPair is a
>>> struct SDL_FPair
>>> {
>>>      float x;
>>>      float y;
>>> ...
>>> if those values were ints.
>>> dmd will not allow a downcast from ulong to int
>>> (the compiler would have caught the issue for me)
>>> but it will allow casting ulong to float which is why It took me a
>>> couple of hours with a debugger
>>> trying to find the bug.
>>
>> So this entire conversation is incorrect -- there is no promotion to 
>> unsigned happening.
>>
>> What is the bug with size_t implicitly casting to float? I would think 
>> it would work.
>>
> 
> I think the issue is that it's converting the ulongs to float, which are 
> actually negative and not positive: center.x - x and y - center.y might 
> become negative and because it's a ulong it will be a huge number, then 
> converting to float it will be a huge float number instead of some 
> normal negative number.
> 
> so:
> 
> size_t centerX = 1;
> size_t x = 3;
> float f = centerX - x; // <- this is not -2, this is 1.84467e+19 without 
> any warnings or deprecations printed
> 
> Meanwhile an implicit cast to int is disallowed (error) but it would 
> actually contain the correct result and nobody would have ever found it.

But the OP rejected the idea of using ptrdiff_t (or did he?), which 
would solve that problem.

It's really hard to tell what the problem is without more definition or 
explanation.

-Steve


More information about the Digitalmars-d mailing list