I'm having a hard time understanding how this example from the w3schools tutorial works.
#include <iostream>
using namespace std;
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
system("pause");
return 0;
}
I think I understand the first part:
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
I'm basically referencing whatever x and y are going to be when I call the function. So x is going to be "pointing" to firstNum and y is going to be pointing to secondNum. It's going to do the switcheroo using a third variable as a placeholder.
However, after I call the function swapNums(firstNum, secondNum);, I don't understand how the function with its local variables has the ability to change the values of int firstNum = 10; and int secondNum = 20;.
My understanding is that variables within a function are "local" and the scope of said variables only extend within the function itself. How do the local variables change other variables outside their own function without any return statements?