lokman said:
Hi,
In the following code, can someone tell me the difference between *p++ and
p++ ? I can see both achieve the same result.
Thanks a lot !
#include <iostream>
using namespace::std;
int main() {
char *p = "test pointer";
Quick note: don't do this. Never make a (non-const) char pointer point
to a string literal. This conversion is allowed for C compatibility, but
is deprecated because it is dangerous. It allows you to write code that
(attempts to) modify a string literal without getting a warning from the
compiler. Modifying a string literal (or attempting to) invokes
undefined behavior.
If you want a pointer to a string literal, always use a pointer to const
char, like one of the following:
const char *p = "some string";
char const *p = "some string"; // same as prev
const char * const p = "some string";
char const * const p = "some string"; // same as prev
In the last two 'p' itself is also const.
while (*p) {
cout << *p;
*p++; // <<- What is the difference between *p++ and p++ (both achieve
the same result) ?
}
cout << endl;
return 0;
}
It looks like all the replies so far are wrong in one way or another.
The expression 'p++' causes p to be incremented at some point before the
next sequence point. It also has a result, which is the value of 'p'
before being incremented. There's an subtle but important point here:
you don't know *when* 'p' will actually be updated, only that it will
happen sometime before the next sequence point (usually a semi-colon,
but there are others). People frequently get this wrong.
As for the expression '*p++', it is equivalent to '*(p++)' (contrary to
what one of the other replies said, post-increment has higher precedence
than dereference -- check any precedence chart). So, as described
previously, 'p' is scheduled to be incremented at some point before the
next sequence point, and also a result is given. The result is the value
of 'p' prior to the increment. The '*' is applied to that, giving the
object that 'p' pointed to prior to the increment. This result is
immediately discarded in your case.
So there's no reason for the '*' in this case. It might even slow your
program down a little, so get rid of it.
Also, replace 'p++' with '++p'. Get in the habit of using pre-increment
in cases where either will work. There's a chance it will be faster, and
it almost certainly won't be slower. There probably is no difference for
built-in types, but for class types there may be a substantial difference.
-Kevin