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

Steven Schveighoffer schveiguy at gmail.com
Sat Apr 2 15:46:10 UTC 2022


On 4/2/22 5:38 AM, Elronnd wrote:
> On Friday, 1 April 2022 at 17:39:24 UTC, Steven Schveighoffer wrote:
>> In practice, I don't see how it affects the behavior *of the 
>> compiler*. When you subtract two pointers, I don't see how the 
>> compiler/optimizer can make some other decision based on the 
>> subtraction not being between two pointers to the same block of memory.
> 
> Unfortunately, they can and do.  For instance, consider this snippet of 
> c code:
> 
> #include <stddef.h>
> #include <stdlib.h>
> int f() {
>      int *x = malloc(1), *y = malloc(1);
>      ptrdiff_t d = y - x;
>      return y == x + d;
> }
> 
> GCC compiles this to the same code as:
> 
> int f() { return 1; }
> 
> This is intertwined with issues of provenance.

Wait, how does that differ from how it would handle pointers to the same 
block? If we use something other than pointers, it becomes obvious why 
this happens:

```c
int x = ...;
int y = ...;
int d = x - y;
return y == x + d;
```

This is trivially always going to be true.

-Steve


More information about the Digitalmars-d mailing list