Reputation: 1650
#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
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
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
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
Reputation: 1220
You're incrementing the pointer's value, not the value pointed by it.
Upvotes: 0
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
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