Andrew
Andrew

Reputation: 1650

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

#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?

Upvotes: 3

Views: 11159

Answers (6)

Loki Astari
Loki Astari

Reputation: 264361

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

Upvotes: 7

casablanca
casablanca

Reputation: 70701

++ 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)++.

Upvotes: 3

NPE
NPE

Reputation: 500217

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.

Upvotes: 9

Juan Pablo Santos
Juan Pablo Santos

Reputation: 1220

You're incrementing the pointer's value, not the value pointed by it.

Upvotes: 0

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145224

*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.,

Upvotes: 1

mdarwi
mdarwi

Reputation: 933

It is the same thing as doing

*(pointer++)

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

Upvotes: 2

Related Questions