Alright, the following works. @user16217248 got me started. See the discussion under that answer.

How to safely and efficiently find abs((int)num1 - (int)num2)

/// Safely and efficiently return `abs((int)num1 - (int)num2)`
unsigned int abs_num1_minus_num2_int(int num1, int num2)
{
    unsigned int abs_diff = num1 > num2 ?
        (unsigned int)num1 - (unsigned int)num2 :
        (unsigned int)num2 - (unsigned int)num1;

    return abs_diff;
}

The secret is to do the num1 > num2 ternary comparison with signed integer values, but then to reinterpret cast them to unsigned integer values to allow for well-defined overflow and underflow behavior when getting the absolute value of num1 - num2.

Here is my full test code:

absolute_value_of_num1_minus_num2.c from my eRCaGuy_hello_world repo:

///usr/bin/env ccache gcc -Wall -Wextra -Werror -O3 -std=gnu17 "$0" -o /tmp/a -lm && /tmp/a "$@"; exit
// For the line just above, see my answer here: https://stackoverflow.com/a/75491834/4561887

#include <limits.h>
#include <stdbool.h> // For `true` (`1`) and `false` (`0`) macros in C
#include <stdint.h>  // For `uint8_t`, `int8_t`, etc.
#include <stdio.h>   // For `printf()`


#define TEST_EQ(func, num1, num2, equals) \
    printf("%s\n", func((num1), (num2)) == (equals) ? "Passed" : "FAILED")

/// Safely and efficiently return `abs((int8_t)num1 - (int8_t)num2)`
uint8_t abs_num1_minus_num2_int8(int8_t num1, int8_t num2)
{
    // Note: due to implicit type promotion rules, rule 2 in my answer here
    // (https://stackoverflow.com/a/72654668/4561887) applies, and both the `>`
    // comparison, as well as subtraction, take place below as `int` types.
    // While signed `int` overflow and underflow is undefined behavior, none of
    // that occurs here.
    // - It's just useful to understand that even though we are doing
    //   `(uint8_t)num1 -(uint8_t)num2`, the C compiler really sees it as this:
    //   `(int)(uint8_t)num1 - (int)(uint8_t)num2`.
    // - This is because all small types smaller than `int`, such as `uint8_t`,
    //   are first automatically implicitly cast to `int` before any
    //   mathematical operation or comparison occurs.
    // - The C++ compiler therefore sees it as this:
    //   `static_cast<int>(static_cast<unsigned char>(num1)) - static_cast<int>(static_cast<unsigned char>(num2))`.
    //   - Run this code through https://cppinsights.io/ to see that.
    //     See here: https://cppinsights.io/s/bfc425f6 --> and click the play
    //     button.
    uint8_t abs_diff = num1 > num2 ?
        (uint8_t)num1 - (uint8_t)num2 :
        (uint8_t)num2 - (uint8_t)num1;

    // debugging
    printf("num1 = %4i (%3u); num2 = %4i (%3u); num1-num2=%3u;  ",
        num1, (uint8_t)num1, num2, (uint8_t)num2, abs_diff);

    return abs_diff;
}

/// Safely and efficiently return `abs((int)num1 - (int)num2)`
unsigned int abs_num1_minus_num2_int(int num1, int num2)
{
    unsigned int abs_diff = num1 > num2 ?
        (unsigned int)num1 - (unsigned int)num2 :
        (unsigned int)num2 - (unsigned int)num1;

    // debugging
    printf("num1 = %11i (%10u); num2 = %11i (%10u); num1-num2=%10u;  ",
        num1, (unsigned int)num1, num2, (unsigned int)num2, abs_diff);

    return abs_diff;
}


