C Standard Library math.h

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

What You’ll Learn

The <math.h> header is the standard math library for C: trigonometry, powers, roots, logarithms, rounding, and more. Most functions take and return double. You include the header and link with -lm on GCC—a step the old reference omitted from its compile instructions.

01

sqrt pow

Roots/power.

02

sin cos

Trig (rad).

03

log exp

Logs/exp.

04

fabs

Abs value.

05

-lm

Link flag.

06

double

Main type.

Definition and Usage

<math.h> declares functions declared in the C standard for real floating-point math. They operate on double by default; float variants end in f (sinf, sqrtf) and long double variants end in l (sinl, sqrtl).

Trigonometric functions expect radians, not degrees. Invalid inputs (like sqrt(-1)) can return NaN and set errno to EDOM. Huge results may set ERANGE.

💡
Beginner Tip

Compile math programs with gcc program.c -std=c11 -lm -o program. Without -lm, GCC reports undefined references to sqrt, pow, etc.

📝 Syntax

Include the header:

C
#include <math.h>

Common functions by category

  • Trigonometrysin, cos, tan, asin, acos, atan, atan2 (radians).
  • Hyperbolicsinh, cosh, tanh.
  • Power / rootpow, sqrt, cbrt (C99).
  • Exponential / logexp, log, log10, log2 (C99).
  • Roundingfloor, ceil, round, trunc (C99).
  • Utilityfabs, fmod, hypot, fmax, fmin (C99).

Common macros (C99)

  • HUGE_VAL, INFINITY, NAN — special values.
  • FP_NAN, FP_INFINITE, isnan, isfinite — classification.
  • M_PI — often available as an extension (not strict ISO C); use acos(-1.0) if missing.

Typical declarations

C
double sin(double x);
double cos(double x);
double sqrt(double x);
double pow(double base, double exp);
double fabs(double x);
double log(double x);
double exp(double x);

Headers and linking

  • #include <math.h>
  • GCC/Clang: gcc program.c -std=c11 -lm -o program
  • Errors: #include <errno.h> for EDOM / ERANGE
  • Limits: #include <float.h> for DBL_MAX, etc.

⚡ Quick Reference

FunctionComputesExample
pow(x, y)xypow(2, 8) → 256
sqrt(x)√xsqrt(9) → 3
sin(x)sine (radians)sin(0) → 0
fabs(x)|x|fabs(-3.5) → 3.5
log10(x)log10 xlog10(100) → 2
hypot(a,b)√(a²+b²)hypot(3,4) → 5
Degrees
deg * M_PI / 180.0

To radians

Link
gcc ... -lm

Required GCC

Remainder
fmod(7.5, 2.0)

Float mod

Round
floor(x) ceil(x)

Down / up

Examples Gallery

Compile every example with gcc file.c -std=c11 -lm -o out. See also the C Math Functions index for deep dives on each function.

📚 Getting Started

Tour the core functions from the reference, with radians made explicit.

Example 1 — pow, sqrt, Trig, log, exp, fabs

Expanded from the reference with M_PI for 45° and clearer output labels.

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

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

int main(void) {
    double x = 2.0;
    double y = 8.0;
    double angle = M_PI / 4.0;  /* 45 degrees in radians */

    printf("pow(%.1f, %.1f) = %.2f\n", x, y, pow(x, y));
    printf("sqrt(%.1f) = %.2f\n", y, sqrt(y));
    printf("sin(pi/4) = %.2f\n", sin(angle));
    printf("cos(pi/4) = %.2f\n", cos(angle));
    printf("tan(pi/4) = %.2f\n", tan(angle));
    printf("log(%.1f) = %.2f\n", x, log(x));
    printf("log10(%.1f) = %.2f\n", y, log10(y));
    printf("exp(%.1f) = %.2f\n", x, exp(x));
    printf("fabs(-%.1f) = %.2f\n", x, fabs(-x));

    return 0;
}

How It Works

M_PI / 4 is 45° in radians—that is why sin and cos are both ~0.71 and tan is 1. Link with -lm so the linker finds these functions.

Example 2 — Convert Degrees to Radians

The fix every beginner needs before calling sin or cos.

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

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

double deg_to_rad(double degrees) {
    return degrees * M_PI / 180.0;
}

int main(void) {
    double deg = 30.0;
    double rad = deg_to_rad(deg);

    printf("%.0f degrees = %.4f radians\n", deg, rad);
    printf("sin(30 deg) = %.4f\n", sin(rad));
    printf("cos(30 deg) = %.4f\n", cos(rad));

    return 0;
}

How It Works

Multiply degrees by π/180 before passing to trig functions. sin(30) without conversion would be wrong—that is 30 radians, not 30 degrees.

📈 Practical Patterns

Distance, remainder, and rounding with math.h.

Example 3 — Distance with hypot

Safer than sqrt(a*a + b*b) for large values—avoids overflow.

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

int main(void) {
    double dx = 3.0;
    double dy = 4.0;

    printf("Distance from (0,0) to (%.0f,%.0f) = %.1f\n",
           dx, dy, hypot(dx, dy));

    return 0;
}

How It Works

Classic 3-4-5 triangle. hypot computes √(dx² + dy²) with better numerical stability than manual squaring.

