Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is arithmetic on pointers associative?

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?

like image 616
cpx Avatar asked Dec 06 '11 18:12

cpx


2 Answers

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).

like image 122
Stuart Golodetz Avatar answered Oct 05 '22 02:10

Stuart Golodetz


§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.

like image 44
Mooing Duck Avatar answered Oct 05 '22 03:10

Mooing Duck