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:#

  1. Header Inclusion:

    #include <print>
    
    • The <print> header is part of the C++23 standard library. It provides the println function, which allows formatted output similar to Python’s print function.

  2. Namespace:

    using namespace std;
    
    • This allows the program to use standard library features (like println) without needing to prefix them with std::.

  3. Variable Declaration:

    int alice_age{ 9 };
    
    • A variable alice_age of type int is declared and initialized with the value 9.

  4. 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 println statement outputs the initial value of alice_age (9).

    • Reference Declaration:

      int& alice_age_ref = alice_age;
      
      • alice_age_ref is declared as a reference to alice_age. This means alice_age_ref is an alias for alice_age and refers to the same memory location.

    • Modification via Reference:

      alice_age_ref = 10;
      
      • The value of alice_age is updated to 10 through the reference alice_age_ref.

    • Final Output:

      • The second println statement outputs the updated value of alice_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 println function uses {} as placeholders for variables, similar to Python’s f-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