bhylu.com

Advertisements

C++ Variables and Initialization

Represent minutes as whole values and reject a lossy initialization before it becomes a hidden conversion.

How it works

Choose a representation from the meaning of the data. Whole minutes fit an integer in this small route, while a measured fractional distance may use double. A variable owns a value of its declared type. Brace initialization rejects many narrowing conversions, helping catch accidental loss of a fraction or range. It does not prevent every later overflowing expression or unit mismatch. Keep units in names so two plain integer objects do not silently mix minutes and seconds.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror values-units.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · values-units.cpp

#include <iostream>

int main() {
    int travel_minutes{18};
    int unloading_minutes{7};
    const int reserve_minutes{5};
    int planned_minutes{travel_minutes + unloading_minutes + reserve_minutes};
    std::cout << "Planned: " << planned_minutes << " minutes\n";
}

Expected result

Planned: 30 minutes

All operands use the same unit and the fixed values fit every conforming int. const makes reserve nonmodifiable through its name. A declaration such as int minutes{2.5} is rejected for narrowing; it is intentionally not included as runnable source. Larger accepted inputs require range checks before arithmetic, not only a different initialization style.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.