Click here to Skip to main content
15,041,266 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

C++
void incr(int* &f)
{
    f++;
}

int main ()
{

    int *i = 0;
    std::cout<<"i ="<<i;
    incr(i);
    std::cout<<"i ="<<i;

  return 0;
}


I am surprised looking at underlined code, int* &f. Can you explain meaning of this line.
Posted

That's not a pointer to a reference, that's a reference to a pointer.
   
v2
Comments
[no name] 31-Mar-12 4:36am
   
Thx 5!
The other way around: f is a reference to a pointer. Did you run your example? What you certainly saw is that i is incremented by 4 in the call to incr. That's probably the point to be demonstrated here. f is a reference to a pointer to int, so it behaves like a pointer to int. When you increment it, its value will increase by the number of bytes that equals the size of an int on your computer - usually 4 on 32-bit systems.

Only by passing f by reference made it possible that the change to f is visible in main at all. If you pass it by value like in

void incr(int* f)
{
    f++;
}


f would be incremented, but main would not see the change, as it never would get back there.
   
Comments
[no name] 31-Mar-12 4:46am
   
Correct.. 5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900