Why does this version of the 'swap ints' program work?

Why does this program work?/


#include <iostream>

using namespace std;

void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}

int main () {
cout << "Enter two integers: ";
int x, y;
cin >> x >> y;

swap (x, y);
cout << "x = " << x << endl;
cout << "y = " << y << endl;
}

swap takes the addresses of two ints.

So if:

x has value 100 and is located at memory address 5
y has value 200 and is located at memory address 10

100 and 200 should be passed into swap as memory addresses and thus swap may be even accessing to memory that hasn't even been declared yet. But somehow, I am guessing that the addresses of x & y are passed in somehow (5 for x and 10 for y in this example).

Can you please explain where my logic is wrong? My logic tells me this program should not work.

Thanks!
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

void swap(int &a, int &b) {//swap takes int references (the addresses of the ints)
int temp = a;                   //this allows the original variables (x and y below) to be changed.
a = b;
b = temp;
}

int main () {
cout << "Enter two integers: ";
int x, y;//variables are declared and allocated in memory (they have addresses)
cin >> x >> y;//unless this fails the variables are initialized

swap (x, y);
cout << "x = " << x << endl;
cout << "y = " << y << endl;
}

See comments.
Last edited on
Thanks I understand it better!

I don't know if someone would want to do this, but how would you pass in the memory address to a function?

i.e. do what I said here: " .... 100 and 200 should be passed into swap as memory addresses and thus swap may be even accessing to memory that hasn't even been declared yet. ... "
Topic archived. No new replies allowed.