Library contents

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

  1. Start with −3
  2. Do this Take the signed integer magnitude
  3. Result 3
Negating this small negative integer produces a representable positive value.

Syntax

C++ 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.

First output line7
lesson.cpp
#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;
}
Output
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

Advertisements

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.

Given−3 °C → 4 °C
Worked result7 °C

The two readings sit seven one-degree intervals apart on the same scale.

Code and output in C++
C++ source
#include <cstdlib>
#include <iostream>

int main() {
    int sunrise = -3, midday = 4;
    std::cout << std::abs(midday - sunrise) << " °C\n";
    return 0;
}
Output
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.

Given09:12 scheduled · 09:05 actual
Worked result7 min

Both times fall in the same hour, so the magnitude of the minute difference gives the delay statistic.

Code and output in C++
C++ source
#include <cstdlib>
#include <iostream>

int main() {
    int scheduled = 12, actual = 5;
    std::cout << std::abs(actual - scheduled) << " min\n";
    return 0;
}
Output
7 min