Bug 8478 – Turn some undefined pointer comparisons into compile-time errors

Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2012-07-30T16:26:30Z
Last change time
2022-09-08T08:37:36Z
Keywords
accepts-invalid, diagnostic
Assigned to
No Owner
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2012-07-30T16:26:30Z
Often the D language shares the semantic of C language. This D program compiles with no errors or warnings: struct Foo { int a, b; } void main() { Foo f; if (&f.a < &f.b) {} // first comparison int a, b; if (&a < &b) {} // second comparison } The first comparison is correct, the addresses of a and b are guaranteed to be in order by the C standard, see §6.5.8:5 (ISO/IEC JTC 1, SC 22, WG 14. ISO/IEC 9899:201x: Programming languages—C. Technical Report n1570, Intl. Organization for Standardization, August 2011). The second comparison is undefined in C according to the C standard §6.5.8:5. Because semantics is given to relational pointer comparisons only where the two addresses share a common base. I think a compiler is free to reorder the position of the variables a and b on the stack. So on that D program I suggest the D compiler to give error similar to: Line 6: Error: cannot apply '<' to different base objects. See: http://c-semantics.googlecode.com/files/2012-C-Semantics-Ellison-Rosu-POPL.pdf
Comment #1 by razvan.nitu1305 — 2022-09-08T08:37:36Z
This is system code and system code is allowed to do any kind of weird operations. Imagine that you have pointers to some stack allocated arrays; in this case it makes sense to compare pointers since the array elements are guaranteed to have an order. My opinion is that the type system must allow liberty when it comes to pointers in system code.