Skip to content

Commit af4f2ad

Browse files
committed
Avoid overflow/underflow; tweak example
1 parent 04afaae commit af4f2ad

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

spec/operatoroverloading.dd

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -520,17 +520,22 @@ $(SPEC_RUNNABLE_EXAMPLE_RUN
520520
struct S
521521
{
522522
int i, j;
523-
int opCmp(ref const S s) const { return i - s.i; } // ignore j
523+
int opCmp(ref const S s) const { return (i > s.i) - (i < s.i); } // ignore j
524524
}
525525

526526
S a = {2, 3};
527527
S b = {2, 1};
528+
S c = {3, 0};
529+
assert(a < c);
528530
assert(a <= b);
529-
assert(!(a < b));
530-
assert(a != b); // generated opEquals tests both i and j members
531+
assert(!(a < b)); // opCmp ignores j
532+
assert(a != b); // generated opEquals tests both i and j members
531533
---
532534
)
533535

536+
$(BEST_PRACTICE Using `(i > s.i) - (i < s.i)` instead of `i - s.i` to
537+
compare integers avoids overflow/underflow.)
538+
534539

535540
$(H2 $(LEGACY_LNAME2 FunctionCall, function-call, Function Call Operator Overloading $(D f())))
536541

0 commit comments

Comments
 (0)