The shortest solution in your first piece of code is to change the printf statement as follows:

    printf("absValue = %u\n", (unsigned)((u<0)?-u:u));

This will print the absolute value of u. The type conversion (unsigned) ensures that the data type is as expected by printf. The statement (u<0)?-u:u uses the conditional operator to select the value -u if the condition (u<0) is true and u if the condition is false (i.e. u>=0).

The problem in your code is that u is a signed integer which means its value is stored using the Two's complement representation in 4 bytes(*) and printf is not intelligent. When you tell printf to display an unsigned integer, then printf will take the 4 bytes holding u and interpret them as an unsigned integer. Since negative numbers in Two's complement are stored as large positive integers, that is the result you see.

(*) The use of Two's complement and the int size of 4 is machine-dependent, but common.

Answer from nielsen on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_abs.htm
C library - abs() function
The C stdlib library abs() function is used to returns the absolute value of the specified number, where absolute represents the positive number. This function only returns the positive integer.
🌐
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 · ❮ C stdlib Library · Display the absolute value of an integer: int value = abs(-5); printf("%d", value); Try ...
🌐
Scaler
scaler.com › home › topics › abs() function in c
abs() Function in C - Scaler Topics
March 21, 2024 - In the C programming language, the use of the function abs in C is to return the absolute value of an integer. By integer, it means that the abs() is an arithmetics function. The stdlib.h library contains predefined function abs() for computing ...
🌐
Cplusplus
cplusplus.com › reference › cstdlib › abs
abs
Returns the absolute value of parameter n ( /n/ ). In C++, this function is also overloaded in header <cmath> for floating-point types (see cmath abs), in header <complex> for complex numbers (see complex abs), and in header <valarray> for valarrays (see valarray abs).
🌐
Cppreference
en.cppreference.com › w › c › numeric › math › abs.html
abs, labs, llabs, imaxabs - cppreference.com
for 32-bit 2's complement type int, INT_MIN is -2147483648, but the would-be result 2147483648 is greater than INT_MAX, which is 2147483647. ... #include <limits.h> #include <stdio.h> #include <stdlib.h> int main(void) { printf("abs(+3) = %d\n", abs(+3)); printf("abs(-3) = %d\n", abs(-3)); // printf("%+d\n", abs(INT_MIN)); // undefined behavior on 2's complement systems }
Top answer
1 of 5
4

The shortest solution in your first piece of code is to change the printf statement as follows:

    printf("absValue = %u\n", (unsigned)((u<0)?-u:u));

This will print the absolute value of u. The type conversion (unsigned) ensures that the data type is as expected by printf. The statement (u<0)?-u:u uses the conditional operator to select the value -u if the condition (u<0) is true and u if the condition is false (i.e. u>=0).

The problem in your code is that u is a signed integer which means its value is stored using the Two's complement representation in 4 bytes(*) and printf is not intelligent. When you tell printf to display an unsigned integer, then printf will take the 4 bytes holding u and interpret them as an unsigned integer. Since negative numbers in Two's complement are stored as large positive integers, that is the result you see.

(*) The use of Two's complement and the int size of 4 is machine-dependent, but common.

2 of 5
4

As an alternative, you can also use the standard C function abs() (or one of its related functions):

7.22.6.1 The abs, labs and llabs functions

Synopsis

     #include <stdlib.h>
     int abs(int j);
     long int labs(long int j);
     long long int llabs(long long int j);

Description

The abs, labs, and llabs functions compute the absolute value of an integer j. If the result cannot be represented, the behavior is undefined.

Returns

The abs, labs, and llabs, functions return the absolute value.

Footnotes

The absolute value of the most negative number cannot be represented in two's complement.

Note the footnote "The absolute value of the most negative number cannot be represented in two's complement." and "If the result cannot be represented, the behavior is undefined." Strictly speaking, you'd likely need to use long long int and llabs() to avoid undefined behavior in converting INT_MIN to a positive value, assuming a 32-bit int value, and long is often 32-bits, even on 64-bit Windows.

