Why ++(*p) changes the pointer value?

Viewed 270

If I have this code:

int A[5] = { 2, 1, 3, 55 };
int *p = A;
cout << ++(*p);

the result is 3 and the value of the first position of A is 3 also, why?

I mean, by hierarchy of operators () is more hierarchical than ++, then we would need operate *p first:

++(*p) => ++(2) => 3 

with any change in A vector?

3 Answers

*p is not just "2", it's an lvalue, i.e. this "2" has a well-defined location. The value at this location is modified by the ++ operator - by definition of the ++ operator.

If you don't want to modify the value, use + 1 instead: *p + 1.


In C/C++, lvalue is a value with a defined location in memory. This value can be changed - by an assignment, incremented, decrement. For example,

int x = 0;
x = 1; // ok, x is an lvalue, assignment changes the value from 0 to 1

int *p = &x;
*p = 2; // ok, *p is an lvalue, assignment changes the value from 1 to 2

In contrast, an rvalue is a value without a defined location - for example, a result of an arithmetic operation. This value can't be assigned, incremented or decremented (it doesn't mean it can't be used in a larger expression).

For example,

int x = 0, y = 1;
(x + y) = 3; // compilation error, (x + y) is an rvalue

2++; // compilation error, 2 is an rvalue

Here's a pretty simple article explaining lvalues / rvalues: https://eli.thegreenplace.net/2011/12/15/understanding-lvalues-and-rvalues-in-c-and-c

The ++(*p) is the same as ++p[0] and ++A[0] All change the first element of the array.

Why ++(*p) changes the pointer value

It does not. The pointer value is value kept in the p. It is called "address" or "reference". It does not change.

It's worth noting the overuse of '*' in C++ which usually confuses novices.

Here:

int *p = A;

'*' means you are declaring p as a variable that can store a memory address (a pointer), and assigning the address of the first position of A (it's the same as &(A[0]) ).

Here:

++(*p)

' *' means you are looking into 'p' content (derreferencing the address of 'p' which is the same as the address of 'A[0]'). Then the '++' increments the value which reflects both.

Just to confirm, after this assignment (int *p = A;) print the values of 'p', 'A' and '&A[0]'.

Related