int main()
{
    printf("Absolute difference tests.\n");

    // ---------------
    // int8_t types
    // ---------------

    int8_t num1_8;
    int8_t num2_8;

    printf("\n");
    printf("INT8_MIN = %i, INT8_MAX = %i\n", INT8_MIN, INT8_MAX); // -128, 127

    num1_8 = -7;
    num2_8 = -4;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, 3);

    num1_8 = INT8_MIN;
    num2_8 = INT8_MAX;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, UINT8_MAX);

    num1_8 = INT8_MAX;
    num2_8 = INT8_MIN;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, UINT8_MAX);

    num1_8 = 100;
    num2_8 = 10;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, 90);

    num1_8 = 10;
    num2_8 = 100;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, 90);

    num1_8 = 10;
    num2_8 = 10;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, 0);

    num1_8 = INT8_MAX;
    num2_8 = 1;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, 126);

    num1_8 = 1;
    num2_8 = INT8_MAX;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, 126);

    // ---------------
    // int types
    // ---------------

    int num1;
    int num2;

    printf("\n");
    printf("INT_MIN = %i, INT_MAX = %i\n", INT_MIN, INT_MAX); // -2147483648, 2147483647

    num1 = -7;
    num2 = -4;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, 3);

    num1 = INT_MIN;
    num2 = INT_MAX;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, UINT_MAX);

    num1 = INT_MAX;
    num2 = INT_MIN;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, UINT_MAX);

    num1 = 100;
    num2 = 10;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, 90);

    num1 = 10;
    num2 = 100;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, 90);

    num1 = 10;
    num2 = 10;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, 0);

    num1 = INT_MAX;
    num2 = 1;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, 2147483646);

    num1 = 1;
    num2 = INT_MAX;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, 2147483646);


    return 0;
}

Sample run and output:

eRCaGuy_hello_world/c$ ./absolute_value_of_num1_minus_num2.c
Absolute difference tests.

INT8_MIN = -128, INT8_MAX = 127
num1 =   -7 (249); num2 =   -4 (252); num1-num2=  3;  Passed
num1 = -128 (128); num2 =  127 (127); num1-num2=255;  Passed
num1 =  127 (127); num2 = -128 (128); num1-num2=255;  Passed
num1 =  100 (100); num2 =   10 ( 10); num1-num2= 90;  Passed
num1 =   10 ( 10); num2 =  100 (100); num1-num2= 90;  Passed
num1 =   10 ( 10); num2 =   10 ( 10); num1-num2=  0;  Passed
num1 =  127 (127); num2 =    1 (  1); num1-num2=126;  Passed
num1 =    1 (  1); num2 =  127 (127); num1-num2=126;  Passed

INT_MIN = -2147483648, INT_MAX = 2147483647
num1 =          -7 (4294967289); num2 =          -4 (4294967292); num1-num2=         3;  Passed
num1 = -2147483648 (2147483648); num2 =  2147483647 (2147483647); num1-num2=4294967295;  Passed
num1 =  2147483647 (2147483647); num2 = -2147483648 (2147483648); num1-num2=4294967295;  Passed
num1 =         100 (       100); num2 =          10 (        10); num1-num2=        90;  Passed
num1 =          10 (        10); num2 =         100 (       100); num1-num2=        90;  Passed
num1 =          10 (        10); num2 =          10 (        10); num1-num2=         0;  Passed
num1 =  2147483647 (2147483647); num2 =           1 (         1); num1-num2=2147483646;  Passed
num1 =           1 (         1); num2 =  2147483647 (2147483647); num1-num2=2147483646;  Passed

Adjacently related

  1. The "absolute subtraction" above reminds me of the "rounding divide" set of solutions you can do with integer math too. For that, see my other answer here: Rounding integer division (instead of truncating). I present rounding up, rounding down, and rounding to nearest when doing integer division.

See also

  1. My answer on implicit casting/promotion and Integer and floating point rank and promotion rules in C and C++
  2. https://cppinsights.io/ - a very useful tool which expands your C++ code into exactly what the compiler sees, including after applying all automatic implicit type promotion rules in the compiler.
    1. Ex: see my code above here: https://cppinsights.io/s/bfc425f6 --> then click the play button to convert and expand it into what the compiler sees.
Answer from Gabriel Staples on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › program-to-find-absolute-value-of-a-given-number
Program to find absolute value of a given number - GeeksforGeeks
For any positive number, the absolute value is the number itself and for any negative number, the absolute value is (-1) multiplied by the negative number ... Below is the implementation of the above approach.
Published   July 15, 2025
Top answer
1 of 5
9

Alright, the following works. @user16217248 got me started. See the discussion under that answer.

How to safely and efficiently find abs((int)num1 - (int)num2)

/// Safely and efficiently return `abs((int)num1 - (int)num2)`
unsigned int abs_num1_minus_num2_int(int num1, int num2)
{
    unsigned int abs_diff = num1 > num2 ?
        (unsigned int)num1 - (unsigned int)num2 :
        (unsigned int)num2 - (unsigned int)num1;

    return abs_diff;
}

