Confuse about & and * in the C++

Viewed 417

I just learned C++, and I don't understand the below:

The code part:

int *i = new int;
*i = 0;
int &j = *i;
j++;

Question: which the meaning of the last line: j++?
Answer: Increments the value pointed to by i by one.

My confusion:
I am not sure the meaning of int &j = *i;

What's the relationship between j and pointer i? j is the pointer or other?

2 Answers

I am not sure the meaning of int &j = *i;

i has been previously initialised as a pointer to a (dynamically allocated using operator new) int. *i is a reference to that same dynamically allocated int.

In the declaration, int &j declares j to be a reference to an int. The = *i causes j to be a reference to the same int as *i.

In subsequent code where j is visible, j is now a reference to (an alternative name, or an alias, for) the int pointed to by i.

Any operation on j will affect that int, in exactly the same way that doing that same operation on *i would.

So, j++ has the effect of post-incrementing *i.

Be aware of rules of operator precedence and associativity though.

  • ++*i and ++j are equivalent because the pre-increment (prefix ++) and * (for pointer dereference) have the same precedence and associativity.
  • However, *i++ is NOT equivalent to j++, since post-increment (postfix ++) has higher precedence than the *. So *i++ is equivalent to *(i++) but j++ is equivalent to (*i)++.
Related