From Bit Twiddling Hacks:

int v;           // we want to find the absolute value of v
unsigned int r;  // the result goes here 
int const mask = v >> sizeof(int) * CHAR_BIT - 1;

r = (v + mask) ^ mask;
Answer from Hasturkun on Stack Overflow
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.

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?

🌐
GNU
gnu.org › software › libc › manual › html_node › Absolute-Value.html
Absolute Value (The GNU C Library)
These functions return the absolute value of number. Most computers use a two’s complement integer representation, in which the absolute value of INT_MIN (the smallest possible int) cannot be represented; thus, abs (INT_MIN) is not defined.
🌐
Reddit
reddit.com › r/c_programming › write a function that computes the absolute value of an integer.
r/C_Programming on Reddit: Write a function that computes the absolute value of an integer.
July 6, 2022 -

Question: Write a function that computes the absolute value of an integer.

Prototype: int _abs(int); FYI: The standard library provides a similar function: abs. Run man abs to learn more.

My code: #include "main.h" #include "stdlib.h> int _abs(int n) { int abs (n); return (0); }

The protoype is in the main.h file and im trying to call the abs() function.

Compiler error:6-abs.c: In function ‘_abs’:
6-abs.c:11:2: error: parameter names (without types) in function declaration [-Werror]
11 | int abs(n);
| ~~
6-abs.c:9:14: error: unused parameter ‘n’ [-Werror=unused-parameter]
9 | int _abs(int n)
| ~~~~^
cc1: all warnings being treated as errors

I have no Idea what any of that means and i've tried to resolve it in different ways but more errors keep coming up. Can someone please explain what the problem to my code is?

Find elsewhere
🌐
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
🌐
Vultr
docs.vultr.com › clang › standard-library › math-h › fabs
C math.h fabs() - Get Absolute Value | Vultr Docs
December 12, 2024 - In this article, you will learn how to effectively use the fabs() function to obtain the absolute value of floating-point numbers. Explore practical examples illustrating its usage in different contexts and discover how it handles various types ...
🌐
Know Program
knowprogram.com › home › absolute value in c
Absolute value in C - abs(), labs(), fabs()
June 29, 2021 - The absolute value of a number is always positive (distance can never be negative). Here we will develop a program to find the absolute value in C. First, we will develop a program without using any pre-defined function, and later we will develop the C program to find absolute value using the pre-defined abs() function.
🌐
C For Dummies
c-for-dummies.com › blog
Calculating the Absolute Value | C For Dummies Blog
Instead, your challenge is to write ... its absolute value. ... This task may not seem too difficult (hence only one star), but a quirk exists when returning the value of some negative integers. I share this quirk along with my solution, but please try this exercise on your own. What happens if you throw an unsigned type at one of the abs functions? Error or just the parameter value returned? Here’s the quirky thing about using an unsigned ...
🌐
Cplusplus
cplusplus.com › reference › cstdlib › abs
abs
The absolute value of n. In C, only the int version exists. For the long int equivalent see labs.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › fabs-function-in-c
fabs() Function in C - GeeksforGeeks
July 23, 2025 - Return Value: While passing values to fabs(), we can convert the number explicitly to double. ... Example 1: Below is the C program to show the use of the fabs() function. ... // C program to show the // use of fabs() function #include <math.h> #include <stdio.h> int main() { double a = 980; double b = -1231; double res; res = fabs(a); printf("The absolute value of %.3lf is %.3lf\n", a, res); res = fabs(b); printf("The absolute value of %.3lf is %.3lf\n", b, res); return 0; }
🌐
Linus Tech Tips
linustechtips.com › software › programming
C abs value - Programming - Linus Tech Tips
December 4, 2020 - Hey there, I want to print absolute value in c but I cannot use abs only conditions like if, else, else if, please help me out with that.
🌐
Cppreference
en.cppreference.com › w › c › numeric › math › abs.html
abs, labs, llabs, imaxabs - cppreference.com
The behavior is undefined if the result cannot be represented by the return type. The absolute value of n (i.e.
🌐
Quora
quora.com › How-do-you-find-the-absolute-value-of-an-expression-by-using-only-a-macro-in-C
How to find the absolute value of an expression by using only a macro in C - Quora
Answer (1 of 3): The code that you have supplied actually only works for a supplied variable: since it assigns the resulting absolute value back into the thing supplied. Thus that code will not work for a number or, as you indicate, for any more complex expression. The following C macro works fo...
🌐
O'Reilly
oreilly.com › library › view › c-in-a › 0596006977 › re57.html
fabs - C in a Nutshell [Book]
December 16, 2005 - NamefabsSynopsisObtains the absolute value of a number#include <math.h> doublefabs( double x ); float fabsf( float x ); long double fabsl( long double x );The fabs() function... - Selection from C in a Nutshell [Book]
Authors   Peter PrinzTony Crawford
Published   2005
Pages   618