The secret is to do the num1 > num2 ternary comparison with signed integer values, but then to reinterpret cast them to unsigned integer values to allow for well-defined overflow and underflow behavior when getting the absolute value of num1 - num2.

Here is my full test code:

absolute_value_of_num1_minus_num2.c from my eRCaGuy_hello_world repo:

///usr/bin/env ccache gcc -Wall -Wextra -Werror -O3 -std=gnu17 "$0" -o /tmp/a -lm && /tmp/a "$@"; exit
// For the line just above, see my answer here: https://stackoverflow.com/a/75491834/4561887

#include <limits.h>
#include <stdbool.h> // For `true` (`1`) and `false` (`0`) macros in C
#include <stdint.h>  // For `uint8_t`, `int8_t`, etc.
#include <stdio.h>   // For `printf()`


#define TEST_EQ(func, num1, num2, equals) \
    printf("%s\n", func((num1), (num2)) == (equals) ? "Passed" : "FAILED")

/// Safely and efficiently return `abs((int8_t)num1 - (int8_t)num2)`
uint8_t abs_num1_minus_num2_int8(int8_t num1, int8_t num2)
{
    // Note: due to implicit type promotion rules, rule 2 in my answer here
    // (https://stackoverflow.com/a/72654668/4561887) applies, and both the `>`
    // comparison, as well as subtraction, take place below as `int` types.
    // While signed `int` overflow and underflow is undefined behavior, none of
    // that occurs here.
    // - It's just useful to understand that even though we are doing
    //   `(uint8_t)num1 -(uint8_t)num2`, the C compiler really sees it as this:
    //   `(int)(uint8_t)num1 - (int)(uint8_t)num2`.
    // - This is because all small types smaller than `int`, such as `uint8_t`,
    //   are first automatically implicitly cast to `int` before any
    //   mathematical operation or comparison occurs.
    // - The C++ compiler therefore sees it as this:
    //   `static_cast<int>(static_cast<unsigned char>(num1)) - static_cast<int>(static_cast<unsigned char>(num2))`.
    //   - Run this code through https://cppinsights.io/ to see that.
    //     See here: https://cppinsights.io/s/bfc425f6 --> and click the play
    //     button.
    uint8_t abs_diff = num1 > num2 ?
        (uint8_t)num1 - (uint8_t)num2 :
        (uint8_t)num2 - (uint8_t)num1;

    // debugging
    printf("num1 = %4i (%3u); num2 = %4i (%3u); num1-num2=%3u;  ",
        num1, (uint8_t)num1, num2, (uint8_t)num2, abs_diff);

    return abs_diff;
}

/// Safely and efficiently return `abs((int)num1 - (int)num2)`
unsigned int abs_num1_minus_num2_int(int num1, int num2)
{
    unsigned int abs_diff = num1 > num2 ?
        (unsigned int)num1 - (unsigned int)num2 :
        (unsigned int)num2 - (unsigned int)num1;

    // debugging
    printf("num1 = %11i (%10u); num2 = %11i (%10u); num1-num2=%10u;  ",
        num1, (unsigned int)num1, num2, (unsigned int)num2, abs_diff);

    return abs_diff;
}


int main()
{
    printf("Absolute difference tests.\n");

    // ---------------
    // int8_t types
    // ---------------

    int8_t num1_8;
    int8_t num2_8;

    printf("\n");
    printf("INT8_MIN = %i, INT8_MAX = %i\n", INT8_MIN, INT8_MAX); // -128, 127

    num1_8 = -7;
    num2_8 = -4;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, 3);

    num1_8 = INT8_MIN;
    num2_8 = INT8_MAX;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, UINT8_MAX);

    num1_8 = INT8_MAX;
    num2_8 = INT8_MIN;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, UINT8_MAX);

    num1_8 = 100;
    num2_8 = 10;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, 90);

    num1_8 = 10;
    num2_8 = 100;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, 90);

    num1_8 = 10;
    num2_8 = 10;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, 0);

    num1_8 = INT8_MAX;
    num2_8 = 1;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, 126);

    num1_8 = 1;
    num2_8 = INT8_MAX;
    TEST_EQ(abs_num1_minus_num2_int8, num1_8, num2_8, 126);

    // ---------------
    // int types
    // ---------------

    int num1;
    int num2;

    printf("\n");
    printf("INT_MIN = %i, INT_MAX = %i\n", INT_MIN, INT_MAX); // -2147483648, 2147483647

    num1 = -7;
    num2 = -4;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, 3);

    num1 = INT_MIN;
    num2 = INT_MAX;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, UINT_MAX);

    num1 = INT_MAX;
    num2 = INT_MIN;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, UINT_MAX);

    num1 = 100;
    num2 = 10;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, 90);

    num1 = 10;
    num2 = 100;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, 90);

    num1 = 10;
    num2 = 10;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, 0);

    num1 = INT_MAX;
    num2 = 1;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, 2147483646);

    num1 = 1;
    num2 = INT_MAX;
    TEST_EQ(abs_num1_minus_num2_int, num1, num2, 2147483646);


    return 0;
}

