bhylu.com

Advertisements

C++ Functions

Extract a duration calculation into a named operation and give default arguments a stable meaning.

How it works

A function declaration states the parameter and result types used to check a call. A definition supplies its body. Pass small scalar values by value and return the computed result when there is one natural output. A default argument supplies an omitted argument at the call site; it is not a separate runtime configuration store. Keep defaults in one shared declaration so different callers do not accidentally compile with different assumptions. This helper requires small nonnegative durations whose sum fits int.

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 function-contracts.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 · function-contracts.cpp

#include <iostream>

int planned_minutes(int travel, int unloading, int reserve = 5) {
    return travel + unloading + reserve;
}

int main() {
    std::cout << "Default reserve: " << planned_minutes(18, 7) << '\n';
    std::cout << "Custom reserve: " << planned_minutes(18, 7, 8) << '\n';
}

Expected result

Default reserve: 30
Custom reserve: 33

The first call uses the declared reserve of five; the second supplies eight. Parameters receive copies of the input values, so assigning a parameter would not change its caller variable. A reusable public duration operation should enforce its domain rather than relying on fixed fixtures. Keep side effects separate from an otherwise pure calculation to make tests easy to explain.

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.

Advertisements