I found this code in a book:
#include <iostream>
using namespace std;
void ChangesAreGood(int *myparam) {
(*myparam) += 10;
cout << "Inside the function:" << endl;
cout << (*myparam) << endl;
}
int main() {
int mynumber = 30;
cout << "Before the function:" << endl;
cout << mynumber << endl;
ChangesAreGood(&mynumber);
cout << "After the function:" << endl;
cout << mynumber << endl;
return 0;
}
It says:
(*myparam) += 10;
What difference would the following produce?
*myparam += 10;
To answer your question:
In your example, there is no difference except in readability.
And, as the comments on this post all suggest, please don’t use the parenthesis here…
Interesting other cases
Using a property/method on the dereferenced object
On the other hand, there is a difference if you have something like
compared to
The names I chose here tell you what the difference is: the dereference operator
*works on whatever is on its right hand side; in the first case the runtime will fetch the contents ofmyObject.myPropertyPtr, and dereference that, while in the second example it will dereferencemyPointer, and getmyPropertyfrom whatever is found on the object thatmyPointerpoints to.The latter is so common that it even has its own syntax:
myPointer->myProperty.Using the
++operator rather than+=Another interesting example, which I thought of after reading another (now deleted) answer to this question, is the difference between these:
The reason this is more interesting is because since
++is a call like any other, and particularly doesn’t deal with left and right hand side values, it is more ambiguous than your examples with+=. (Of course, they don’t always make sense – sometimes you will end up trying to use the++operator on an object that doesn’t support it – but if we limit our study toints, this won’t be a problem. And it should give you a compiler error anyway…)Since you caught my curiosity, I conducted a small experiment testing these out. This is what I found out:
*myPointer++does the same thing as*(myPointer++), i.e. first increment the pointer, then dereference. This shouldn’t be so surprising – it is what we’d expect knowing the result of running*myObject.someProperty.(*myPointer)++does what you’d expect, i.e. first dereference the pointer, then increment whatever the pointer pointed to (and leave the pointer as is).Feel free to take a closer look at the code I used to find this out if you want to. Just save it to
dereftest.cpp, compile withg++ dereftest.cpp -o dereftest(assuming you have G++ installed) and run with./dereftest.