Variables, Scopes and Namespaces: Scopes#

Adapted from: “Learn Modern C++” by cpptutor: Learn Modern C++: Variables, Scopes and Namespaces

Program that Demonstrates Scopes#

// 02-scopes.cpp : define three variables with the same name in one program
 
#include <print>
using namespace std;
 
auto a{ 1.5f };
 
int main() {
    println("(1) {}", a);
    auto a{ 2u };
    println("(2) {}", a);
    {
        auto a{ 2.5 };
        println("(3) {}", a);
    }
}

Explanation of the Above Code#

This C++ code demonstrates the concept of variable scopes by defining three variables with the same name (a) in different scopes. Here’s an explanation:

Code Breakdown:#

#include <print>
using namespace std;
  • The <print> header is used for formatted output (similar to std::format in C++20). It allows the use of println for printing formatted strings.

  • using namespace std; allows direct access to standard library functions without prefixing them with std::.

auto a{ 1.5f };
  • A global variable a is defined with a value of 1.5f (a floating-point literal). This variable is accessible throughout the program unless shadowed by a local variable.

int main() {
    println("(1) {}", a);
  • Inside the main function, the global variable a is accessed and printed. The output will be:

    (1) 1.5
    
    auto a{ 2u };
    println("(2) {}", a);
  • A local variable a is defined within the main function, shadowing the global variable a. This local variable is an unsigned integer (2u).

  • The local a is printed, and the output will be:

    (2) 2
    
    {
        auto a{ 2.5 };
        println("(3) {}", a);
    }
  • A new block scope is introduced with {}. Inside this block, another local variable a is defined, shadowing the a from the outer scope. This variable is a double (2.5).

  • The innermost a is printed, and the output will be:

    (3) 2.5
    

Key Concepts:#

  1. Global Scope: The first a is defined globally and is accessible unless shadowed by a local variable.

  2. Local Scope: The second a is defined within the main function, shadowing the global a.

  3. Block Scope: The third a is defined within a block inside main, shadowing the a from the main function.

Output:#

The program will produce the following output:

(1) 1.5
(2) 2
(3) 2.5

This demonstrates how variables with the same name can coexist in different scopes without conflict, as each scope has its own “view” of the variable.

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-scopes.cpp -o /app/02-scopes

Use Docker to Run Executable in a C++23 Environment#

!docker run --rm -v $(pwd):/app cpp23-clang18:latest ./02-scopes
(1) 1.5
(2) 2
(3) 2.5