Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

<tgmath.h> — type-generic mathematics

The <tgmath.h> header provides macros that select mathematical functions from argument types.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <tgmath.h>

<tgmath.h> includes <math.h> and <complex.h>. Macros such as sqrt select the appropriate function without requiring an explicit suffix.

For ordinary real types, sqrt(float) selects sqrtf, sqrt(double) selects sqrt, and sqrt(long double) selects sqrtl. Calling sqrt with an integer argument selects the double variant. Only arguments corresponding to generic parameters participate in selection. The macros use their own selection rules, not the usual arithmetic conversions. If the implementation supports decimal floating types, the pow macro with one _Decimal32 argument and one integer argument selects the _Decimal64 variant, even though the usual arithmetic conversions give _Decimal32 as the common type for operands of those types.

A complex argument can select a complex function. sqrt(-1.0) alone does not select csqrt. Mixing standard and decimal floating types in generic arguments causes undefined behavior. The example checks types using _Generic and computes a square root.

Examples

#include <stdio.h>
#include <tgmath.h>

int main(void)
{
    printf("float: %d\n", _Generic(sqrt(4.0f), float: 1, default: 0));
    printf("double: %d\n", _Generic(sqrt(4), double: 1, default: 0));
    printf("long double: %d\n", _Generic(sqrt(4.0L), long double: 1, default: 0));
    printf("value: %.0f\n", (double)sqrt(4.0f));
    return 0;
}

Result

float: 1
double: 1
long double: 1
value: 2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources