3

Is there a difference between the two expressions:

(*x)++

and

++(*x)

I can see both of these statements replace the contents of (*x+1) in *x. But are there any differences between them?

3

4 Answers 4

7

(*x)++ evaluates to the value of*x; as a side effect, the value in *x will be incremented by 1.

++(*x) evaluates to the value of *x + 1; as a side effect, the value in *x will be incremented by 1.

Assuming the code:

int a = 5;
int *x = &a;

(*x)++ will evaluate to 5, while ++(*x) will evaluate to 6.

Note that the side effect does not have to be applied immediately after the expression has been evaluated; it only needs to be applied before the next sequence point.

Also note that the parentheses matter for (*x)++; postfix ++ has higher precedence than unary *, so *x++ would be parsed as *(x++); it still evaluates to the value of *x, but as a side effect advances the pointer, rather than increment the thing being pointed to. Prefix ++ and unary * have the same precedence, so they're applied left-to-right; thus ++(*x) and ++*x would have the same result (*x gets incremented, not x).

1
  • 1
    Thanks for mentioning importance of parentheses.. :) Jul 4, 2014 at 17:05
6

Let us say the value pointed by x is 10 i:e (*x is 10)

y = (*x)++;

the above statement will be executed as
1. y = *x
2. *x = *x + 1
so y = 10 & *x is 11

y = ++(*x);

the above statement will be executed as
1. *x = *x + 1
2. y = *x
so y = 11 & *x is 11

2

One increments the values stored in x before it is used (pre), while the other does it after it is used (post).

Also note that ++(*x) is not the same as (*x + 1). The first increments the value and stores it back, the other just increments the value.

1
1

One is "pre" and the other is "post". That's the difference. One is evaluated before the the increment (the first option), the other is evaluated after the increment (the second option).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.