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?
Try this
#include <iostream>
void change_val_by_ref(int &x)
{
x=100
}
void change_val_by_val(int x)
{
x=50;
}
int main()
{
int whatever=0;
std::cout<<"Original value: "<<whatever<<"\n";
change_val_by_ref(whatever);
std::cout<<"After change by ref: "<<whatever<<"\n";
change_val_by_val(whatever);
std::cout<<"After change by val: "<<whatever<<"\n";
}
The output you will see is:
0
100
100
Let's see what happened
change_val_by_ref
changed the original whatever
, because the ref
was "pointing" to the VARIABLE.change_val_by_val
didn't change the whatever
, because the argument of the function x
has just copied the value of whatever
, and anything that happens to x
will not affect whatever
, because they are not related.That's the point of passing by ref.