References - &
Lesson 8 of 14 in Coddy's C++ Pointers course.
References are a special kind of variable that represents an alternative name (alias) of an already existing variable. After the reference is defined to refer to a certain variable, that variable can be accessed with its name or with the reference.
References are particularly useful when you want to modify the original variable within a function or when passing large structures efficiently. They allow you to work with that variable directly without needing to use pointers.
int a = 10;
int &ref = a; // ref is a reference to a
ref = 20; // Changes the value of a to 20
cout << "a = " << a;Output:
a = 20References work very similarly to pointers, but they are a different approach to changing a variable's data without using the variable itself, they are very useful when using functions which you will see in the next lesson
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou will be given two numbers, and input them into the variables a and b accordingly. Create a reference refA that refers to a and a reference refB that refers to b. Multiply refA by 4, and subtract a from refB
Note: Do NOT change the default code
Try it yourself
#include <iostream>
using namespace std;
int main() {
// Enter your code here
// DO NOT CHANGE THE CODE BELOW
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "refA = " << refA << endl;
cout << "refB = " << refB << endl;
// DO NOT CHANGE THE CODE ABOVE
}All lessons in C++ Pointers
2Pointers & References
Pointers as ParametersReferences - &References as ParametersPointers vs References