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#

  1. The program attempts to swap the values of an int and a double.

  2. The first line of the main function initializes an int variable a with the value 1 and a double variable b with the value 2.5.

  3. The program prints the values of a and b using the println function.

  4. The second line of the main function attempts to assign the value 2.5 (a double) to the int variable a, which results in an implicit cast.

  5. The program then attempts to assign the value 1 (an int) to the double variable b, which is valid.

  6. Finally, the program prints the values of a and b again.

  7. The output of the program will show the values of a and b before and after the swap attempt.

  8. The implicit cast from double to int will truncate the decimal part, and the output will reflect this.

  9. The program demonstrates the concept of variable swapping and the behavior of implicit casting in C++.

  10. The program also highlights the importance of understanding variable types and their scopes in C++.

  11. The program uses the print library 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