However, since double values are likely implemented in IEEE format with 53 bits of precision, a 32-bit int value can be converted to double with no loss of precision, so you can use the fabs() function to get the absolute value of a 32-bit int value in one call:

7.12.7.2 The fabs functions

Synopsis

    #include <math.h>
    double fabs(double x);
    float fabsf(float x);
    long double fabsl(long double x);

The fabs functions compute the absolute value of a floating-point number x.

So your code would be:

#include <stdio.h>
#include <math.h>

int main (int argc, char *argv[]) {
    int u;

    scanf("%d", &u);
    printf("absValue = %u\n", (unsigned) fabs((double) u));

    return 0;
}

Note that in (unsigned) fabs((double) u), casting u to double is not strictly necessary, as the int value will be implicitly converted to a double because of the double fabs(double) function prototype from stdlib.h. But the cast back to unsigned is exremely necessary to pass the unsigned int value you want to pass to printf().

You could also do this:

#include <stdio.h>
#include <math.h>

int main (int argc, char *argv[]) {
    int u;

    scanf("%d", &u);
    unsigned int absValue = fabs(u);
    printf("absValue = %u\n", absValue);

    return 0;
}

That works because unsigned int absValue is explicitly an unsigned int.

Also, on modern CPUs, conversion between int and double is usually done by a single relatively fast instruction.

Find elsewhere
🌐
GitHub
github.com › lattera › glibc › blob › master › stdlib › abs.c
glibc/stdlib/abs.c at master · lattera/glibc
License along with the GNU C Library; if not, see · <http://www.gnu.org/licenses/>. */ · #include <stdlib.h> · #undef abs · · /* Return the absolute value of I. */ int · abs (int i) { return i < 0 ?
Author   lattera
🌐
Fresh2Refresh
fresh2refresh.com › home › c programming tutorial › c – arithmetic functions › c – abs() function
C abs() function | C Arithmetic functions | Fresh2Refresh
September 23, 2020 - C abs() function:abs( ) function in C returns the absolute value of an integer. The absolute value of a number is always positive.
🌐
GNU
gnu.org › software › libc › manual › html_node › Absolute-Value.html
Absolute Value (The GNU C Library)
These functions return the absolute value of the complex number z (see Complex Numbers). The absolute value of a complex number is: sqrt (creal (z) * creal (z) + cimag (z) * cimag (z)) This function should always be used instead of the direct formula because it takes special care to avoid losing ...
🌐
Javatpoint
javatpoint.com › abs-function-in-c
abs() function in C - javatpoint
abs() function in C with Tutorial, C language with programming examples for beginners and professionals covering concepts, c pointers, c structures, c union, c strings etc.
🌐
W3Resource
w3resource.com › c-programming › stdlib › c-abs.php
C abs() function
C abs() function (stdlib.h): The abs() function is used to compute the absolute value of an integer value.
🌐
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.
🌐
IBM
ibm.com › docs › en › rdfi › 9.6.0
ILE C/C++ Runtime Library Functions
We cannot provide a description for this page right now
🌐
Wikibooks
en.wikibooks.org › wiki › C_Programming › stdlib.h › abs
C Programming/stdlib.h/abs - Wikibooks, open books for an open world
int abs (int i); long labs (long i); double fabs (double i); float fabsf (float i); long double fabsl (long double i); Retrieved from "https://en.wikibooks.org/w/index.php?title=C_Programming/stdlib.h/abs&oldid=3238954"
🌐
Quora
quora.com › What-is-the-function-of-the-ABS-function-in-C-programming-language
What is the function of the ABS() function in C programming language? - Quora
Answer (1 of 2): My initial inclination was to write that it exercised your abdominal muscles, making them strong enough to lift the manual containing descriptions of all the functions in the standard C library, but I realised that it might be a bit harsh. abs(x) returns the positive magnitude o...
🌐
Codingtag
codingtag.com › abs()-function-in-c
abs() function in C
The abs() function in C is a standard library function used to compute the absolute value of an integer.
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?