C Math abs() Function

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
<stdlib.h>

What You’ll Learn

The abs() function returns the absolute value of an integer—its distance from zero without a sign. It is one of the first math-related helpers beginners reach for when comparing differences, validating input, or printing magnitudes.

01

Magnitude

Drop the sign.

02

stdlib.h

Not math.h.

03

int only

Use fabs for double.

04

labs / llabs

Wider integers.

05

Distance

|a − b|.

06

INT_MIN

Overflow trap.

Definition and Usage

abs (absolute) computes the non-negative magnitude of an int. Mathematically, |x| is x when x ≥ 0 and −x when x < 0. In C, you call abs(x) instead of writing that branch yourself.

Although absolute value feels like “math,” the standard abs() for integers lives in <stdlib.h>, not <math.h>. Floating-point absolute values use fabs() and friends from the math library.

💡
Beginner Tip

Think of abs() as “how far from zero?” —5 and +5 are both five steps away, so both give 5.

📝 Syntax

Standard C declaration for integers:

C
int abs(int x);

Related variants

C
long labs(long x);              /* <stdlib.h> */
long long llabs(long long x);   /* <stdlib.h> */
double fabs(double x);          /* <math.h>   */
float fabsf(float x);           /* <math.h>   */
long double fabsl(long double x); /* <math.h> */

Parameters

  • x — the integer whose absolute value you want.

Return Value

  • Non-negative int with the same magnitude as x.
  • abs(0) returns 0.
  • Calling abs(INT_MIN) may overflow—see Notes.

Headers

  • #include <stdlib.h> for abs, labs, llabs
  • #include <math.h> for fabs, fabsf, fabsl

⚡ Quick Reference

CallInput typeResult
abs(-5)int5
abs(42)int42 (unchanged)
labs(-100L)long100L
fabs(-3.14)double3.14
abs(a - b)intDistance between a and b
Integer
abs(x)

stdlib.h

Long
labs(x)

Wider int

Double
fabs(x)

math.h

Distance
abs(a - b)

|a − b|

Examples Gallery

Compile with gcc abs.c -std=c11 -o abs. Link with -lm only when you use fabs() from <math.h>.

📚 Getting Started

See how abs() removes the minus sign from integers.

Example 1 — Absolute Value of a Negative Integer

Convert -5 to its positive magnitude.

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

int main(void) {
    int num = -5;
    int result = abs(num);

    printf("Absolute value of %d is %d\n", num, result);

    return 0;
}

How It Works

abs(-5) negates the value because it is below zero, producing 5. Include <stdlib.h> so the compiler knows the prototype.

Example 2 — Positive Numbers Stay the Same

Zero and positive inputs are returned unchanged.

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

int main(void) {
    int values[] = { -10, 0, 10, 42 };
    size_t i;

    for (i = 0; i < sizeof values / sizeof values[0]; i++) {
        printf("abs(%d) = %d\n", values[i], abs(values[i]));
    }

    return 0;
}

How It Works

Only negative values are flipped. Zero has no sign to remove, and positive numbers already represent their own magnitude.

📈 Practical Patterns

Floating-point cousins, distance calculations, and safe usage.

Example 3 — Floating-Point with fabs()

Use fabs() from <math.h> for double values—not abs().

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

int main(void) {
    double num = -3.14;
    double result = fabs(num);

    printf("Absolute value of %.2f is %.2f\n", num, result);

    return 0;
}

How It Works

Compile with gcc fabs_demo.c -std=c11 -o fabs_demo -lm. The f prefix marks the floating-point version; fabsf and fabsl cover float and long double.

Example 4 — Distance Between Two Points

abs(a - b) gives the distance along a number line when both values fit in int.

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

int main(void) {
    int point_a = 12;
    int point_b = -7;
    int distance = abs(point_a - point_b);

    printf("Distance between %d and %d is %d\n",
           point_a, point_b, distance);

    return 0;
}

How It Works

Subtract first (12 - (-7) = 19) and apply abs so order does not matter: abs(-7 - 12) also yields 19.

Example 5 — Safer Absolute Value Helper

Guard against INT_MIN overflow before calling abs().

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