Sample run and output:

eRCaGuy_hello_world/c$ ./absolute_value_of_num1_minus_num2.c
Absolute difference tests.

INT8_MIN = -128, INT8_MAX = 127
num1 =   -7 (249); num2 =   -4 (252); num1-num2=  3;  Passed
num1 = -128 (128); num2 =  127 (127); num1-num2=255;  Passed
num1 =  127 (127); num2 = -128 (128); num1-num2=255;  Passed
num1 =  100 (100); num2 =   10 ( 10); num1-num2= 90;  Passed
num1 =   10 ( 10); num2 =  100 (100); num1-num2= 90;  Passed
num1 =   10 ( 10); num2 =   10 ( 10); num1-num2=  0;  Passed
num1 =  127 (127); num2 =    1 (  1); num1-num2=126;  Passed
num1 =    1 (  1); num2 =  127 (127); num1-num2=126;  Passed

INT_MIN = -2147483648, INT_MAX = 2147483647
num1 =          -7 (4294967289); num2 =          -4 (4294967292); num1-num2=         3;  Passed
num1 = -2147483648 (2147483648); num2 =  2147483647 (2147483647); num1-num2=4294967295;  Passed
num1 =  2147483647 (2147483647); num2 = -2147483648 (2147483648); num1-num2=4294967295;  Passed
num1 =         100 (       100); num2 =          10 (        10); num1-num2=        90;  Passed
num1 =          10 (        10); num2 =         100 (       100); num1-num2=        90;  Passed
num1 =          10 (        10); num2 =          10 (        10); num1-num2=         0;  Passed
num1 =  2147483647 (2147483647); num2 =           1 (         1); num1-num2=2147483646;  Passed
num1 =           1 (         1); num2 =  2147483647 (2147483647); num1-num2=2147483646;  Passed

Adjacently related

  1. The "absolute subtraction" above reminds me of the "rounding divide" set of solutions you can do with integer math too. For that, see my other answer here: Rounding integer division (instead of truncating). I present rounding up, rounding down, and rounding to nearest when doing integer division.

See also

  1. My answer on implicit casting/promotion and Integer and floating point rank and promotion rules in C and C++
  2. https://cppinsights.io/ - a very useful tool which expands your C++ code into exactly what the compiler sees, including after applying all automatic implicit type promotion rules in the compiler.
    1. Ex: see my code above here: https://cppinsights.io/s/bfc425f6 --> then click the play button to convert and expand it into what the compiler sees.
2 of 5
3

A simple solution to this problem is to avoid overflow entirely by always subtracting the smaller one from the bigger one. This gives the expected results, even for x == INT_MIN and y == INT_MAX. The signed to unsigned conversion here is safe:

unsigned diff = x > y ? (unsigned)x-(unsigned)y : (unsigned)y-(unsigned)x;

Edit: In order for the subtraction to be guaranteed to not cause signed overflow in cases of the 'smaller' one being less than zero, the operands must be cast to unsigned.

Discussions

microcontroller - Implementing an absolute value function in C - Electrical Engineering Stack Exchange
It's not hard to do once you've worked out the steps in your situation. Let me just suggest some options to consider. Perhaps that's the best I can do. (I'm assuming below that you don't want to take the absolute function of a constant, since there is an obvious "code time" solution for that case.) More on electronics.stackexchange.com
🌐 electronics.stackexchange.com
July 2, 2019
absolute difference between numbers - Connect IQ App Development Discussion - Connect IQ - Garmin Forums
I'm currently getting values from the accelerometer on a Garmin device. The number are negative and positive. What I need to do is find the absolute difference between any two given numbers e.g. Number1 = -100 Number2 = 100 Number3 = absolute difference 200 in Excel you can use the ABS Function ... More on forums.garmin.com
🌐 forums.garmin.com
Absolute value without calling the Math.abs() method?

