Type-generic math
For ISO C Standard 11 (C11) and later, the <tgmath.h>
header, in addition to including <math.h>
and <complex.h>
, provides macros that invoke a corresponding math function based on the types of the parameters.
C runtime library math functions come in real and complex variants. Each variant comes in three flavors, depending on the type of the argument: float
, double
, and long double
. Because C doesn't support overloading like C++ does, each variant has a different name. For example, to get the absolute value of a real floating-point value, you'd call either fabsf
, fabs
, or fabsl
depending on whether you're passing a float
, double
, or long double
value, respectively. To get the complex absolute value, you'd call one of cabsf
, cabs
, or cabsl
depending on whether you're passing a float
, double
, and long double
complex value, respectively. If the arguments don't match any of the above mentioned types, the function is chosen as though the arguments were doubles.
<tgmath.h>
contains macros that simplify the selection of the right math function to call. The macros examine the type they're passed and then call the right function. For example, the sqrt
macro binds sqrt(9.9f)
to sqrtf()
, but it binds sqrt(9.9)
to sqrt()
. If at least one macro argument for a generic parameter is complex, then the macro binds to a complex function; otherwise, it invokes a real function.
The type-generic macros in <tgmath.h>
allow you to write more portable code because you don't need to manage casting or selecting different function names depending on the type of argument.
These macros are in their own header so that programs written using the <math.h>
header won't break. So double x = sin(42);
behaves as it always has when you include <math.h>. Even so, most existing C programs are expected to be unaffected when the <tgmath.h>
header is included instead of <math.h>
or <complex.h>
.
The following table lists the macros that are available in <tgmath.h>
and what they expand to. modf
isn't included in this table because it doesn't have a corresponding type-generic macro because it isn't clear how to make it safe without complicating type resolution.
Requirements
Compile with /std:c11
.
Windows SDK 10.0.20348.0 (version 2104) or later. See Windows SDK to download the latest SDK. For instructions to install and use the SDK for C11 and C17 development, see Install C11 and C17 support in Visual Studio.