Hatefiend
Hatefiend

Reputation: 3596

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?

Upvotes: 2

Views: 589

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

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.

Upvotes: 5

Related Questions