int safe_abs(int x) {
    if (x == INT_MIN) {
        /* No positive int exists for INT_MIN on two's complement */
        return INT_MAX;
    }
    return abs(x);
}

int main(void) {
    int test = -100;

    printf("safe_abs(%d) = %d\n", test, safe_abs(test));
    printf("safe_abs(%d) handled without overflow\n", INT_MIN);

    return 0;
}

How It Works

Production code often promotes to long long or checks bounds first. Here we detect INT_MIN and return a defined fallback instead of invoking undefined behavior.

🚀 Common Use Cases

  • Distance and difference — measure |a − b| without caring which is larger.
  • Error margins — compare how far a measured value is from an expected target.
  • Input validation — check whether a deviation stays within a tolerance band.
  • Sorting by magnitude — rank numbers by size regardless of sign.
  • Game and graphics math — speed, offsets, and collision checks often need non-negative distances.

🧠 How abs() Works

1

Receive int x

The function inspects the sign of the argument.

Input
2

Compare with zero

If x < 0, negate; otherwise return x unchanged.

Branch
3

Return magnitude

Result is always ≥ 0 (except INT_MIN edge case).

Output
=

Non-negative int

Same distance from zero, sign removed.

📝 Notes

  • abs() is declared in <stdlib.h>, not <math.h>.
  • Do not pass float or double to abs()—use fabs() instead.
  • abs(INT_MIN) can overflow on two’s-complement systems—handle explicitly.
  • For long and long long, prefer labs() and llabs().
  • Link with -lm when compiling programs that call fabs().

⚡ Optimization

Modern compilers inline abs() into a few instructions—often a conditional move rather than a function call. You rarely need a manual ternary for speed. Prefer the library function for clarity unless you are targeting a platform without stdlib (embedded bare-metal with a custom runtime).

Conclusion

abs() is the standard way to strip the sign from an int. Include <stdlib.h>, pick the right variant for your numeric type, and watch the INT_MIN corner case when values can reach the limits of the type.

Continue with acos() for inverse trigonometry, or explore fabs() when your data is floating-point.

💡 Best Practices

✅ Do

  • Include <stdlib.h> for abs()
  • Use fabs() for double values
  • Use labs() / llabs() for wider integers
  • Check for INT_MIN when input range is unknown
  • Compile with -lm when using math.h functions

❌ Don’t

  • Call abs() on floating-point numbers
  • Assume abs() lives in <math.h>
  • Ignore overflow on INT_MIN
  • Mix signed/unsigned types carelessly in a - b
  • Reimplement abs manually unless you have a special reason

Key Takeaways

Knowledge Unlocked

Five things to remember about abs()

Quick mental model for integer absolute value in C.

5
Core concepts
📚 02

stdlib.h

Header file.

Setup
📈 03

fabs for double

Right type.

Types
📍 04

|a − b|

Distance.

Pattern
⚠️ 05

INT_MIN

Overflow.

Safety

❓ Frequently Asked Questions

abs() returns the absolute value (non-negative magnitude) of an int. For example, abs(-5) is 5 and abs(5) is still 5. It ignores the sign and keeps the number's size.
Include <stdlib.h>. abs() is not declared in <math.h>. For double values use fabs() from <math.h>; for long use labs() and for long long use llabs(), both from <stdlib.h>.
No. abs() takes an int. Passing a float or double may truncate the value and give wrong results. Use fabs() for double, fabsf() for float, and fabsl() for long double.
It returns an int with the same magnitude as the argument but never negative. Zero stays zero. The return type is always int even when the input was negative.
On typical two's-complement systems, INT_MIN has no positive int counterpart, so abs(INT_MIN) overflows and the result is undefined. Avoid calling abs on INT_MIN; use a wider type or check first.
abs() works on int via stdlib.h. fabs() works on double via math.h. They solve the same mathematical idea (magnitude) but for different numeric types.
Did you know?

C borrowed the name abs from mathematics, but split absolute-value helpers across two headers: integer versions in <stdlib.h> and floating-point versions in <math.h>. That split surprises beginners who expect every “math” operation to live in one place.

Explore C Math Functions

Master abs(), then continue through trigonometry, rounding, and power functions.

Math Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful