D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 8478 - Turn some undefined pointer comparisons into compile-time errors
Summary: Turn some undefined pointer comparisons into compile-time errors
Status: RESOLVED WONTFIX
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 enhancement
Assignee: No Owner
URL:
Keywords: accepts-invalid, diagnostic
Depends on:
Blocks:
 
Reported: 2012-07-30 16:26 UTC by bearophile_hugs
Modified: 2022-09-08 08:37 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2012-07-30 16:26:30 UTC
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 RazvanN 2022-09-08 08:37:36 UTC
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.