-7
#include<iostream>
using namespace std;
int main()
{

    int x=7;
    int *p=&x;
    int *p1=&++x;
    int *p2=&x++;
    int *p3=&(++x);
    int *p4=&(x++);
    cout<<p<<endl<<p1<<endl<<p2<<endl<<p3<<endl<<p4<<endl<<*p<<endl<<*p++<<endl<<*++p<<endl<<*(p++)<<endl<<*(++p)<<endl;
    return 0;
}

p2 and p4 return error. Also, can you please explain the dereferencing of all the increments of the pointer, p, that I print in the cout statement?

  • 1
    When asking questions about error, share the error as well – Arun A S Dec 10 '17 at 10:55
  • Possible duplicate of [Post-increment and Pre-increment concept?](https://stackoverflow.com/questions/4445706/post-increment-and-pre-increment-concept) – CIsForCookies Dec 10 '17 at 10:55
  • 1
    Hint: consider which increment operators return the original x and which make a copy to be returned. – Paul Floyd Dec 10 '17 at 10:57
  • And the strange output is because of this [Behavior of post increment in cout](https://stackoverflow.com/questions/3986361/behavior-of-post-increment-in-cout) – Bo Persson Dec 10 '17 at 11:01

1 Answers1

3

The problem here is not the pointers. It's the action of taking addresses of variables (on the RHS of the assignment operations).

The operator & can only be used on lvalues. When you post-increment a variable, the value of the expression is an rvalue, which is not eligible to be taken address.

Reference from CppReference (linked above):

lvalue

  • ++a and --a, the built-in pre-increment and pre-decrement expressions;

prvalue

  • a++ and a--, the built-in post-increment and post-decrement expressions;

And below:

lvalue

Properties:

  • Address of an lvalue may be taken: &++i and &std::endl are valid expressions.

rvalue

  • Address of an rvalue may not be taken: &int(), &i++, &42, and &std::move(x) are invalid
iBug
  • 35,554
  • 7
  • 89
  • 134