I'm practicing C++, and facing the Pass-by-value/reference topic. What I learned from BroCode is that, when we call a swap function by the parameters' value, both of their memory_addresses will be different from the original ones.
#include <iostream>
using std::cout;
using std::endl;
void swap_byValue(int dog, int cat);
void swap_byReference(int &dog, int &cat);
void print(int dog, int cat);
int main(){
int dog = 100;
int cat = 999;
cout << "*****************************" << endl
<< "* variable_name * value *" << " (memory_address)" << endl;
print(dog, cat);
swap_byValue(dog, cat);
print(dog, cat);
return 0;
}
void swap_byValue(int dog, int cat){
int temp;
temp = dog;
dog = cat;
cat = temp;
}
void swap_byReference(int &dog, int &cat){
int temp;
temp = dog;
dog = cat;
cat = temp;
}
void print(int dog, int cat){
cout << "*****************************" << "-----> " << &dog << endl
<< "* dog * " << dog << " *" <<endl
<< "*****************************" << "-----> " << &cat << endl
<< "* cat * " << cat << " *" <<endl;
}
The result after running is down below:
*****************************
* variable_name * value * (memory_address)
*****************************-----> 0x42295ffc30
* dog * 100 *
*****************************-----> 0x42295ffc38
* cat * 999 *
*****************************-----> 0x42295ffc30
* dog * 100 *
*****************************-----> 0x42295ffc38
* cat * 999 *
But shouldn't the memory-address of variable dog(before swapping) differ from variable dog(after swapping)? They're both 0x42295ffc30 right now. Is there anything I misunderstood or did wrong? Thanks a lot.