Reputation: 289
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?
Upvotes: 4
Views: 709
Reputation: 36607
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.*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)++
.Upvotes: 1
Reputation: 15446
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++?
Upvotes: 2