I want to have a explanation with respect to variable created on stack memory, what is the difference between pointer and reference. I understand in the case of calling by pointer, for example, the following things are happening.
#include <iostream>
using namespace std;
void swap(int *x, int *y){
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int main(){
int i1 = 3, i2 = 7;
swap (&i1,&i2);
return 0;
}
- Two variables i1, i2 are created on stack framed to the main function.
- at calling 'swap' function, two more variables x, y, are created on stack, framed to the 'swap function. These two variables are initialized at the address of i1 and i2.
- a temp variable is created on stack framed to 'swap' function. All of x,y,temp disappear after 'swap'.
Could someone explain in a similar way what happens when I use 'call by reference'? In particular, is there a variable x and y created on stack when calling 'swap'? If so, what are they?
#include <iostream>
using namespace std;
void swap(int &x, int &y){
int temp;
temp = x;
x = y;
y = temp;
}
int main(){
int i1 = 3, i2 = 7;
swap (i1,i2);
return 0;
}
Thank you!