-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReferenceVSValuePassing.cpp
More file actions
27 lines (21 loc) · 1001 Bytes
/
ReferenceVSValuePassing.cpp
File metadata and controls
27 lines (21 loc) · 1001 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
void swap(std::string &x, std::string &y);
int main()
{
std::string x = "Kool-Aid";
std::string y = "Water";
//swap(x, y); pass by value, wont swap these local variables (assuming swap function didnt add &)
swap(x, y); // pass by reference, will swap these local variables (assuming swap function added &)
std::cout << "x: " << x << '\n'; // prints the variable stored at the memeory address
std::cout << "y: " << y << '\n'; // prints the variable stored at the memeory address
return 0;
}
//normally when you pass a variable to a function it passes the value of that variable, not the memory address of that variable
// this means that if you change the value of the variable in the function it will not change the value of the variable in the main function
void swap(std::string &x, std::string &y)
{
std::string temp;
temp = x; // temp is a copy of x
x = y; // x is now equal to y
y = temp; // y is now equal to temp
}