---
jupytext:
formats: md:myst
text_representation:
extension: .md
format_name: myst
kernelspec:
display_name: Python 3
language: python
name: python3
---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 tostd::formatin C++20). It allows the use ofprintlnfor printing formatted strings.using namespace std;allows direct access to standard library functions without prefixing them withstd::.
auto a{ 1.5f };A global variable
ais defined with a value of1.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
mainfunction, the global variableais accessed and printed. The output will be:(1) 1.5
auto a{ 2u };
println("(2) {}", a);A local variable
ais defined within themainfunction, shadowing the global variablea. This local variable is an unsigned integer (2u).The local
ais 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 variableais defined, shadowing theafrom the outer scope. This variable is a double (2.5).The innermost
ais printed, and the output will be:(3) 2.5
Key Concepts:¶
Global Scope: The first
ais defined globally and is accessible unless shadowed by a local variable.Local Scope: The second
ais defined within themainfunction, shadowing the globala.Block Scope: The third
ais defined within a block insidemain, shadowing theafrom themainfunction.
Output:¶
The program will produce the following output:
(1) 1.5
(2) 2
(3) 2.5This 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-scopesUse 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