4

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
LiLian
  • 289
  • 2
  • 14
  • Does this answer your question? [What is a reference variable in C++?](https://stackoverflow.com/questions/2765999/what-is-a-reference-variable-in-c) – mmackliet Aug 26 '20 at 01:46

2 Answers2

2

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?

int &j is declaring a variable j, of type int&, or integer reference (see What is a reference variable in C++?).

int &j = *i is assigning the value at address i to the reference variable j. So whenever you modify j, you'll be modifying *i (and vice versa).

See also: What are the differences between a pointer variable and a reference variable in C++?

scohe001
  • 15,110
  • 2
  • 31
  • 51
1

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)++.
Peter
  • 35,646
  • 4
  • 32
  • 74