I think you can probably figure this one out just with a hint.

What happens to negative numbers when they are multiplied by -1?

Note that you can check if numbers are less than zero using if and then do something about less than zero numbers.

If you still get stuck after thinking on that for a few minutes shoot me a pm.

Edit: as long as you don't ask me to just write out all the code for you.

More on reddit.com
🌐 r/javahelp
7
1
December 27, 2015
How to efficiently compute absolute value of float in #![no_std]?
Don't use the unsafe suggestions. It's completely unnecessary. Pointer casting or unions are needed in C, but Rust has these 2 little functions called {f32,f64}::to_bits() and {f32,f64}::from_bits() that tuck away all the ugliness so you can just focus on the safe no-op conversion. pub fn abs64(x: f64) -> f64 { f64::from_bits(x.to_bits() & (i64::MAX as u64)) } pub fn abs32(x: f32) -> f32 { f32::from_bits(x.to_bits() & (i32::MAX as u32)) } There's also the fact that this entire thread only exists because of this 4 year old issue . As shown, the implementation is trivial, but LLVM can lower it to a libm call ( but in practice, never will, not even with soft floats ), so it was decided to go in std instead of core. More on reddit.com
🌐 r/rust
49
63
August 19, 2023
🌐
Scaler
scaler.com › home › topics › abs() function in c
abs() Function in C - Scaler Topics
March 21, 2024 - A number will always have a positive abs value or absolute value, meaning that a distance will never be negative. To use the abs() function in C, you need a header file called <stdlib.h>.
🌐
W3Schools
w3schools.com › c › ref_stdlib_abs.php
C stdlib abs() Function
C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Compiler C Syllabus C Study Plan C Interview Q&A C Certificate ... The abs() function returns the absolute (positive) value of a number.
🌐
w3resource
w3resource.com › c-programming-exercises › inline_function › c-inline-function-exercise-2.php
C inline function - Absolute difference between 2 integers
The absolute difference is the positive value of the difference between the two integers, regardless of which one is the higher. The function takes two integer parameters and returns their absolute difference as an integer value.
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_abs.htm
C library - abs() function
In this example, we create a basic c program to demonstrate the use of abs() function. #include<stdio.h> #include<stdlib.h> int main(){ int x = -2, res; printf("Original value of X is %d\n", x); // use the abs() function to get the absolute ...
🌐
LeetCode
leetcode.com › problems › minimum-absolute-difference
Minimum Absolute Difference - LeetCode
Minimum Absolute Difference - Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows ...
Find elsewhere
🌐
Tutorial Gateway
tutorialgateway.org › c-program-to-find-the-absolute-value-of-a-number
C Program to Find the Absolute Value of a Number
December 19, 2024 - It is a simple code to find the absolute value of any number in c using an if statement that checks whether the number less than zero.
🌐
Scaler
scaler.com › home › topics › abs() in c++
abs() in C++ | abs() Function in C++ - Scaler Topics
October 10, 2025 - The abs() function in C++ returns the absolute value of an integer number. The absolute value of a negative number is multiplied by -1, but the absolute value of positive numbers and zero is that number itself.
🌐
Arduino
docs.arduino.cc › language-reference › en › functions › math › abs
abs()
Arduino programming language can be divided in three main parts: functions, values (variables and constants), and structure.
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › abs-labs-llabs-functions-cc
abs(), labs(), llabs() functions in C/C++ - GeeksforGeeks
July 11, 2025 - The std::abs(), std::labs() and std::llabs() in C++ are built-in functions that are used to find the absolute value of any number that is given as the argument. Absolute value is the value of a number without any sign.
🌐
Quora
quora.com › How-do-you-write-a-program-that-calculates-the-absolute-value-of-a-given-number-floating-point-number-and-long-number-What-are-some-examples
How to write a program that calculates the absolute value of a given number, floating point number and long number? What are some examples - Quora
Answer (1 of 4): First you learn to program, and diving into C or C++ to do this is a very bad idea, since these are complex system-oriented languages. C++ is a terrible language to learn, a bad example of just about everything, especially complexity. Ultimately you only learn C++ to learn C++, ...
🌐
MathWorks
mathworks.com › matlab › mathematics › elementary math › complex numbers
abs - Absolute value and complex magnitude - MATLAB
Create a numeric vector of real values. ... Find the absolute value of the elements of the vector. ... Input array, specified as a scalar, vector, matrix, multidimensional array, table, or timetable. If X is complex, then it must be a single or double array.
Top answer
1 of 3
11

