C++ std::abs for signed integers
The integer overload of std::abs returns a signed value. Its mathematical result must fit the return type for the call to have defined behavior.
A simple example
std::abs for signed integers
- Start with −3
- Do this Take the signed integer magnitude
- Result 3
Syntax
std::abs(signed_value)
Run this example in C++
Save the program as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson
Handle a magnitude that might exceed the signed range
A batch can contain enough readings, or large enough values, to exceed a simple implementation's assumptions. Select a safe representation or comparison before combining, storing or ordering those inputs.
#include <iostream>
#include <cstdlib>
#include <limits>
static unsigned magnitude(int value) {
return value < 0 ? 0u - static_cast<unsigned>(value) : static_cast<unsigned>(value);
}
int main() {
std::cout << std::abs(-7) << '\n';
int lowest = std::numeric_limits<int>::min();
std::cout << std::boolalpha << (magnitude(lowest) == magnitude(lowest + 1) + 1u) << '\n';
return 0;
}
7 true
For the most negative int on common machines the positive magnitude exceeds INT_MAX. Converting to unsigned first and subtracting from 0u uses defined modulo arithmetic for the full input range.
C++ working draft for std::abs for signed integers
Compare two morning readings
A class logs the courtyard temperature at sunrise and again before lunch. The report asks how far apart the readings are, even when one is below freezing.
The two readings sit seven one-degree intervals apart on the same scale.
Code and output in C++
#include <cstdlib>
#include <iostream>
int main() {
int sunrise = -3, midday = 4;
std::cout << std::abs(midday - sunrise) << " °C\n";
return 0;
}
7 °C
Measure a bus timetable error
A bus expected at 09:12 arrives at 09:05. The dispatcher records how far the arrival missed the timetable and tracks early or late in a separate field.
Both times fall in the same hour, so the magnitude of the minute difference gives the delay statistic.
Code and output in C++
#include <cstdlib>
#include <iostream>
int main() {
int scheduled = 12, actual = 5;
std::cout << std::abs(actual - scheduled) << " min\n";
return 0;
}
7 min