In C++, how does the expression, "*pointer++" work?

10,429

Solution 1

Post-increment (++) has higher precedence than dereference (*). This means that the ++ binds to pointer rather than *pointer.

See C FAQ 4.3 and references therein.

Solution 2

Ok, everybody has explained the binding of the parameters.
But nobody mentioned what it means.

int    data[1,2,3,4,5];

int*   pointer = data;

std::cout << *pointer++ << std::endl;
std::cout << *pointer   << std::endl;

As mentioned the ++ operator has a higher priority and thus binds tighter than the * operator. So the expressions is equivalent too:

std::cout << *(pointer++) << std::endl;
std::cout << *pointer << std::endl;

But the operator ++ is the postfix version. This means the pointer is incremented but the result of the operation returns the original value for use by the * operator. Thus we can modify the statement as follows;

std::cout << *pointer << std::endl;
pointer++;
std::cout << *pointer << std::endl;

So the result of the output is the integer currently pointed at but the pointer also get incremented. So the value printed is

1
2

not

2
3

Solution 3

++ has higher precedence than *, so your expression is equivalent to *(pointer++) -- it dereferences the value and then increments the pointer, not the value. If you want to increment the value, you need to do (*pointer)++.

Solution 4

It is the same thing as doing

*(pointer++)

in that it increments the address that the pointer holds, then it dereferences it.

Solution 5

*pointer++ means *(pointer++).

i.e., it increments the pointer, not the pointee.

one way to remember that is to read the original K&R "The C Programming Language", where their example of strcpy uses this.

anyway, that's how i remember the precedence.

and since it increments the pointer, your second dereference has Undefined Behavior.

cheers & hth.,

Share:
10,429
Andrew
Author by

Andrew

Updated on June 04, 2022

Comments

  • Andrew
    Andrew almost 2 years
    #include <iostream>
    using namespace std;
    
    int main () {
        int value = 1, *pointer;
        pointer = &value;
        cout << *pointer++ << endl;
        cout << *pointer << endl;
    }
    

    Why does the ++ operator not increment value?