C fdim() Function

Definition
In C, fdim() returns the positive difference of x and y. If x > y, the result is x - y. Otherwise it is 0.
You pass two double values. The result is a non-negative double. Include <math.h>. On GCC, link with -lm.
Syntax
Pass the first value, then the second. Start with this call.
| Call | What it does |
|---|
fdim(5.0, 2.0) | Returns 3.0 because 5 > 2. |
fdim(2.0, 5.0) | Returns 0.0 because 2 is not greater than 5. |
Include <math.h>. On GCC, link with -lm. This is not the same as fabs(x - y).
Library declarations
double fdim(double x, double y);
float fdimf(float x, float y);
long double fdiml(long double x, long double y);
Parameters
| Parameter | Description |
|---|
| x | Required. First operand of the positive difference. |
| y | Required. Second operand. Subtracted when x is larger. |
Return Value
| Return Value | Description |
|---|
| Non-negative double | x - y when x > y; otherwise 0. Never returns a negative result. |
C Examples
Example 1 — Basic Positive Difference
Show both the positive case and the zero case.
#include <stdio.h>
#include <math.h>
int main(void) {
printf("%.1f\n", fdim(5.0, 2.0));
printf("%.1f\n", fdim(2.0, 5.0));
return 0;
}
How It Works
- Include math.h. That declares
fdim. - x larger. 5 − 2 = 3.
- x smaller. Result clamps to 0.
- Non-negative. You never get a minus sign back.
Example 2 — Amount Above a Threshold
Measure how far a reading sits above a limit.
#include <stdio.h>
#include <math.h>
int main(void) {
double reading = 81.5;
double limit = 80.0;
double over = fdim(reading, limit);
printf("over by %.1f\n", over);
return 0;
}
How It Works
- Read a value. 81.5 is the sample.
- Set a limit. 80.0 is the threshold.
- Call fdim. Only the excess is kept.
- Below limit. Would print 0.0 instead.
Example 3 — Compare with fabs
Absolute difference and positive difference are different tools.
#include <stdio.h>
#include <math.h>
int main(void) {
double x = 2.0;
double y = 5.0;
printf("fdim = %.1f\n", fdim(x, y));
printf("fabs = %.1f\n", fabs(x - y));
return 0;
}
How It Works
- Same inputs. x = 2, y = 5.
- fdim clamps. Because x < y, result is 0.
- fabs keeps distance. Absolute gap is 3.
- Pick intentionally. Choose based on whether order matters.
Frequently Asked Questions
fdim(x, y) returns x - y when x > y, otherwise 0.
x and y are required doubles. The positive difference uses both.
A non-negative double. It never returns a negative number.
Include <math.h>. On GCC, link with -lm.
No. fabs(x - y) is always the absolute gap. fdim returns 0 when x is not greater than y.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful