C++ Basics: Check an Integer Before Narrowing It
Use std::in_range to test whether an integer fits the destination type before casting.
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 in-range-checked-narrowing-demo.cpp:
#include <cstdint>
#include <iostream>
#include <utility>
int main()
{
for (int value : {-1, 0, 255, 256}) {
std::cout << value << ": ";
if (std::in_range<std::uint8_t>(value)) {
const auto byte = static_cast<std::uint8_t>(value);
std::cout << "stored=" << static_cast<unsigned>(byte) << '\n';
} else {
std::cout << "rejected\n";
}
}
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic in-range-checked-narrowing-demo.cpp -o in-range-checked-narrowing-demo &&
./in-range-checked-narrowing-demoObserved output:
-1: rejected
0: stored=0
255: stored=255
256: rejectedRead the result
On this system, uint8_t represents values from zero through 255. The test rejects both a negative value and a value above the maximum before the cast occurs. Converting the stored byte to unsigned for printing avoids character output.
Apply it carefully
Test the original value, not an already narrowed result. std::in_range is for integer range checks, not floating-point conversion or application rules such as valid port numbers. uint8_t is optional, though available on the tested Linux platform.
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 -- in-range-checked-narrowing-demo.cpp in-range-checked-narrowing-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.