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

Steven Schveighoffer schveiguy at gmail.com
Fri Apr 1 19:43:01 UTC 2022


On 4/1/22 2:44 PM, Paul Backus wrote:
> On Friday, 1 April 2022 at 15:52:39 UTC, Ali Çehreli wrote:

>> 2) Is subtracting pointers that used to be in the same array legal.
>>
>> void main() {
>>   auto a = [ 1, 2 ];
>>   auto b = a;
>>   assert(a.ptr - b.ptr == 0);    // i) Obviously legal?
>>
>>   // Drop the first element
>>   a = a[1..$];
>>   assert(a.ptr - b.ptr == 1);    // ii) GC-behaviorally legal?
>>
>>   // Save the pointer
>>   const old_aPtr = a.ptr;
>>   // and move the array to another memory
>>   a.length = 1_000_000;
>>   // Expect a and b are on different blocks of memory
>>   assert(a.ptr != old_aPtr);
>>
>>   assert(old_aPtr - b.ptr == 1);  // iii) Practically legal?
>> }
> 
> According to the C rules, (i) and (ii) are legal, since they point to 
> the same memory block, but (iii) is illegal.

(iii) is the same as (ii) because old_aPtr is the same as a.ptr at that 
time.

-Steve


More information about the Digitalmars-d mailing list