Example 4 — Floating Remainder with fmod

Like % for integers, but for double values.

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

int main(void) {
    double value = 7.5;
    double step = 2.0;
    double rem = fmod(value, step);

    printf("fmod(%.1f, %.1f) = %.1f\n", value, step, rem);
    printf("%.1f = %.0f * %.1f + %.1f\n",
           value, step, floor(value / step), rem);

    return 0;
}

How It Works

fmod returns the remainder with the same sign as the dividend. Useful for wrapping angles or grid snapping with fractional steps.

Example 5 — floor and ceil

Round down or up to the nearest integer (still returned as double).

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

int main(void) {
    double values[] = { 3.2, 3.7, -2.3 };
    size_t i;

    for (i = 0; i < 3; i++) {
        double v = values[i];
        printf("x=%5.1f  floor=%.0f  ceil=%.0f  round=%.0f\n",
               v, floor(v), ceil(v), round(v));
    }

    return 0;
}

How It Works

floor moves toward −∞; ceil toward +∞. C99 round rounds to nearest, half away from zero. Cast to int only when the value is known to fit.

🚀 Common Use Cases

  • Graphics & games — sin/cos for rotation, hypot for distance.
  • Science & engineering — pow, log, exp for formulas and decay models.
  • Finance — compound interest with pow, rounding with floor/ceil.
  • Signal processing — trigonometry and fmod for phase wrapping.
  • Statistics — logarithms, square roots, error functions.
  • Embedded sensorssqrtf/sinf float variants for speed.

🧠 How math.h Works

1

Include & link

#include <math.h> and -lm on GCC.

Setup
2

Call function

Pass double arguments; convert degrees to radians for trig.

Compute
3

Get double result

Store in double; watch for NaN on invalid input.

Result
=

Standard math in C

Portable, optimized routines instead of hand-written approximations.

📝 Notes

  • Trig functions use radians; convert from degrees with * M_PI / 180.0.
  • Link with -lm on GCC/Clang (not always needed on MSVC).
  • Most functions are defined for double; use sinf for float.
  • Domain errors set errno to EDOM; range errors may set ERANGE.
  • M_PI is not in strict ISO C—provide a fallback #define if needed.
  • For integer absolute value, use abs from <stdlib.h>, not fabs.

⚡ Optimization

libm functions are highly optimized on modern CPUs. Use float variants (sqrtf, sinf) in hot loops with large arrays when precision allows. Avoid calling heavy functions inside tight inner loops when a lookup table or approximation suffices—but for most apps, math.h is plenty fast.

Conclusion

<math.h> is the standard way to do real-number math in C: powers, roots, trig, logs, and rounding. Include the header, link with -lm, pass radians to trig functions, and handle edge cases with errno or input checks.

Explore the C Math Functions hub for dedicated tutorials on sqrt, sin, pow, and every other function in the library.

💡 Best Practices

✅ Do

  • Compile with -lm on GCC/Clang
  • Convert degrees to radians before sin/cos
  • Use hypot for Pythagorean distance
  • Use fabs for floating absolute value
  • Validate input before sqrt of user data

❌ Don’t

  • Pass degrees directly to sin or cos
  • Forget -lm and wonder why linking fails
  • Use pow(x, 0.5) when sqrt(x) is clearer
  • Compare floats with == after chained math calls
  • Assume M_PI exists on every strict compiler

Key Takeaways

Knowledge Unlocked

Five things to remember about math.h

Math in C, explained simply.

5
Core concepts
📚 02

Radians

Not degrees.

Trig
📈 03

double

Default type.

API
📄 04

sqrt pow

Core ops.

Basics
🌐 05

EDOM

Bad input.

errno

❓ Frequently Asked Questions

math.h declares standard mathematical functions: trigonometry (sin, cos, tan), roots and powers (sqrt, pow), logarithms (log, log10), exponentials (exp), rounding (floor, ceil), and utilities like fabs and fmod. Most functions work on double values.
On GCC and many Unix-like toolchains, math functions live in a separate libm library. Compile with gcc program.c -std=c11 -lm -o program. MSVC links math automatically; MinGW/GCC on Windows usually still needs -lm.
Radians. Convert degrees first: radians = degrees * M_PI / 180.0. Forgetting this is the most common beginner mistake with C trigonometry.
M_PI is a common macro for pi (~3.14159). It is not in strict ISO C math.h but is available on many systems (GNU, BSD). Portable alternatives: acos(-1.0) or define your own constant.
sqrt of a negative number returns NaN and may set errno to EDOM (domain error). Check inputs when possible; use fabs or validate before sqrt. See errno.h for error reporting.
This page introduces the header. CodeToFun also has detailed per-function tutorials at /c/math/function (abs, sin, sqrt, pow, and more). Start here for overview and linking; dive into individual functions there.
Did you know?

Before math.h, programmers wrote their own Taylor-series approximations for sine and cosine. Today’s libm uses carefully tuned hardware and software implementations—often one CPU instruction for sqrt on x86. That is why linking -lm pulls in decades of numerical expertise for free.

Explore C Math Functions

30 function tutorials: sin, cos, pow, abs, and more.

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