Hatefiend Hatefiend - 2 months ago 14
C Question

C - Increment and decrement pointer, then retrieve value

The following code outputs y as a massive integer, not

15
. I don't understand why. I know the
--
and
++
operators come before the
*
operator, so it should work.

What the follwing code is trying to say.

/*
Create a variable, set to 15.
Create a pointer to that variable.
Increment the pointer, into undefined memory space.
Decrement the pointer back where it was,
then return the value of what is there,
and save it into the variable y.
Print y.
*/

int main()
{
int x = 15;
int *test = &x;
test++;
int y = *test--;
printf("%d\n", y);

return 0;
}


If instead, I change the code to the following:

int main()
{
int x = 15;
int *test = &x;
test++;
test--;
printf("%d\n", *test);

return 0;
}


That code outputs
15
. Why?

Answer

The difference is between x++ and ++x, post- and pre-increment of a pointer.

  • When ++ is after x, the old value is used prior to the increment
  • When ++ is before x, the new value is used after the increment.

This will work:

int y = *(--test);

Although parentheses are not necessary, it is a good idea to use them for clarity.