Variables, Scopes and Namespaces: Swap#
Adapted from: “Learn Modern C++” by cpptutor: Learn Modern C++: Variables, Scopes and Namespaces
Program that Demonstrates Variable Swapping and Implicit Casting#
// 02-swap.cpp : attempt to swap the values of an int and a double
#include <print>
using namespace std;
int main() {
int a = 1;
double b = 2.5;
println("(1) a = {}, b = {}", a, b);
a = 2.5;
b = 1;
println("(2) a = {}, b = {}", a, b);
}
Explanation of the Above Code#
The program attempts to swap the values of an
intand adouble.The first line of the
mainfunction initializes anintvariableawith the value1and adoublevariablebwith the value2.5.The program prints the values of
aandbusing theprintlnfunction.The second line of the
mainfunction attempts to assign the value2.5(adouble) to theintvariablea, which results in an implicit cast.The program then attempts to assign the value
1(anint) to thedoublevariableb, which is valid.Finally, the program prints the values of
aandbagain.The output of the program will show the values of
aandbbefore and after the swap attempt.The implicit cast from
doubletointwill truncate the decimal part, and the output will reflect this.The program demonstrates the concept of variable swapping and the behavior of implicit casting in C++.
The program also highlights the importance of understanding variable types and their scopes in C++.
The program uses the
printlibrary for output, which is a modern C++ feature.
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-swap.cpp -o /app/02-swap
/app/02-swap.cpp:10:9: warning: implicit conversion from 'double' to 'int' changes value from 2.5 to 2 [-Wliteral-conversion]
10 | a = 2.5;
| ~ ^~~
1 warning generated.
Use Docker to Run Executable in a C++23 Environment#
!docker run --rm -v $(pwd):/app cpp23-clang18:latest ./02-swap
(1) a = 1, b = 2.5
(2) a = 2, b = 1