Variables, Scopes and Namespaces: References#
Adapted from: “Learn Modern C++” by cpptutor: Learn Modern C++: Variables, Scopes and Namespaces
Program that Demonstrates References#
// 02-references.cpp : introducing l-value references
#include <print>
using namespace std;
int alice_age{ 9 };
int main() {
println("Alice\'s age is {}", alice_age);
int& alice_age_ref = alice_age;
alice_age_ref = 10;
println("Alice\'s age is now {}", alice_age);
}
Explanation of the Above Code#
This C++ code demonstrates the concept of l-value references and how they can be used to modify variables indirectly.
Code Breakdown:#
Header Inclusion:
#include <print>
The
<print>header is part of the C++23 standard library. It provides theprintlnfunction, which allows formatted output similar to Python’sprintfunction.
Namespace:
using namespace std;
This allows the program to use standard library features (like
println) without needing to prefix them withstd::.
Variable Declaration:
int alice_age{ 9 };
A variable
alice_ageof typeintis declared and initialized with the value9.
Main Function:
int main() { println("Alice's age is {}", alice_age); int& alice_age_ref = alice_age; alice_age_ref = 10; println("Alice's age is now {}", alice_age); }
Formatted Output:
The first
printlnstatement outputs the initial value ofalice_age(9).
Reference Declaration:
int& alice_age_ref = alice_age;
alice_age_refis declared as a reference toalice_age. This meansalice_age_refis an alias foralice_ageand refers to the same memory location.
Modification via Reference:
alice_age_ref = 10;
The value of
alice_ageis updated to10through the referencealice_age_ref.
Final Output:
The second
printlnstatement outputs the updated value ofalice_age(10).
Key Concepts:#
L-value Reference:
An l-value reference (
int&) allows you to create an alias for an existing variable. Any changes made to the reference directly affect the original variable.
Formatted Output:
The
printlnfunction uses{}as placeholders for variables, similar to Python’sf-strings.
Output:#
When executed, the program will produce the following output:
Alice's age is 9
Alice's age is now 10
Compile and Run Code#
Use Python to Change to Working Directory#
import os
root_dir = os.getcwd()
code_dir = root_dir + "/" + "Cpp_Code/02_Variables_Scopes_and_Namespaces"
os.chdir(code_dir)
Use Docker to Compile the Code in a C++23 Environment#
!docker run --rm -v $(pwd):/app cpp23-clang18:latest clang++-18 -std=c++23 -stdlib=libc++ /app/02-references.cpp -o /app/02-references
Use Docker to Run Executable in a C++23 Environment#
!docker run --rm -v $(pwd):/app cpp23-clang18:latest ./02-references
Alice's age is 9
Alice's age is now 10