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 theprintln
function, which is used for formatted output similar to Python’sprint
function.
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;
PI
is defined as a constant of typedouble
. Theconst
keyword 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
main
function:APPROX_E
is declared as a constant usingauto const
. Theauto
keyword deduces its type asint
based on the assigned value3
.The
println
function is used to print a formatted string. The placeholders{}
are replaced with the values ofPI
andAPPROX_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