Small Steps V — Making Your Own Types
Naming the original instead of copying
Name the original instead of copying it.
What you will learn
A reference is another name for an existing object. An int& parameter refers to the original integer passed in.
Try it
Example · example1.cpp
void add_one(int x)
{
x = x + 1;
print("Inside: ", x);
}
void small_main()
{
int n = 10;
add_one(n);
print("Outside: ", n);
}
First run the example: it prints Inside: 11 and Outside: 10. Change add_one(int x) to add_one(int& x) and run again. Now both are 11.
Initially x was a copy; after adding &, it is another name for n. Use this when you intend to change the original.
Exercise
Create swap(int& a, int& b) to exchange the original values of two ints.
Exercise starter · exercise1_starter.cpp
void swap(int& a, int& b)
{
// swap the original values.
}
void small_main()
{
int x = 3;
int y = 7;
swap(x, y);
print(x, ", ", y);
}
Hint
Save a temporarily in temp, then assign a=b and b=temp.
show solution
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
void small_main()
{
int x = 3;
int y = 7;
swap(x, y);
print(x, ", ", y);
}