Is D's pointer subtraction more permissive than C (and C++)?

Steven Schveighoffer schveiguy at gmail.com
Sat Apr 2 02:20:34 UTC 2022


On 4/1/22 5:20 PM, H. S. Teoh wrote:
> On Fri, Apr 01, 2022 at 01:56:19PM -0700, Ali Çehreli via Digitalmars-d wrote:
>> On 4/1/22 13:47, Steven Schveighoffer wrote:
>>
>>>> I think this rule is related to C's accepting wildly different
>>>> platforms, some of which may have different kinds of memory. Two
>>>> pointers to different kinds of memory may not be subtracted.
>>>
>>> Well, can the pointers be subtracted? Yes.
>>
>> My understanding is that depending on the CPU, certain operations
>> would make the CPU barf. I am not sure but the old protected memory,
>> extended memory, etc. systems might not be able to subtract between
>> the systems at all. (Not sure; I am making this up.)
> [...]
> 
> In the bad ole days of segmented protected memory (around the days of
> the 386 or 486, IIRC), you could have memory with different segment
> prefixes, referenced using a convoluted scheme of far ptrs and near
> ptrs. Near ptrs are relative to a particular segment; subtracting near
> ptrs associated with diverse segment pointers yields nonsensical values.
> You can subtract far ptrs, sorta-kinda, but the results are likely to be
> either garbage, or else refer to an address that can't be addressed with
> existing segment pointers. So basically, it's Trouble with a capital T.
> 
> On modern machines, though, this is no longer relevant. I think people
> figured out real quick that segmented addressing is just way more
> trouble than it's worth, so we came running back, tail between legs, to
> the flat memory model and embraced it like there's no tomorrow. :-D

Right, but my larger point was, the *subtraction itself* is not harmful.

There's two ways to look at this. First, if you subtract two pointers 
that *aren't to the same block*, then the data is garbage. The other way 
is that it is *undefined behavior*. I think *using* that subtracted 
difference to e.g. index a pointer is what would be UB. But the 
subtraction itself is ok.

-Steve


More information about the Digitalmars-d mailing list