Skip to content

Commit 03622ce

Browse files
committed
[expression.dd] Add examples for pointer addition/subtraction
[arrays.dd] Don't mention `p + 2` pointer addition, leave that to the AddExpression link to explain.
1 parent 4b0c4f2 commit 03622ce

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

spec/arrays.dd

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,11 +235,12 @@ $(SPEC_RUNNABLE_EXAMPLE_RUN
235235
int[] a = [1,2,3];
236236
int* p = a.ptr;
237237

238-
*(p + 2) = 4; // same as `p[2] = 4`
238+
p[2] = 4;
239239
assert(a[2] == 4);
240+
writeln(p[3]); // undefined behaviour
240241

241242
assert(p == &a[0]);
242-
p++;
243+
p++; // point to a[1]
243244
assert(*p == 2);
244245
---
245246
)

spec/expression.dd

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -813,6 +813,20 @@ $(GNAME AddExpression):
813813
the size of the type pointed to by the first operand.
814814
)
815815

816+
$(SPEC_RUNNABLE_EXAMPLE_RUN
817+
---
818+
int[] a = [1,2,3];
819+
int* p = a.ptr;
820+
assert(*p == 1);
821+
822+
*(p + 2) = 4; // same as `p[2] = 4`
823+
assert(a[2] == 4);
824+
---
825+
)
826+
827+
$(P $(GLINK IndexExpression) can also be used with a pointer and has
828+
the same behaviour as adding an integer.)
829+
816830
$(P If the second operand is a pointer, and the first is an integral type,
817831
and the operator is $(D +),
818832
the operands are reversed and the pointer arithmetic just described
@@ -831,7 +845,13 @@ $(GNAME AddExpression):
831845
The type of the result is $(D ptrdiff_t).
832846
)
833847

834-
$(P $(GLINK IndexExpression) can also be used with a pointer.)
848+
$(SPEC_RUNNABLE_EXAMPLE_RUN
849+
---
850+
int[] a = [1,2,3];
851+
ptrdiff_t d = &a[2] - a.ptr;
852+
assert(d == 2);
853+
---
854+
)
835855

836856
$(H2 $(LNAME2 cat_expressions, Cat Expressions))
837857

0 commit comments

Comments
 (0)