int a = 2, b = 3; Swap(a, b); // a and b have swapped values cout << a << b; // 3 and 2
void Swap(int x, int y) { int temp = x; x = y; y = temp; }
x
and y
,
the values of a
and b
in the function call
would remain unchanged
int a = 2, b = 3; Swap(a, b); // a and b have NOT swapped values! cout << a << b; // 2 and 3
Swap
function work, we need to put &
in
front of the parameter names
so they become reference parameters
void Swap(int &x, int &y) { int temp = x; x = y; y = temp; }
x
will change a
, and modifying y
will
change b
)
// Won't work because literals cannot change value or be passed by reference! Swap(2, 3); // This works because variables are used as arguments Swap(a, b);
void AddOne(int x, int &y) { x++; y++; } void main() { int a = 2, b = 2; AddOne(a, b); cout << a << b; // 2 and 3 }
AddOne
:2 | 2 |
main: a | main: b |
AddOne
:2 | 2 | 2 |
main: a | main: b AddOne: y |
AddOne: x |
x
and y
in AddOne
:2 | 3 | 3 |
main: a | main: b AddOne: y |
AddOne: x |
AddOne
:2 | 3 |
main: a | main: b |
a
's value did not change because it was passed by value,
but b
's value changed because it was passed by reference
// This function adds one to coke_votes if the incoming vote is C or c, // or it adds one to pepsi_votes if the vote is P or p void CountVote(char vote, int &coke_votes, int &pepsi_votes) { vote = toupper(vote); if (vote == 'C') coke_votes++; else if (vote == 'P') pepsi_votes++; } void main() { int coke_votes = 0, pepsi_votes = 0; char vote; cout << "Enter a vote for Coke or Pepsi (C or P): "; cin >> vote; CountVote(vote, coke_votes, pepsi_votes); }