Reputation: 23
I was wondering what these 4 symbols mean. I am new to pointers in C and I'm not sure if this is considered pointer arithmetic?
1. (*x)++
2. *(x++)
3. ++(*x)
4. *(++x)
Thanks
Upvotes: 2
Views: 783
Reputation: 20272
(*x)++
- Increment the value pointed by x
(postincrement, returns the original value)
*(x++)
- Increment x
(post increment) dereference the original pointer).
++(*x)
- Same as #1, but returns the incremented value.
*(++x)
- Same as #2, but dereferencing the resulting pointer.
Also, #2 and #4 change the value of the pointer (pointer arithmetics), while #1 and #3 - change the value pointed by x
(i.e.: whatever-x-points-at arithmetics).
Upvotes: 6
Reputation: 56059
(*x)++
Increments the value pointed to by x
and returns its old value.*(x++)
Changes x
to point to the next memory address (Exactly where that is is determined by the size of what x
is declared to be pointing at) and returns the value stored at the old address.++(*x)
Increments the value pointed to by x
and returns its new value.*(++x)
Moves x
to the next address (see 2), and returns the value stored at the new address.Upvotes: 1
Reputation: 109119
1. (*x)++
The value that is being pointed to by x
is being post-incremented. This will yield the pointed to value prior to the increment operation.
2. *(x++)
The pointer x
is being dereferenced and the post-incremented. This returns the value that is being pointed to by x
prior to the increment operation.
3. ++(*x)
The value being pointed to by x
is being pre-incremented. This will yield the pointed to value after the increment operation.
4. *(++x)
The pointer x
is being dereferenced after being pre-incremented. This will yield the value of the location immediately after the one currently being pointed to by x
.
Since 2 & 4 alter the value of x
itself they are considered examples of pointer arithmetic. 1 & 3 modify the object being pointed to by x
, but not the pointer itself; so these are not considered to be pointer arithmetic.
Upvotes: 5
Reputation: 37950
Everything that involves increasing or decreasing the value of a pointer (as opposed to the value of what it points to) is considered pointer arithmetic. Hence, 2 and 4 are examples of pointer arithmetic, while 1 and 3 are not.
For example, (*x)++
means to first locate the value that x
points to and then increment that value by 1, while *(x++)
means to increment x
itself (that is, make it point to the element to the immediate right of what it was originally pointing to), and then find the value of the element that x
originally pointed to.
Upvotes: 0