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::format
in C++20). It allows the use ofprintln
for printing formatted strings.using namespace std;
allows direct access to standard library functions without prefixing them withstd::
.
auto a{ 1.5f };
A global variable
a
is 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
main
function, the global variablea
is accessed and printed. The output will be:(1) 1.5
auto a{ 2u };
println("(2) {}", a);
A local variable
a
is defined within themain
function, shadowing the global variablea
. 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 variablea
is defined, shadowing thea
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:#
Global Scope: The first
a
is defined globally and is accessible unless shadowed by a local variable.Local Scope: The second
a
is defined within themain
function, shadowing the globala
.Block Scope: The third
a
is defined within a block insidemain
, shadowing thea
from themain
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