Site Tools


h-tgmath

<tgmath.h>

<tgmath.h> provides type-generic math wrappers (C99) so you can write sqrt instead of sqrtf/sqrt/sqrtl. The dispatcher selects the right function based on argument type at compile time.

Precision-critical code often prefers explicit suffixes for clarity.

Example

This example shows type-generic dispatch to different precision functions.

// compile: gcc -o tgmathexample tgmathexample.c -lm
// run: ./tgmathexample
// description: type-generic dispatch to float/double/long-double variants
 
#include <tgmath.h>
#include <stdio.h>
 
int main() {
    float f = 2.0f;
    double d = 2.0;
    long double ld = 2.0L;
 
    printf("sqrt(float)       = %.10f\n", (double)sqrt(f));
    printf("sqrt(double)      = %.10f\n", sqrt(d));
    printf("sqrt(long double) = %.10Lf\n", sqrt(ld));
 
    return 0;
}

Common function wrappers

All math functions from <math.h> are available type-generically. Common ones:

Root and power:

  • sqrt(x), cbrt(x), pow(x, y), hypot(x, y)

Exponential and logarithm:

  • exp(x), exp2(x), exp10(x), log(x), log2(x), log10(x)

Trigonometric:

  • sin(x), cos(x), tan(x), asin(x), acos(x), atan(x), atan2(y, x)

Hyperbolic:

  • sinh(x), cosh(x), tanh(x), asinh(x), acosh(x), atanh(x)

Rounding and absolute value:

  • ceil(x), floor(x), round(x), trunc(x), fabs(x), fmod(x, y)

Note: For precision-critical code, explicit function variants (e.g., sqrtf, sqrt, sqrtl) are preferred over type-generic dispatch.

h-tgmath.md · Last modified: by 127.0.0.1