0

Why I can't re-set the value of a reference but I can do that if the reference is a function parameter? For example the following code will work without a problem:

void foo(int& i)
{
}

int main()
{
    int i; foo(i);
    int j; foo(j);

    return 0;
}
  • You can do the same in both cases. But you're not changing the reference, you're changing the object it refers to. Your code doesn't exhibit the issue you're asking about. – user207421 Feb 01 '15 at 03:05
  • 1
    What is the thing that surprises you? The program you are showing successfully does nothing as one would expect. Also please check your wording. Do you mean *“can”* or *“can not”*? And what does “re-set the value of a reference” mean? – 5gon12eder Feb 01 '15 at 03:06
  • @EJP based on this question: http://stackoverflow.com/questions/728233/why-are-references-not-reseatable-in-c, you can't re-set the reference value, but when it is a function parameter, you can call the function multiple times with different value for the reference parameter. –  Feb 01 '15 at 03:16

1 Answers1

1

There is no 'reference parameter re-set' here. The function reference formal parameter doesn't even exist until you call the function, with a new actual argument value and possibly a new location on the stack every time you call it. Every time you call the function you are initializing a new reference (to be passed as the actual argument value), just as you would be with int &k = i; in the main() of your example.

user207421
  • 305,947
  • 44
  • 307
  • 483