Ryan L.
Ryan L.

Reputation: 23

Meaning of these syntax (Pointer Arithmetic?)

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

Answers (4)

littleadv
littleadv

Reputation: 20272

  1. (*x)++ - Increment the value pointed by x (postincrement, returns the original value)

  2. *(x++) - Increment x (post increment) dereference the original pointer).

  3. ++(*x) - Same as #1, but returns the incremented value.

  4. *(++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

Kevin
Kevin

Reputation: 56059

  1. (*x)++ Increments the value pointed to by x and returns its old value.
  2. *(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.
  3. ++(*x) Increments the value pointed to by x and returns its new value.
  4. *(++x) Moves x to the next address (see 2), and returns the value stored at the new address.

Upvotes: 1

Praetorian
Praetorian

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

Aasmund Eldhuset
Aasmund Eldhuset

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

Related Questions