0
0
C++programming~10 mins

Reference declaration in C++ - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Reference declaration
Declare variable
Declare reference with &
Reference points to variable
Use reference as alias
Changes via reference affect original variable
This flow shows how a reference is declared to alias an existing variable and how changes through the reference affect the original variable.
Execution Sample
C++
int x = 10;
int& ref = x;
ref = 20;
std::cout << x;
This code declares an integer x, a reference ref to x, changes x via ref, and prints x.
Execution Table
StepActionVariable xReference refOutput
1Declare x = 1010--
2Declare ref as reference to x10alias to x-
3Assign ref = 20 (changes x)20alias to x-
4Print x20alias to x20
💡 Program ends after printing x which is now 20 due to reference assignment
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
xundefined10102020
refundefinedundefinedalias to xalias to xalias to x
Key Moments - 2 Insights
Why does changing 'ref' also change 'x'?
Because 'ref' is a reference (alias) to 'x', any assignment to 'ref' actually changes 'x' as shown in step 3 of the execution_table.
Can a reference be changed to refer to another variable after declaration?
No, once a reference is set to a variable (step 2), it cannot be changed to refer to another variable. It always aliases the original variable.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the value of x?
A10
B20
Cundefined
Dref
💡 Hint
Check the 'Variable x' column at step 3 in the execution_table.
At which step does 'ref' become an alias to 'x'?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Reference ref' column in the execution_table to see when it becomes 'alias to x'.
If we assign 'ref = 30;' after step 3, what will be the value of x?
Aundefined
B20
C30
Dref
💡 Hint
Since 'ref' aliases 'x', assigning to 'ref' changes 'x' as shown in the variable_tracker.
Concept Snapshot
Reference declaration syntax: int& ref = variable;
A reference is an alias to an existing variable.
Changing the reference changes the original variable.
References must be initialized when declared.
References cannot be reseated to another variable.
Full Transcript
This example shows how to declare a reference in C++. First, we declare an integer variable x with value 10. Then, we declare a reference ref to x using int& ref = x;. The reference ref acts as another name for x. When we assign 20 to ref, it changes the value of x to 20. Finally, printing x outputs 20. The key idea is that references alias variables and any changes through the reference affect the original variable. References must be initialized when declared and cannot be changed to alias another variable later.