0

The difference between passing by value and passing by reference is that unlike passing by values, when we are passing by reference, the address of the declared in one function gets passed to another.

void func(int& a){
    a *= 4;
    return;
}

int main(){
    int n = 3;
    func(n);
    std::cout << n << std::endl; //displays 12
}

In this case, n will be created and stored in the stack right? When we pass by reference, does the address pointing to n in the stack be passed to func? If so, how is it possible to access a variable from a different stack frame?

  • Usually we have only one stack per thread. So, in your case, it will be the same stack area – A M Jan 26 '21 at 19:36
  • 2
    The stack frame of `main` still exists while `func` is running, so local variables in `main` still exist and have not gone out of scope.. Assuming that your compiler implements references in terms of pointers then essentially the address of `n` is passed to `func`. – jkb Jan 26 '21 at 19:40
  • You access variables from different stack frames by passing the address along to each function that needs to make a change. In truth, the compiler has the option of leaving that value in a register and just passing that register along instead, but to you the programmer, it will still appear the same as if it were an address. – Michael Dorgan Jan 26 '21 at 19:40

0 Answers0