Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::llabs — absolute value of a long long

std::llabs from <cstdlib> computes the absolute value of a long long and returns the same type. The result must be representable; calling it with the minimum long long value has undefined behavior.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <cstdlib>
constexpr long long int std::llabs(long long int j);

std::llabs(j), declared in <cstdlib>, takes a long long int argument and returns its absolute value as long long int. It returns the positive counterpart of a negative value and leaves zero and positive values unchanged. long long and long long int name the same type.

The result must fit in the return type. In C++23, the positive counterpart of the minimum long long value, std::numeric_limits<long long>::min() from <limits>, is not representable. Passing that value to std::llabs causes undefined behavior, not a guaranteed exception or a saturated result. If your input can contain that value, check for it before calling the function.

std::llabs has a fixed parameter type; it does not choose its return type based on the argument. By contrast, std::abs has integer overloads, including one for long long, with the same semantics. Do not use std::llabs as a general floating-point absolute-value function: the argument would first be converted to long long.

In C++23, std::llabs is constexpr, so a valid call can be evaluated at compile time. The example checks this with static_assert and prints results for a negative number, zero, and a positive number. Selecting a C++23 flag in a repository alone does not attest support in the production environment.

Examples

#include <cstdlib>
#include <iostream>

int main() {
    constexpr long long value = -42LL;
    constexpr long long magnitude = std::llabs(value);
    static_assert(magnitude == 42LL);

    std::cout << magnitude << '\n';
    std::cout << std::llabs(0LL) << '\n';
    std::cout << std::llabs(17LL) << '\n';
}

Result

42
0
17

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources