C fmax() Function

Definition
In C, fmax() returns the larger of two double values. fmax(3.0, 7.0) is 7.0.
You pass two double values. The result is a double. Include <math.h>. On GCC, link with -lm.
Syntax
Pass both values. Start with this call.
| Call | What it does |
|---|
fmax(3.0, 7.0) | Returns 7.0, the larger value. |
fmax(-2.0, -5.0) | Returns -2.0, which is larger than -5.0. |
Include <math.h>. On GCC, link with -lm. For the smaller value, use fmin().
Library declarations
double fmax(double x, double y);
float fmaxf(float x, float y);
long double fmaxl(long double x, long double y);
Parameters
| Parameter | Description |
|---|
| x | Required. First value to compare. |
| y | Required. Second value to compare. |
Return Value
| Return Value | Description |
|---|
| double | The larger of x and y. If one argument is NaN, the other numeric value is typically returned. |
C Examples
Example 1 — Basic Maximum
Compare positive and negative pairs.
#include <stdio.h>
#include <math.h>
int main(void) {
printf("%.1f\n", fmax(3.0, 7.0));
printf("%.1f\n", fmax(-2.0, -5.0));
return 0;
}
How It Works
- Include math.h. That declares
fmax. - Positive pair. 7 is larger than 3.
- Negative pair. −2 is larger than −5.
- Result type. Still a
double.
Example 2 — Raise a Value to a Floor
Use fmax to keep a reading from going below a minimum.
#include <stdio.h>
#include <math.h>
int main(void) {
double reading = -1.5;
double min_ok = 0.0;
double v = fmax(reading, min_ok);
printf("v = %.1f\n", v);
return 0;
}
How It Works
- Start below the floor. reading is −1.5.
- Set the floor. min_ok is 0.
- Call fmax. Result becomes 0.
- Clamp pattern. Pair with
fmin for a high cap.
Example 3 — One NaN Argument
When one side is NaN, fmax prefers the numeric value.
#include <stdio.h>
#include <math.h>
int main(void) {
double n = nan("");
printf("%.1f\n", fmax(n, 4.0));
printf("%.1f\n", fmax(4.0, n));
return 0;
}
How It Works
- Build a NaN.
nan("") makes a quiet NaN. - NaN first. Numeric 4.0 is returned.
- NaN second. Same numeric result.
- Different from fmaximum. C23
fmaximum propagates NaN instead.
Frequently Asked Questions
fmax() returns the larger of two double values. fmax(3, 7) is 7.
x and y are required doubles to compare.
The larger double. If one argument is NaN, the other number is typically returned.
Include <math.h>. On GCC, link with -lm.
fmaximum() is a C23 API with different NaN rules. fmax() is the older math.h maximum.
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