-3

Let's see the first code:

The following code displays the value of n=10:

#include<iostream>
int main()
{
    int n=10;
    int*p=&n;
    *p++;
    std::cout<<n;
    return 0;
}

The following code displays the value of n=11:

#include<iostream>
int main()
{
    int n=10;
    n++;
    std::cout<<n
    return 0;
}
Shubham
  • 2,847
  • 4
  • 24
  • 37
  • 1
    Looks as if only the adress stored in p is incremented. Try to put some paranthesis around the dereferenced pointer – simmue Jun 24 '18 at 09:06
  • Should also point out that `*(p++)` is not portable because you're modifying a pointer to memory that doesn't belong to an array (it might even be undefined behaviour, not quite sure, anyway you should never do it unless you really know what you're doing). – George Jun 24 '18 at 09:26

2 Answers2

10

p++ increments the pointer. You would need (*p)++ to increment the value.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
4

Operator precedence.

The first case is parsed as *(p++); - first increment the address and then dereference. This does not modify any values.

The second case merely increments the value itself.

DeiDei
  • 10,205
  • 6
  • 55
  • 80
  • 3
    A clarification about the order: The increment is done on the pointer alright, but it's the *old* value of the pointer which is dereferenced. Otherwise, if it's the incremented pointer which is dereferenced (as in `*++p`) then it would be *undefined behavior*. – Some programmer dude Jun 24 '18 at 09:07
  • ISO/IEC 14882 [expr.post.incr] says: _The value of a postfix ++ expression is the value of its operand._ i.e. the value before it is incremented. – Adrian W Jun 24 '18 at 09:23