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: Constants

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

Variables, Scopes and Namespaces: Constants

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

Program that Demonstrates Constants

// 02-constants.cpp : introducing the const keyword
 
#include <print>
using namespace std;
 
const double PI = 3.14159265358979;
 
int main() {
    auto const APPROX_E = 3;
    println("pi is almost exactly {}, while e is approximately {}",
        PI, APPROX_E);
}

Explanation of the Above Code

This C++ code demonstrates the use of the const keyword to define constants and the use of the println function for formatted output.

Code Explanation:

  1. Header Inclusion:

    #include <print>
    • The <print> header is part of the C++23 standard library. It provides the println function, which is used for formatted output similar to Python’s print function.

  2. Namespace:

    using namespace std;
    • This allows the program to use standard library features (like println) without needing to prefix them with std::.

  3. Constant Definition:

    const double PI = 3.14159265358979;
    • PI is defined as a constant of type double. The const keyword ensures that its value cannot be modified after initialization.

  4. Main Function:

    int main() {
        auto const APPROX_E = 3;
        println("pi is almost exactly {}, while e is approximately {}", PI, APPROX_E);
    }
    • Inside the main function:

      • APPROX_E is declared as a constant using auto const. The auto keyword deduces its type as int based on the assigned value 3.

      • The println function is used to print a formatted string. The placeholders {} are replaced with the values of PI and APPROX_E.

Output:

When executed, the program will output:

pi is almost exactly 3.14159265358979, while e is approximately 3

Key Concepts:

  • const Keyword: Used to define immutable variables.

  • auto Keyword: Automatically deduces the type of a variable.

  • Formatted Output: The println function simplifies printing formatted strings 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-constants.cpp -o /app/02-constants

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

!docker run --rm -v $(pwd):/app cpp23-clang18:latest ./02-constants
pi is almost exactly 3.14159265358979, while e is approximately 3