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:#
Header Inclusion:
#include <print>
The
<print>header is part of the C++23 standard library. It provides theprintlnfunction, which is used for formatted output similar to Python’sprintfunction.
Namespace:
using namespace std;
This allows the program to use standard library features (like
println) without needing to prefix them withstd::.
Constant Definition:
const double PI = 3.14159265358979;
PIis defined as a constant of typedouble. Theconstkeyword ensures that its value cannot be modified after initialization.
Main Function:
int main() { auto const APPROX_E = 3; println("pi is almost exactly {}, while e is approximately {}", PI, APPROX_E); }
Inside the
mainfunction:APPROX_Eis declared as a constant usingauto const. Theautokeyword deduces its type asintbased on the assigned value3.The
printlnfunction is used to print a formatted string. The placeholders{}are replaced with the values ofPIandAPPROX_E.
Output:#
When executed, the program will output:
pi is almost exactly 3.14159265358979, while e is approximately 3
Key Concepts:#
constKeyword: Used to define immutable variables.autoKeyword: Automatically deduces the type of a variable.Formatted Output: The
printlnfunction 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