If I say,
int a[] = {1, 2, 3, 4, 5};
int *p = a;
Now, If I write p + 1 + 2
will it be same as ((p + 1) + 2)
? Any standard reference which proves this wrong?
Only if you don't go out of range. For instance, in this:
int a[] = {1, 2, 3, 4, 5};
int *p = (a + 10) - 9;
int *q = a + (10 - 9);
The assignment to p
invokes undefined behaviour, whereas the assignment to q
doesn't.
As long as you stay in range, though, you'd expect associativity to hold.
Incidentally, note that in your question the two things you give are the same by definition, since addition (well, in-range addition anyway) is left-associative. That is, x + y + z == (x + y) + z
, not x + (y + z)
.
§3.7.4.3
2
A pointer value is a safely-derived pointer to a dynamic object only if it has pointer-to-object type and it is one of the following: ... the result of well-defined pointer arithmetic (5.7) using a safely-derived pointer value;
§ 5.7
3
The result of the binary + operator is the sum of the operands.
Sounds legit to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With