C++ Basics: Initialize a Maximum for Negative Data
Use numeric_limits::lowest when a floating-point maximum accumulator must handle negative values.
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 numeric-limits-lowest-negative-data-demo.cpp:
#include <algorithm>
#include <array>
#include <iostream>
#include <limits>
int main()
{
constexpr std::array<double, 3> readings{-8.0, -3.0, -12.0};
double highest = std::numeric_limits<double>::lowest();
for (double value : readings) {
highest = std::max(highest, value);
}
std::cout << "highest: " << highest << '\n';
std::cout << std::boolalpha
<< "min is positive: "
<< (std::numeric_limits<double>::min() > 0.0) << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic numeric-limits-lowest-negative-data-demo.cpp -o numeric-limits-lowest-negative-data-demo &&
./numeric-limits-lowest-negative-data-demoObserved output:
highest: -3
min is positive: trueRead the result
The maximum reading is -3. For double on this platform, min() is a small positive normalized value, so it is the wrong starting point for this loop. lowest() supplies the lowest finite value.
Apply it carefully
This example assumes a nonempty collection of finite readings. For potentially empty input, represent absence explicitly or test emptiness before computing a result. Decide how to handle NaN and infinities separately; lowest() is a finite bound, not negative infinity.
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 -- numeric-limits-lowest-negative-data-demo.cpp numeric-limits-lowest-negative-data-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.