C++ Basics: Clamp a Setting and Store the Result by Value
Bound an integer setting with std::clamp while avoiding a reference to temporary bounds.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as clamp-copy-result-demo.cpp:
#include <algorithm>
#include <iostream>
int main()
{
for (int requested : {-5, 40, 120}) {
const int accepted = std::clamp(requested, 0, 100);
std::cout << requested << " -> " << accepted << '\n';
}
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic clamp-copy-result-demo.cpp -o clamp-copy-result-demo &&
./clamp-copy-result-demoObserved output:
-5 -> 0
40 -> 40
120 -> 100Read the result
Values below zero become zero, values above 100 become 100, and an in-range request stays unchanged. The accepted variable is an int value, so it does not depend on the lifetime of either temporary bound after the statement completes.
Apply it carefully
The lower bound must not compare greater than the upper bound. Validate configurable bounds first. std::clamp returns a reference to one of its arguments: binding that result to const auto& can leave a dangling reference when a temporary bound is selected. Copy the result when you need to retain it. Floating-point NaNs need a separate policy; this example deliberately uses integers.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- clamp-copy-result-demo.cpp clamp-copy-result-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.