The standard C library is providing the optimized solutions for many problems with considerations based on the architecture, compiler in use and others. The abs() function defined in stdlib.h is one of these, and it is used for your purpose exactly. To emphasize the point, here is ARM compiler result when using abs vs a version of a homebrew abs: https://arm.godbolt.org/z/aO7t1n

Paste:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    srand(111);
    int x = rand() - 200;
    printf("%d\n", abs(x));
}

results in

main:
        push    {r4, lr}
        mov     r0, #111
        bl      srand
        bl      rand
        sub     r1, r0, #200
        cmp     r1, #0
        rsblt   r1, r1, #0
        ldr     r0, .L4
        bl      printf
        mov     r0, #0
        pop     {r4, pc}
.L4:
        .word   .LC0
.LC0:
        .ascii  "%d\012\000"

And

#include <stdio.h>
#include <stdlib.h>

int my_abs(int x)
{
    return x < 0 ? -x : x;
}

int main(void)
{
    srand(111);
    int x = rand() - 200;
    printf("%d\n", my_abs(x));
}

results in

my_abs:
        cmp     r0, #0
        rsblt   r0, r0, #0
        bx      lr
main:
        push    {r4, lr}
        mov     r0, #111
        bl      srand
        bl      rand
        sub     r1, r0, #200
        cmp     r1, #0
        rsblt   r1, r1, #0
        ldr     r0, .L5
        bl      printf
        mov     r0, #0
        pop     {r4, pc}
.L5:
        .word   .LC0
.LC0:
        .ascii  "%d\012\000"

Notice that the main code is identical (only a label name is different) in both programs as my_abs got inlined, and its implementation is the same as the standard one.

2 of 3
3

The speed of a given solution will depend greatly on the architecture, but in C I would say

return (n > 0 ? n : -n);

and let the compiler figure out the best solution.

EDIT: @jonk points out correctly that this will fail for the most-negative possible value of n, assuming that two's-complement arithmetic is used.

Yes, my solution has a conditional branch, but yours has an arithmetic operator and two bitwise operators. Can your microcontroller shift 15 places in a single clock?

🌐
Wikipedia
en.wikipedia.org › wiki › Absolute_difference
Absolute difference - Wikipedia
3 weeks ago - The absolute difference takes non-negative integers to non-negative integers. As a binary operation that is commutative but not associative, with an identity element on the non-negative numbers, the absolute difference gives the non-negative numbers (whether real or integer) the algebraic structure of a commutative magma with identity.
🌐
Garmin Forums
forums.garmin.com › developer › connect-iq › f › discussion › 4643 › absolute-difference-between-numbers
absolute difference between numbers - Connect IQ App Development Discussion - Connect IQ - Garmin Forums
What I need to do is find the absolute difference between any two given numbers e.g. Number1 = -100 Number2 = 100 Number3 = absolute difference 200 in Excel you can use the ABS Function ABS(B2-B3) in C Sharp there is Math.Abs Is there anything similar in monkey C - Ive had a search of the ...
🌐
w3resource
w3resource.com › c-programming-exercises › basic-algo › c-programming-basic-algorithm-exercises-2.php
C Program: Get the absolute difference between n and 51 - w3resource
C programming, exercises, solution: Write a C program that will take a number as input and find the absolute difference between the input number and 51. If the input number is greater than 51, it will return triple the absolute difference.
🌐
Cppreference
en.cppreference.com › w › cpp › numeric › math › abs.html
std::abs, std::labs, std::llabs, std::imaxabs - cppreference.com
March 14, 2025 - #include <climits> #include <cstdlib> #include <iostream> int main() { std::cout << std::showpos << "abs(+3) = " << std::abs(3) << '\n' << "abs(-3) = " << std::abs(-3) << '\n'; // std::cout << std::abs(INT_MIN); // undefined behavior on 2's complement systems }