Lesson 2 of 46
Lesson Progress: 0%
A reference in C++ is an alias for an existing variable. Once you bind a reference to a variable, you can use the reference name just like the original. References cannot be null and must be initialized when declared. They provide a simpler and safer alternative to pointers for many tasks. This lesson covers declaring references, modifying values through references, and how multiple references can point to the same variable. Understanding references is an important step toward writing effective C++ code.
#include <iostream>
using namespace std;
int main() {
int x = 10;
int& ref = x;
cout << x << " " << ref;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
int& ref = x — the & after the type marks it as a reference.ref and x refer to the same memory location.#include <iostream>
using namespace std;
int main() {
int x = 10;
int& ref = x;
ref = 25;
cout << x;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
ref = 25 updates x because ref is just another name for x.#include <iostream>
using namespace std;
int main() {
int x = 7;
int& r1 = x;
int& r2 = x;
r1 = 14;
cout << r2;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
r1 and r2 are both aliases for x.r1 updates x, and reading r2 reflects the new value.#include <iostream>
using namespace std;
int main() {
double pi = 3.14;
double& ref = pi;
cout << ref;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
double.ref acts exactly like the original pi.ref directly accesses the same memory.#include <iostream>
using namespace std;
int main() {
string msg = "Hi";
string& ref = msg;
cout << ref;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
string.ref is an alias for msg.ref outputs the value of the original msg.#include <iostream>
using namespace std;
int main() {
int x = 5;
int& ref = x;
x = x + 10;
cout << ref;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
x = x + 10, x becomes 15, so ref outputs 15.Test Incomplete