Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Variables, Scopes and Namespaces: Assign

---
jupytext:
  formats: md:myst
  text_representation:
    extension: .md
    format_name: myst
kernelspec:
  display_name: Python 3
  language: python
  name: python3
---

Variables, Scopes and Namespaces: Assign

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

Program that Demonstrates Variable Assignments

// 02-assign.cpp : assigns to local variables

#include <print>
using namespace std;

int main()
{
    int i = 1, j = 2;
    unsigned k;
    println("(1) i= {}, j= {}, k= {}", i, j, k);
    i = j;
    j = 3;
    k = -1;
    println("(2) i= {}, j= {}, k= {}", i, j, k);
}

Explanation of the Above Code

The above program is compiled and run using clang-18 in a Docker container. This is done so that the installation of a C++23 compiler is not required. The Docker container is based on the Ubuntu 22.04 image and includes clang-18, which supports C++23 features.

The program demonstrates the assignment of values to local variables. The variables i, j, and k are declared as integers, and their values are assigned using the assignment operator =. The program prints the values of these variables before and after the assignments.

The first print statement shows the initial values of i, j, and k. The second print statement shows the values after the assignments. The variable k is assigned a negative value, which is allowed because it is declared as an unsigned integer. However, this may lead to unexpected behavior if not handled properly.

The program uses the println function to print the values of the variables. The println function is a custom function that formats the output using the std::format library. This allows for easy formatting of strings and variables in C++23.

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

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

!docker run --rm -v $(pwd):/app cpp23-clang18:latest ./02-assign
(1) i= 1, j= 2, k= 32766
(2) i= 2, j= 3, k= 4294967295