--- Cannot embed stylesheet: [Errno 2] No such file or directory: '../../../aros.css' --->
On AROS standardized C interfaces are implemented with a few shared libraries. A distinction is made between a standard ANSI-C/ISO-C part and a POSIX emulation layer. Here the ANSI-C/ISO-C part is documented. The ANSI-C/ISO-C part is implemented by the stdc.library and the stdcio.library shared libraries. The former implements the part that only depends on exec.library; the latter the parts that depends on other libraries like dos.library and contains mostly I/O related functions. Currently both libraries are disk based but the plan is in the future put stdc.library in ROM and be initialized right after exec so that all modules, also those in ROM can use it. stdcio.library will likely stay disk based. Purpose of these libraries is to provide a base implementation that can be used by compilers. Compilers are free to override functions with their own implementation. The reference used for the developing the two libraries is the ISO/IEC standard document ISO/IEC 9899:1999 also known as C99. Not all functions are implemented but for each function defined in the standard a place in the library is reserved. The order of the functions in the library lookup table is based on the order that they are defined in the standard document. Not all functions are implemented. Not implemented functions either are not available in the library at all or just a stub function is provided. The latter can be used to get programs running without having a proper implementation of a function. Of course target should be to have in the end all functions implemented. Consult the include files and the autodocs to see which functions are not (fully) implemented. The include files provided for the C99 code implement a proper separation of the include files. The includes should only define the prototypes as defined by the standard. This means includes like proto/stdc.h or proto/stdcio.h should not be included in the standard C99 include files. Developers improving or extending these libraries should keep this in mind. In order to use the stdc.library programs need to properly initialize the library using the __stdc_progam_startup() and __stdc_program_end() functions. It is assumed that this is taken care of by the startup code provided by the compiler.
posixc.library/--background_posixc--
Currently no real locale support is provided by stdc.library. All locale related functions have a minimal implementation assuming only a "C" locale. Implementing proper locale support will need careful development to have a consistent integration with locale.library. People with ideas can always post on the AROS development mailing list.
locale.h --background_wchar-- --background_c99--
Contrary to the other include files; almost all string functions are made part of stdc.library include the POSIX and the SAS/C ones. These string functions are most of the small and don't depend on other code. Doing it this way avoids having code that only uses non C99 string functions having a dependency on posixc.library.
--background_locale-- --background_c99--
wchar.h/wctype.h is not implemented by stdc.library. It is left to the compiler to provide their implementation of wchar support. No system functions should thus at the moment use wchar as implementation is compiler dependent.
--background_locale-- --background_c99--
void __assert( const char * expr, const char * file, unsigned int line)
This is a function that is used for implementation of the C99 assert() function.
expr - The expression to evaluate. The type of the expression does
not matter, only if its zero/NULL or not.
file - Name of the source file.
line - Line number of assert() call.
The function doesn't return.
Different versions of this function are available. This function is used when a program is using stdc.library but not stdcio.library or posixc.library. Because no normal DOS file I/O is available an attempt will be made to display the assertion in a requester and thus deviating from the C99 standard that says it to go to the error stream.
int __cxa_atexit( void (*func)(void *, int), void *arg, void *d)
Registers a cleanup function to be called when the program terminates via exit() or when a shared object (DSO) is unloaded. This function is primarily used by C++ compilers to handle destruction of static and global objects associated with shared libraries.
func - Pointer to the function to be called on exit or unload.
The function must accept a void pointer and an int as arguments.
arg - Argument to be passed to the function when it is called.
d - The DSO handle with which the function is associated.
Returns 0 on success, or -1 if there is insufficient memory to register the function.
void my_cleanup(void *arg, int status) {
// Perform cleanup
}
__cxa_atexit(my_cleanup, my_data, my_dso_handle);
The function is called with (arg, status) arguments, where status is usually zero. The `d` parameter is used to manage which functions to call when a specific shared object is unloaded.
This function is not intended for use in user code; it is called automatically by the C++ runtime.
void __cxa_finalize( void *d)
Call all functions registered via __cxa_atexit() that match the specified DSO handle. If the handle is NULL, all registered functions are called in reverse order of registration. This is typically called automatically when a shared object is unloaded or during normal process termination to run global destructors.
d - Dynamic shared object (DSO) handle, or NULL to finalize all.
None.
This function is part of the C++ runtime support and is not meant to be called by user code. It is invoked by the runtime to clean up static or global objects.
AROS doesnt support Dynamic shared objects, so the DSO handle will always be NULL.
int __fpclassifyd( double d)
Classify d as zero, subnormal, normal, infinite or NaN.
d - Value to classify.
Return one of the following constants from <math.h>: FP_ZERO - Zero. FP_SUBNORMAL - A finite, nonzero subnormal value. FP_NORMAL - A finite, nonzero value that is not subnormal. FP_INFINITE - Infinity. FP_NAN - Not a number. The sign does not affect the result.
Use fpclassify() for type-generic classification.
int __fpclassifyf( float f)
Classify f as zero, subnormal, normal, infinite or NaN.
f - Value to classify.
Return one of the following constants from <math.h>: FP_ZERO - Zero. FP_SUBNORMAL - A finite, nonzero subnormal value. FP_NORMAL - A finite, nonzero value that is not subnormal. FP_INFINITE - Infinity. FP_NAN - Not a number. The sign does not affect the result.
Use fpclassify() for type-generic classification.
int __fpclassifyl( long double e)
Classify e as zero, subnormal, normal, infinite or NaN.
e - Value to classify.
Return one of the following constants from <math.h>: FP_ZERO - Zero. FP_SUBNORMAL - A finite, nonzero subnormal value. FP_NORMAL - A finite, nonzero value that is not subnormal. FP_INFINITE - Infinity. FP_NAN - Not a number. The sign does not affect the result.
Use fpclassify() for type-generic classification.
On ARM and PowerPC builds with an 11-bit long-double exponent, infinity and NaN incorrectly return FP_NORMAL.
int __isfinite( double d)
Determine whether d is finite.
d - Value to classify.
Return 1 for zero, subnormal and normal values; return 0 for infinity and NaN. The sign does not affect the result.
Include <math.h>. Use isfinite() for type-generic classification.
int __isfinitef( float f)
Determine whether f is finite.
f - Value to classify.
Return 1 for zero, subnormal and normal values; return 0 for infinity and NaN. The sign does not affect the result.
Include <math.h>. Use isfinite() for type-generic classification.
int __isfinitel( long double e)
Determine whether e is finite.
e - Value to classify.
Return 1 for zero, subnormal and normal values; return 0 for infinity and NaN. The sign does not affect the result.
Include <math.h>. Use isfinite() for type-generic classification.
On ARM and PowerPC builds with an 11-bit long-double exponent, infinity and NaN incorrectly return 1.
int __isinf( double d)
Determine whether d is infinite.
d - Value to examine.
Return 1 for positive or negative infinity; return 0 for finite values and NaN.
Include <math.h>. Use isinf() for type-generic calls.
int __isinff( float f)
Determine whether f is infinite.
f - Value to examine.
Return 1 for positive or negative infinity; return 0 for finite values and NaN.
Include <math.h>. Use isinf() for type-generic calls.
int __isinfl( long double e)
Determine whether e is infinite.
e - Value to examine.
Return 1 for positive or negative infinity; return 0 for finite values and NaN.
Include <math.h>. Use isinf() for type-generic calls.
On ARM and PowerPC builds with an 11-bit long-double exponent, this function always returns 0.
int __isnan( double d)
Determine whether d is NaN.
d - Value to examine.
Return 1 for NaN; return 0 for finite values and infinity. The sign does not affect the result.
Include <math.h>. Use isnan() for type-generic calls.
int __isnanf( float f)
Determine whether f is NaN.
f - Value to examine.
Return 1 for NaN; return 0 for finite values and infinity. The sign does not affect the result.
Include <math.h>. Use isnan() for type-generic calls.
int __isnanl( long double e)
Determine whether e is NaN.
e - Value to examine.
Return 1 for NaN; return 0 for finite values and infinity. The sign does not affect the result.
Include <math.h>. Use isnan() for type-generic calls.
On ARM and PowerPC builds with an 11-bit long-double exponent, this function always returns 0.
int __isnormal( double d)
Determine whether d is a normal floating-point value.
d - Value to classify.
Return 1 for a finite, nonzero value that is not subnormal; return 0 for zero, subnormal values, infinity and NaN. The sign does not affect the result.
Include <math.h>. Use isnormal() for type-generic classification.
int __isnormalf( float f)
Determine whether f is a normal floating-point value.
f - Value to classify.
Return 1 for a finite, nonzero value that is not subnormal; return 0 for zero, subnormal values, infinity and NaN. The sign does not affect the result.
Include <math.h>. Use isnormal() for type-generic classification.
int __isnormall( long double e)
Determine whether e is a normal floating-point value.
e - Value to classify.
Return 1 for a finite, nonzero value that is not subnormal; return 0 for zero, subnormal values, infinity and NaN. The sign does not affect the result.
Include <math.h>. Use isnormal() for type-generic classification.
On ARM and PowerPC builds with an 11-bit long-double exponent, infinity and NaN incorrectly return 1.
int __signbit( double d)
Test the sign bit of d.
d - Value to examine.
Return 1 if the sign bit is set; otherwise return 0. This distinguishes negative zero from positive zero and also applies to infinities and NaNs.
Include <math.h>. Use signbit() for type-generic calls.
int __signbitf( float f)
Test the sign bit of f.
f - Value to examine.
Return 1 if the sign bit is set; otherwise return 0. This distinguishes negative zero from positive zero and also applies to infinities and NaNs.
Include <math.h>. Use signbit() for type-generic calls.
int __signbitl( long double e)
Test the sign bit of e.
e - Value to examine.
Return 1 if the sign bit is set; otherwise return 0. This distinguishes negative zero from positive zero and also applies to infinities and NaNs.
Include <math.h>. Use signbit() for type-generic calls.
int *__stdc_get_errorptr( void)
This function gets the pointer to store error return value for program exit.
-
pointer to return value
int __stdc_gmtoffset( void)
The offset to GMT in minutes
Will return 0 when locale.library is not loaded into memory yet.
void __stdc_inherit_mempool(
int inherit );
Decide which pool the stdc.library bases this task opens from now on will use.
inherit - non-zero to share the pool of the task that created this
one, zero to have the next base create a pool of its own.
-
This function is private to the C runtime. posixc.library calls it for pthread workers and for the vfork() child, which belong to the program of their creator. Any stdc.library base may be used for the call. Available from stdc.library 0.50.
void __stdc_jmp2exit( int normal, int retcode)
This function directly jumps to the exit of a program.
normal - Indicates if exit is normal or not. When it is abnormal no
atexit functions will be called.
retcode - the return code for the program.
-
In normal operation this function does not return. If this function returns it means that this function was called in a context where jmp_buf for exit was not initialized. Likely cause is a module that opened stdc.library. Be sure to capture this situation.
void __stdc_program_end( void)
This function is to be called when main() has returned or after program has exited. This allows to stdc.library to do some cleanup that can't be done during closing of the library.
-
-
This function is normally called by the startup code so one should not need to do it oneself. TODO: Maybe this function should be implemented using Tags so that functionality can be extended in the future without breaking backwards compatibility.
void __stdc_program_startup( jmp_buf exitjmp, int *errorptr)
This is called during program startup and before calling main. This is to allow stdc.library to do some initialization that couldn't be done when opening the library.
exitjmp - jmp_buf to jump to to exit the program errorptr - pointer to store return value of program
-
This function is normally called by the startup code so one should not need to do it oneself. TODO: Maybe this function should be implemented using Tags so that functionality can be extended in the future without breaking backwards compatibility.
int *__stdc_set_errorptr( int *errorptr)
This function sets the pointer to store error return value for program exit.
errorptr - new pointer to return value
old pointer to return value
void __stdc_set_exitjmp( jmp_buf exitjmp, jmp_buf previousjmp)
This function set the jmp_buf to use for directly exiting current program.
exitjmp - new jmp_buf for exiting
previous jmp_buf for exiting
void __stdc_set_taskexit( void (*taskexit)(int returncode))
Set how exit(), abort() and an unhandled signal end a task that shares the program's stdc.library base but is not the task that started the program, such as a thread.
taskexit - Called with the exit code in such a task; it must not
return. NULL leaves such a task waiting forever.
-
This function is private and meant for threading libraries; the pthread link library sets a function that calls pthread_exit(). exit() cannot run the program's exit code in such a task: that code has to run on the stack of the program's task. Before taskexit is called the program's task is sent SIGBREAKF_CTRL_C.
char ***__stdcio_get_environptr( void)
This function the get pointer to the child environ global variable currently used by posixc.library.
-
environptr - ptr to the child environ variable (== &environ).
NULL is return if envirion emulation is disabled.
char ***__stdcio_get_envlistptr( void)
-
Private - do not use!
int __stdcio_set_environptr( char ***environptr)
This function is called to enable environ emulation mode.
environptr - ptr to the child environ variable (== &environ).
0 on fail, other value on success
This function will enable environ emulation. This means that all current DOS local variables are converted to the 'var=value' format and be accessible through char **environ.
At the moment only a static list is supported. getenv() and setenv() don't use this yet so changes done with these functions are not reflected in environ. This is still TODO.
int __stdcio_set_envlistptr( char ***envlistptr)
Private - do not use!
int __vcformat( void * data, int (* outc)(int, void *), const char * format, va_list args)
Format a list of arguments and call a function for each char to print.
data - This is passed to the user callback outc as its second argument.
outc - Call this function for every character that should be
emitted. The function should return EOF on error and
> 0 otherwise.
format - A printf() format string.
args - A list of arguments for the format string.
The number of characters written.
int __vwformat( void * data, wint_t (* outwc)(wchar_t, void *), const wchar_t * format, va_list args)
Formats a list of arguments according to the provided wide-character format string and emits each resulting wide character through a callback function.
data - A user-supplied pointer passed as the second argument to
the outwc() callback function.
outwc - A callback function invoked for each wide character to output.
The callback receives the character and the data pointer.
It should return EOF on error or a positive value on success.
format - A wide-character printf() format string containing
formatting directives.
args - A va_list containing the arguments for the format string.
The number of wide characters successfully written, or a negative value on error.
This is a generic backend used to implement wide-character printf functions. It handles parsing of printf-style format specifiers and passes formatted output one character at a time to the caller's output function.
Some format specifiers may not yet be implemented or fully support wide-character variations.
int __vwscanf( void * data, wint_t (* get_wchar)(void *), int (* unget_wchar)(wint_t, void *), const wchar_t * format, va_list args)
Core wide-character scanf parser. Reads formatted wide-character input from the data source using the provided get/unget character functions, parsing according to the given format string, and stores the results into the locations described by the argument list.
data - Opaque pointer passed to get_wchar and unget_wchar get_wchar - Function to read the next character from the input unget_wchar - Function to push back a character into the input format - How to convert the input into the arguments args - List of argument pointers to receive results
The number of converted arguments.
void _Exit( int code)
Terminates the running program immediately. The code is returned to the program which has called the running program. In contrast to exit(), this function does not call user exit-handlers added with atexit() or on_exit(). It does, however, close open filehandles.
code - Exit code. 0 for success, other values for failure.
None. This function does not return.
This function must not be used in a shared library or in a threaded application.
void abort( void)
Causes abnormal program termination. If there is a signal handler for SIGABORT, then the handler will be called. If the handler returns, then the program is aborted anyway.
None.
None. This function does not return.
if (fatal_error)
abort ();
This function must not be used in a shared library or in a threaded application.
Signal handling is not implemented yet.
int abs( int j)
Compute the absolute value of j.
j - A signed integer
The absolute value of j.
// returns 1 abs (1); // returns 1 abs (-1);
double acos( double x)
Computes the principal value of the arc cosine of x.
x - a double value in the domain [-1.0, 1.0]
The arc cosine of x, in radians, in the range [0, p].
double y = acos(0.0); // y = p/2 ˜ 1.57079632679 double z = acos(1.0); // z = 0.0
acos(x) returns NaN if x is outside the domain [-1,1].
None known beyond domain restrictions.
float acosf( float x)
Computes the principal value of the arc cosine of x.
x - a float value in the domain [-1.0f, 1.0f]
The arc cosine of x, in radians, in the range [0, p].
float y = acosf(0.5f); // y ˜ 1.0471975512f (p/3) float z = acosf(-1.0f); // z = p
acosf(x) returns NaN if x is outside [-1,1].
Precision loss near domain boundaries possible.
double acosh( double x)
Computes the inverse hyperbolic cosine of x.
x - a double value where x >= 1.0
The inverse hyperbolic cosine of x.
double y = acosh(1.0); // y = 0.0 double z = acosh(2.0); // z ˜ 1.3169578969
acosh(x) is defined only for x = 1. Returns NaN and sets errno to EDOM if x < 1. For large x, acosh(x) ˜ ln(2x).
None known beyond domain restrictions.
float acoshf( float x)
Computes the inverse hyperbolic cosine of x.
x - a float value where x >= 1.0f
The inverse hyperbolic cosine of x.
float y = acoshf(1.0f); // y = 0.0f float z = acoshf(3.0f); // z ˜ 1.7627471740f
Defined only for x = 1. Returns NaN and sets errno if input is outside domain. Uses approximations for numerical stability.
Minor precision loss near x=1.
long double acoshl( long double x)
Computes the inverse hyperbolic cosine of `x`.
x - the value whose inverse hyperbolic cosine is to be calculated.
Must be greater than or equal to 1.
Returns the inverse hyperbolic cosine of `x`. If `x` < 1, returns NaN and sets errno to EDOM.
double r = acosh(2.0); // returns ~1.317
The result is always non-negative.
None known.
long double acosl( long double x)
Computes the arc cosine (inverse cosine) of the input value `x`.
x - the value whose arc cosine is to be calculated. Must be in the
range [-1, 1].
Returns the arc cosine of `x`, in radians, in the range [0, p]. If `x` is outside the valid domain, returns NaN and sets errno to EDOM.
double angle = acos(0.5); // returns ~1.047 (60 degrees in radians)
For values outside [-1, 1], the result is a domain error. For x == ±1, the result is 0 or p respectively.
None known.
void *aligned_alloc( size_t alignment, size_t size)
Allocate aligned memory.
alignment - Alignment of allocated memory. The address of the
allocated memory will be a multiple of this value, which
must be a power of two and a multiple of sizeof(void *).
size - How much memory to allocate.
Returns zero on success. Returns EINVAL if the alignment parameter was not a power of two, or was not a multiple of sizeof(void *). Returns ENOMEM if there was insufficient memory to fulfill the request.
Memory allocated by aligned_alloc() should be freed with free(). If not, it will be freed when the program terminates. If an error occurs, errno will not be set.
uint32_t arc4random( void)
Return a single 32-bit cryptographically-strong random value. The value is obtained from entropy.resource (a ChaCha20 CSPRNG seeded from software and, where available, CPU hardware entropy). If the resource is not present a self-contained fallback is used so that the function always returns a value.
None.
A uniformly-distributed random value in the range [0, 2^32).
uint32_t token = arc4random();
Unlike rand()/random(), this generator is not seeded by the caller and has no reproducible sequence; it is suitable for keys, nonces, tokens and similar security-sensitive uses.
void arc4random_buf( void *buf, size_t nbytes)
Fill a buffer with cryptographically-strong random bytes. The bytes are obtained from entropy.resource (a ChaCha20 CSPRNG seeded from software and, where available, CPU hardware entropy). If the resource is not present a self-contained fallback is used so that the buffer is always filled.
buf - the buffer to fill. nbytes - the number of bytes to write.
None.
unsigned char key[32]; arc4random_buf(key, sizeof(key));
A NULL buf or a zero nbytes is a harmless no-op.
uint32_t arc4random_uniform( uint32_t upper_bound)
Return a cryptographically-strong random value, uniformly distributed and free of modulo bias, in the range [0, upper_bound).
upper_bound - the exclusive upper bound.
A uniformly-distributed random value in [0, upper_bound). If upper_bound is 0 or 1 the result is 0.
// an unbiased dice roll in 1..6 int roll = 1 + arc4random_uniform(6);
Rejection sampling is used to avoid the bias a plain arc4random() % upper_bound would introduce when upper_bound does not evenly divide 2^32.
char * asctime( const struct tm * tm)
The asctime() function converts the broken-down time value tm into a string. See asctime_r() for details.
tm - The broken down time
A statically allocated buffer with the converted time. Note that the contents of the buffer might get lost with the call of any of the date and time functions.
time_t tt; struct tm * tm; char * str; // Get time time (&tt); // Break time up tm = localtime (&tt); // Convert to string str = asctime (tm);
The returned string is buffered per stdc.library base.
double asin( double x)
Computes the principal value of the arc sine of x.
x - a double value in the domain [-1.0, 1.0]
The arc sine of x, in radians, in the range [-p/2, p/2].
double y = asin(0.0); // y = 0.0 double z = asin(1.0); // z = p/2 ˜ 1.57079632679
Returns NaN if |x| > 1 and sets errno to EDOM. Accurate for inputs close to domain boundaries.
None known beyond domain checks.
float asinf( float x)
Computes the principal value of the arc sine of x.
x - a float value in the domain [-1.0f, 1.0f]
The arc sine of x, in radians, in the range [-p/2, p/2].
float y = asinf(0.5f); // y ˜ 0.5235987756f (p/6) float z = asinf(-1.0f); // z = -p/2
Returns NaN if input is outside [-1,1], with errno set. Precision may degrade near domain limits.
Minor precision issues near domain edges.
double asinh( double x)
Computes the inverse hyperbolic sine of x.
x - a double value (any real number)
The inverse hyperbolic sine of x.
double y = asinh(0.0); // y = 0.0 double z = asinh(1.0); // z ˜ 0.8813735870
asinh is defined for all real numbers. For large |x|, asinh(x) ˜ ln(2x), ensuring precision. Returns NaN if input is NaN.
None known.
float asinhf( float x)
Computes inverse hyperbolic sine (float version).
x - real float.
asinhf(x)
float v = asinhf(1.0f); // ˜ 0.881373f
Accurate for small and large x.
None known.
long double asinl( long double x)
Computes the arc sine (inverse sine) of the input value `x`.
x - the value whose arc sine is to be calculated. Must be in the
range [-1, 1].
Returns the arc sine of `x`, in radians, in the range [-p/2, p/2]. If `x` is outside the valid domain, returns NaN and sets errno to EDOM.
double angle = asin(0.5); // returns ~0.524 (30 degrees in radians)
For values outside [-1, 1], the result is a domain error.
None known.
int asprintf( char **restrict str, const char *restrict format, ...)
Analog of sprintf, except that sotrage is allocated for a string large enough to hold the output including the terminating null byte
str - Where to store the pointer for the allocated string. format - A printf() format string. ... - Arguments for the format string
The number of characters written, or EOF on error.
void assert( expr)
Evaluates the expression expr and if it's FALSE or NULL, then printf a message and aborts the program. The message will contain the expression, the name of the file with the assert in it and the line in the file.
expr - The expression to evaluate. The type of the expression does
not matter, only if it's zero/NULL or not.
The function doesn't return.
// Make sure that x equals 1 assert (x==1);
Normally the output is sent to stderr and thus this code should only be called from processes with the context of the process available. In low level modules it is advised to use the ASSERT() macro for aros/debug.h. As a last resort one can use the normal assert() macro but link with the kernelassert static link library to get a version that also outputs to kernel debug output. With this assert also an Alert will be generated in place of abort of the program.
int at_quick_exit( void (*func)(void))
Register a function to be called, without arguments, by quick_exit(). Registered functions are called in the reverse order of registration.
func - the function to register.
0 on success, non-zero on failure.
Handlers registered with at_quick_exit() are independent of those registered with atexit(); only quick_exit() calls them.
double atan( double x)
Computes the principal value of the arc tangent of x.
x - a double value (any real number)
The arc tangent of x, in radians, in the range [-p/2, p/2].
double y = atan(0.0); // y = 0.0 double z = atan(1.0); // z = p/4 ˜ 0.78539816339
atan(x) is defined for all real numbers. Returns NaN if input is NaN.
None known.
double atan2( double y, double x)
Computes the arc tangent of y/x using the signs of both arguments to determine the correct quadrant of the return value.
y - numerator (double) x - denominator (double)
The angle ? between the positive x-axis and the point (x,y), in radians, in the range [-p, p].
double angle = atan2(1.0, 1.0); // ˜ p/4 (0.78539816339) double angle2 = atan2(-1.0, -1.0); // ˜ -3p/4 (-2.35619449019)
Handles cases where x is zero to avoid division by zero. Returns NaN if either argument is NaN. Returns ±p/2 if x = 0 and y ? 0.
None known.
float atan2f( float y, float x)
Computes the arc tangent of y/x with correct quadrant determination.
y - numerator (float) x - denominator (float)
The angle ? between the positive x-axis and the point (x,y), in radians, in the range [-p, p].
float angle = atan2f(0.0f, -1.0f); // p float angle2 = atan2f(1.0f, 0.0f); // p/2
Correctly handles special cases (x = 0, y = 0). Returns NaN if either argument is NaN.
None known.
long double atan2l( long double y, long double x)
Computes the arc tangent of y/x considering the signs of both arguments to determine the correct quadrant of the result.
y - the vertical component. x - the horizontal component.
Returns angle in radians in the range [-p, p]. Returns NaN and sets errno to EDOM if x and y are both 0.
long double angle = atan2l(1.0L, -1.0L); // returns ~2.356L
This is the long double precision variant of atan2().
None known.
float atanf( float x)
Computes the principal value of the arc tangent of x.
x - a float value (any real number)
The arc tangent of x, in radians, in the range [-p/2, p/2].
float y = atanf(0.0f); // y = 0.0f float z = atanf(-1.0f); // z = -p/4 ˜ -0.78539816339f
Defined for all real floats. Returns NaN if input is NaN.
None known.
double atanh( double x)
Computes the inverse hyperbolic tangent of x.
x - a double value.
The inverse hyperbolic tangent of x.
double y = atanh(0.5); // y ˜ 0.5493061443
Domain is (-1, 1); outside this range returns NaN. Returns ±Inf if x is ±1. Returns NaN if input is NaN. The function satisfies atanh(x) = 0.5 * ln((1+x)/(1-x)).
May lose precision near domain boundaries.
float atanhf( float x)
Computes the inverse hyperbolic tangent of x (float version).
x - value in range (-1, 1).
atanhf(x)
float v = atanhf(0.5f); // ˜ 0.5493f
Returns NaN for |x| = 1. Very large values close to 1 may result in loss of precision.
None known.
long double atanhl( long double x)
Computes the inverse hyperbolic tangent of `x`.
x - the value whose inverse hyperbolic tangent is to be calculated.
Must be in the range (-1, 1).
Returns the inverse hyperbolic tangent of `x`. Returns NaN and sets errno to EDOM if |x| > 1. Returns ±infinity and sets errno to ERANGE if |x| == 1.
double r = atanh(0.5); // returns ~0.549
The function is odd: atanh(-x) = -atanh(x).
None known.
long double atanl( long double x)
Computes the arc tangent of x in radians.
x - a long double value.
Returns value in range [-p/2, p/2].
long double r = atanl(1.0L); // returns ~0.785L
Long double precision version of atan().
None known.
int atexit( void (*func)(void))
Registers the given function to be called at normal process termination.
func - function to be called.
double atof( const char * str)
Convert a string of digits into a double.
str - The string which should be converted. Leading
whitespace are ignored. The number may be prefixed
by a '+' or '-'.
The value of string str.
int atoi( const char * str)
Convert a string of digits into an integer.
str - The string which should be converted. Leading
whitespace are ignored. The number may be prefixed
by a '+' or '-'.
The value of string str.
// returns 1
atoi (" \t +1");
// returns 1
atoi ("1");
// returns -1
atoi (" \n -1");
long atol( const char * str)
Convert a string of digits into an long integer.
str - The string which should be converted. Leading
whitespace are ignored. The number may be prefixed
by a '+' or '-'.
The value of string str.
// returns 1
atol (" \t +1");
// returns 1
atol ("1");
// returns -1
atol (" \n -1");
long long atoll( const char * str)
Convert a string of digits into an long long integer.
str - The string which should be converted. Leading
whitespace are ignored. The number may be prefixed
by a '+' or '-'.
The value of string str.
// returns 1
atoll (" \t +1");
// returns 1
atoll ("1");
// returns -1
atoll (" \n -1");
void * bsearch( const void * key, const void * base, size_t count, size_t size, int (* comparefunction)(const void *, const void *))
Search in a sorted array for an entry key.
key - Look for this key.
base - This is the address of the first element in the array
to be searched. Note that the array *must* be sorted.
count - The number of elements in the array
size - The size of one element
comparefunction - The function which is called when two elements
must be compared. The function gets the addresses of two
elements of the array and must return 0 is both are equal,
< 0 if the first element is less than the second and > 0
otherwise.
A pointer to the element which equals key in the array or NULL if no such element could be found.
t_t btowc( int c) FUNCTION The btowc() function converts a single byte character (in the range of unsigned char) to its corresponding wide character representation, according to the current multibyte encoding in the current locale. If the input is EOF or does not correspond to a valid single-byte multibyte character, WEOF is returned.
c - A single byte character as an int (must be representable as
unsigned char or EOF).
Returns the corresponding wide character (wint_t) if the conversion succeeds. Returns WEOF if the input is EOF or an invalid multibyte sequence.
wint_t wc = btowc((int)'A');
This function only works for single-byte multibyte characters. It is intended to be used with byte input where the encoding may vary depending on the locale. It uses mbrtowc() internally with a zero-initialized conversion state.
If called with a multibyte encoding that requires more than one byte per character (e.g., UTF-8 for non-ASCII), this function will fail for non-ASCII characters.
size_t c16rtomb( char * restrict s, char16_t c16, mbstate_t * restrict ps)
Converts a 16-bit (UTF-16) code unit to its multibyte representation. A high surrogate is buffered until the following low surrogate is supplied, at which point the combined code point is emitted.
s - Where to store the multibyte sequence (may be NULL). c16 - The UTF-16 code unit to convert. ps - Conversion state (a static internal state is used if NULL).
The number of bytes stored (0 when a high surrogate is buffered and no output is produced yet), or (size_t)-1 on an encoding error (errno = EILSEQ).
Only UTF-8 output is supported.
size_t c32rtomb( char * restrict s, char32_t c32, mbstate_t * restrict ps)
Converts a single 32-bit (UTF-32) character to its multibyte representation.
s - Where to store the multibyte sequence (may be NULL). c32 - The character to convert. ps - Conversion state (a static internal state is used if NULL).
The number of bytes stored, or (size_t)-1 on an encoding error (errno = EILSEQ).
char32_t holds a complete Unicode code point, so on AROS - where wchar_t is 32 bits wide - this is equivalent to wcrtomb().
double complex cabs( double complex z)
Computes the magnitude (absolute value) of a complex number.
z - complex number.
The magnitude sqrt(real(z)^2 + imag(z)^2).
double complex z = 3.0 + 4.0*I; double r = cabs(z); // r = 5.0
Avoids overflow/underflow by scaling.
None known.
float cabsf( float complex z)
Computes magnitude of complex float.
z - complex number.
sqrt(Re(z)^2 + Im(z)^2)
float complex z = 3.0f + 4.0f*I; float v = cabsf(z); // 5.0
Uses scaling to avoid overflow/underflow.
None known.
long double cabsl( long double x)
Computes absolute value (modulus) of complex long double number.
x - complex number (real and imaginary parts)
Returns magnitude sqrt(real² + imag²).
long double r = cabsl(3.0 + 4.0iL); // 5.0L
Scales input to prevent overflow/underflow.
None known.
void * calloc( size_t count, size_t size)
Allocate size bytes of memory, clears the memory (sets all bytes to 0) and returns the address of the first byte.
count - How many time size size - How much memory to allocate.
A pointer to the allocated memory or NULL. If you don't need the memory anymore, you can pass this pointer to free(). If you don't, the memory will be freed for you when the application exits.
double carg( double complex z)
Return the principal argument of z, in radians, with a branch cut along the negative real axis. The angle is calculated by atan2(cimag(z), creal(z)).
z - Complex input value.
An angle in the interval [-pi, pi]. The signs of zero select the side of the branch cut. With a negative real component, imaginary +0 gives +pi and imaginary -0 gives -pi. An imaginary zero with positive real part is preserved. Infinite components select the corresponding axis or quadrant angle; a NaN component produces NaN.
Include <complex.h>.
float cargf( float complex z)
Return the principal argument of z, in radians, with a branch cut along the negative real axis. The angle is calculated by atan2f(cimagf(z), crealf(z)).
z - Complex input value.
An angle in the interval [-pi, pi]. The signs of zero select the side of the branch cut. With a negative real component, imaginary +0 gives +pi and imaginary -0 gives -pi. An imaginary zero with positive real part is preserved. Infinite components select the corresponding axis or quadrant angle; a NaN component produces NaN.
Include <complex.h>.
long double cargl( long double complex z)
Return the principal argument of z, in radians, with a branch cut along the negative real axis. The angle is calculated by atan2l(cimagl(z), creall(z)).
z - Complex input value.
An angle in the interval [-pi, pi]. The signs of zero select the side of the branch cut. With a negative real component, imaginary +0 gives +pi and imaginary -0 gives -pi. An imaginary zero with positive real part is preserved. Infinite components select the corresponding axis or quadrant angle; a NaN component produces NaN. Signed-zero pairs differ on targets using the separate long double implementation; see BUGS.
Include <complex.h>.
On targets with a separate long double implementation, atan2l() treats both signed-zero components as a domain error, sets errno to EDOM and returns NaN if execution continues. It requests FE_INVALID, but the exception may not be raised by every AROS target. Where cargl() aliases carg(), the double behavior applies.
double cbrt( double x)
Computes the cube root of x.
x - a double value (any real number)
The cube root of x.
double y = cbrt(27.0); // y = 3.0 double z = cbrt(-8.0); // z = -2.0
Defined for all real numbers including negative values. cbrt(-8.0) returns -2.0. Returns NaN if input is NaN.
None known.
float cbrtf( float x)
Computes the cube root of x.
x - a float value (any real number)
The cube root of x.
float y = cbrtf(8.0f); // y = 2.0f float z = cbrtf(-27.0f); // z = -3.0f
Works for negative and positive values. Returns NaN if input is NaN.
None known.
long double cbrtl( long double x)
Computes the cube root of a long double value.
x - input value.
Returns the cube root of x.
long double r = cbrtl(-8.0L); // returns -2.0L
Works with negative values as well.
None known.
double complex ccosh( double complex z)
Return the complex hyperbolic cosine of z.
z - Double complex value x + i*y, with y in radians.
An approximation to cosh(x) * cos(y) + i*sinh(x) * sin(y) in double complex. For finite x and signed-zero y, returns cosh(x) with imaginary zero x*y. For infinite x and signed-zero y, returns positive infinity with a zero whose sign is the product of the signs of x and y. NaN x with signed-zero y returns NaN with the same zero-sign rule. For zero x and infinite or NaN y, returns NaN with an imaginary zero whose sign is the product of the input signs. For finite nonzero x and infinite or NaN y, both components are NaN. For infinite x and finite nonzero y, evaluates infinity*cos(y) + i*x*sin(y). For infinite x and infinite or NaN y, returns positive infinity + i*NaN. For NaN x and nonzero y, both components are NaN.
Include <complex.h>. Each component can overflow or underflow independently. Use round-to-nearest mode for trigonometric argument reduction. Floating-point exceptions can occur; enabled traps may prevent return. Overflow in the real cosh(x) call for zero y sets errno to ERANGE and requests FE_OVERFLOW. Other paths can overflow without setting errno.
Large finite real parts can reach undefined signed-shift arithmetic in exp(). Results on those paths are not portable.
float complex ccoshf( float complex z)
Return the complex hyperbolic cosine of z.
z - Float complex value x + i*y, with y in radians.
An approximation to cosh(x) * cos(y) + i*sinh(x) * sin(y) in float complex. For finite x and signed-zero y, returns cosh(x) with imaginary zero x*y. For infinite x and signed-zero y, returns positive infinity with a zero whose sign is the product of the signs of x and y. NaN x with signed-zero y returns NaN with the same zero-sign rule. For zero x and infinite or NaN y, returns NaN with an imaginary zero whose sign is the product of the input signs. For finite nonzero x and infinite or NaN y, both components are NaN. For infinite x and finite nonzero y, evaluates infinity*cos(y) + i*x*sin(y). For infinite x and infinite or NaN y, returns positive infinity + i*NaN. For NaN x and nonzero y, both components are NaN.
Include <complex.h>. Each component can overflow or underflow independently. Use round-to-nearest mode for trigonometric argument reduction. Floating-point exceptions can occur; enabled traps may prevent return. The function does not assign errno.
Large finite real parts can reach undefined signed-shift arithmetic in expf(). Results on those paths are not portable.
double ceil( double x)
Returns the smallest integer value greater than or equal to x.
x - input floating point number.
The ceiling of x as a double.
double val = ceil(2.3); // val == 3.0
If x is already integral, returns x unchanged. Domain: all real numbers.
None known.
float ceilf( float x)
Returns smallest integer not less than x.
x - input float
Ceiling of x.
float r = ceilf(2.3f); // 3.0f float r2 = ceilf(-2.3f); // -2.0f
Rounds up fractional values.
None known.
long double ceill( long double x)
Returns the smallest integer value greater than or equal to x as long double.
x - input long double number.
The ceiling of x as a long double.
long double val = ceill(2.3L); // val == 3.0L
If x is integral, returns x. Domain: all real numbers.
None known.
double complex cexp( double complex z)
Compute the complex exponential of z.
z - Complex exponent.
Return the complex exponential. For finite z = x + i*y, the real and imaginary components are exp(x)*cos(y) and exp(x)*sin(y). When the imaginary component is zero, the result retains its sign in the imaginary component.
Include <complex.h>. Components can overflow or underflow; infinite or NaN inputs have corresponding exceptional results.
float complex cexpf( float complex z)
Compute the float complex exponential of z.
z - Complex exponent.
Return the complex exponential. For finite z = x + i*y, the real and imaginary components are expf(x)*cosf(y) and expf(x)*sinf(y). When the imaginary component is zero, the result retains its sign in the imaginary component.
Include <complex.h>. Components can overflow or underflow; infinite or NaN inputs have corresponding exceptional results.
double cimag( double complex z)
Return the imaginary component of z.
z - Complex input value.
The imaginary component of z, including its sign. Signed zero, infinity and NaN retain their respective classifications.
Include <complex.h>.
float cimagf( float complex z)
Return the imaginary component of z.
z - Complex input value.
The imaginary component of z, including its sign. Signed zero, infinity and NaN retain their respective classifications.
Include <complex.h>.
long double cimagl( long double complex z)
Return the imaginary component of z.
z - Complex input value.
The imaginary component of z, including its sign. Signed zero, infinity and NaN retain their respective classifications.
Include <complex.h>. When LDBL_MANT_DIG equals DBL_MANT_DIG, cimagl() aliases cimag().
void clearerr( FILE * stream)
Clear EOF and error flag in a stream. You must call this for example after you have read the file until EOF, then appended something to it and want to continue reading.
stream - The stream to be reset.
None.
clock_t clock( void)
clock() returns an approximation of the time passed since the program was started
The time passed in CLOCKS_PER_SEC units. To get the number of seconds divide by CLOCKS_PER_SEC.
Reference point is set when stdc.library is opened. If you use the function from another shared library the reference point is thus when this library opened stdc.library
double complex conj( double complex z)
Return the complex conjugate of z.
z - Complex input value.
A complex value with the real component unchanged and the sign of the imaginary component reversed, including signed zero and infinity. NaN components remain NaNs.
Include <complex.h>.
float complex conjf( float complex z)
Return the complex conjugate of z.
z - Complex input value.
A complex value with the real component unchanged and the sign of the imaginary component reversed, including signed zero and infinity. NaN components remain NaNs.
Include <complex.h>.
long double complex conjl( long double complex z)
Return the complex conjugate of z.
z - Complex input value.
A complex value with the real component unchanged and the sign of the imaginary component reversed, including signed zero and infinity. NaN components remain NaNs.
Include <complex.h>. When LDBL_MANT_DIG is 53, conjl() aliases conj().
long double copysignl( long double x, long double y)
Return the magnitude of x with the sign bit of y.
x - Value supplying the magnitude. y - Value supplying the sign bit.
The magnitude of x with the sign of y, including the sign of zero, infinity or NaN. No numerical comparison with y is made.
Include <math.h>. A NaN input retains its NaN classification; NaN payload behavior depends on the target representation. On equal-precision long double targets, copysignl() aliases copysign().
double cos( double x)
Computes the cosine of x (x in radians).
x - a double value representing an angle in radians.
The cosine of the angle x.
double y = cos(0.0); // y = 1.0 double z = cos(M_PI / 2.0); // z ˜ 0.0
The function is periodic with period 2p. Returns NaN if input is NaN. Uses argument reduction to improve precision for large inputs.
Slight loss of precision for very large inputs.
float cosf( float x)
Computes the cosine of x (x in radians).
x - a float value representing an angle in radians.
The cosine of the angle x.
float y = cosf(0.0f); // y = 1.0f float z = cosf(3.14159f / 2); // z ˜ 0.0f
Periodic with period 2p. Returns NaN if input is NaN. May lose precision for large magnitude inputs.
Precision degradation on large inputs.
double cosh( double x)
Computes the hyperbolic cosine of x.
x - a double value.
The hyperbolic cosine of x, defined as (e^x + e^(-x)) / 2.
double y = cosh(0.0); // y = 1.0 double z = cosh(1.0); // z ˜ 1.5430806348
cosh(x) = 1 for all real x. Returns NaN if input is NaN. May overflow for large |x|, resulting in +Inf.
Overflow for large inputs.
float coshf( float x)
Computes the hyperbolic cosine of x.
x - a float value.
The hyperbolic cosine of x, (e^x + e^(-x)) / 2.
float y = coshf(0.0f); // y = 1.0f float z = coshf(1.0f); // z ˜ 1.543081f
Returns values = 1. Returns NaN if input is NaN. May overflow to +Inf for large |x|.
Overflow for large magnitude inputs.
long double coshl( long double x)
Computes the hyperbolic cosine of x.
x - input angle in radians.
Returns the hyperbolic cosine of x.
long double r = coshl(0.0L); // returns 1.0L
Returns positive values = 1.
None known.
long double cosl( long double x)
Computes the cosine of x (x in radians).
x - angle in radians.
Returns the cosine of x.
double c = cos(0.0); // returns 1.0
Result is in the range [-1, 1].
None known.
double complex cproj( double complex z)
Project z onto the Riemann sphere.
z - Complex input value.
If either component is infinite, positive real infinity with an imaginary zero carrying the sign of the original imaginary component. Otherwise z is returned unchanged, including a NaN component when neither part is infinite.
Include <complex.h>.
float complex cprojf( float complex z)
Project z onto the Riemann sphere.
z - Complex input value.
If either component is infinite, positive real infinity with an imaginary zero carrying the sign of the original imaginary component. Otherwise z is returned unchanged, including a NaN component when neither part is infinite.
Include <complex.h>.
long double complex cprojl( long double complex z)
Project z onto the Riemann sphere.
z - Complex input value.
If either component is infinite, positive real infinity with an imaginary zero carrying the sign of the original imaginary component. Otherwise z is returned unchanged, including a NaN component when neither part is infinite.
Include <complex.h>. When LDBL_MANT_DIG is 53, cprojl() aliases cproj().
double creal( double complex z)
Return the real component of z.
z - Complex input value.
The real component of z, including its sign. Signed zero, infinity and NaN retain their respective classifications.
Include <complex.h>. When LDBL_MANT_DIG is 53, creal() aliases creal().
float crealf( float complex z)
Return the real component of z.
z - Complex input value.
The real component of z, including its sign. Signed zero, infinity and NaN retain their respective classifications.
Include <complex.h>.
long double creall( long double complex z)
Return the real component of z.
z - Complex input value.
The real component of z, including its sign. Signed zero, infinity and NaN retain their respective classifications.
Include <complex.h>. When LDBL_MANT_DIG is 53, creall() aliases creal().
float complex csinf( float complex z)
Return the complex sine of z.
z - Float complex value x + i*y, with x in radians.
An approximation to sin(x) * cosh(y) + i*cos(x) * sinh(y) in float complex. For signed-zero x and infinite or NaN y, retains x as the real component. The imaginary component is infinity with the sign of y, or NaN, respectively. For infinite or NaN x and signed-zero y, returns NaN with that same imaginary zero. For infinite or NaN x and finite nonzero y, both components are NaN. For finite nonzero x and infinite y, evaluates infinity*sin(x) + i*y*cos(x). For infinite or NaN x and infinite y, returns NaN + i*y. For nonzero x and NaN y, both components are NaN.
Include <complex.h>. Each component can overflow or underflow independently. Use round-to-nearest mode for trigonometric argument reduction. Floating-point exceptions can occur; enabled traps may prevent return. The function does not assign errno.
Large finite imaginary parts can reach undefined signed-shift arithmetic in expf(). Results on those paths are not portable.
double complex csinh( double complex z)
Return the complex hyperbolic sine of z.
z - Double complex value x + i*y, with y in radians.
An approximation to sinh(x) * cos(y) + i*cosh(x) * sin(y) in double complex. For signed-zero y, returns sinh(x) with that same imaginary zero; infinite or NaN x is retained in the real component. For zero x and infinite or NaN y, returns x + i*NaN. For finite nonzero x and infinite or NaN y, both components are NaN. For infinite x and finite nonzero y, evaluates x*cos(y) + i*infinity*sin(y). For infinite x and infinite or NaN y, returns x + i*NaN. For NaN x and nonzero y, both components are NaN.
Include <complex.h>. Each component can overflow or underflow independently. Use round-to-nearest mode for trigonometric argument reduction. Floating-point exceptions can occur; enabled traps may prevent return. Do not use errno alone to detect component overflow.
Large finite real parts can reach undefined signed-shift arithmetic in exp(). Results on those paths are not portable.
float complex csinhf( float complex z)
Return the complex hyperbolic sine of z.
z - Float complex value x + i*y, with y in radians.
An approximation to sinh(x) * cos(y) + i*cosh(x) * sin(y) in float complex. For signed-zero y, returns sinh(x) with that same imaginary zero; infinite or NaN x is retained in the real component. For zero x and infinite or NaN y, returns x + i*NaN. For finite nonzero x and infinite or NaN y, both components are NaN. For infinite x and finite nonzero y, evaluates x*cos(y) + i*infinity*sin(y). For infinite x and infinite or NaN y, returns x + i*NaN. For NaN x and nonzero y, both components are NaN.
Include <complex.h>. Each component can overflow or underflow independently. Use round-to-nearest mode for trigonometric argument reduction. Floating-point exceptions can occur; enabled traps may prevent return. The function does not assign errno.
Large finite real parts can reach undefined signed-shift arithmetic in expf(). Results on those paths are not portable.
long double complex csqrtl( long double complex z)
Return the principal square root of a complex number.
z - Complex argument with long double components.
An approximation to the square root of z, with a nonnegative real part. For finite inputs, the imaginary part has the sign of the input imaginary part, subject to the limitations below. At complex zero, the real part is positive zero and the imaginary part retains its sign. On the negative real axis, the sign of the imaginary zero selects the side of the branch cut. An infinite imaginary part returns positive infinity plus the original imaginary infinity, even when the real part is NaN. For a finite imaginary part, positive real infinity returns positive infinity and a signed imaginary zero; negative real infinity returns positive real zero and a signed imaginary infinity. Other NaN inputs return two NaNs, except that a positive infinite real part remains positive infinity, and a negative infinite real part produces an imaginary infinity with the sign of the input imaginary NaN.
Include <complex.h>. Extended-precision targets use sqrtl() and hypotl(). Where long double has the same precision as double, csqrtl() aliases csqrt(). Floating-point exceptions may occur, and enabled traps may prevent return. The extended-precision path relies on the floating-point environment support used by sqrtl(). On m68k, that dependency can clear or change errno.
Very small finite components can underflow internally before the square root is taken. A purely imaginary argument whose magnitude is the smallest positive subnormal can produce an infinite imaginary result in round-to-nearest mode. The m68k and AArch64 floating-point environment stubs do not provide the rounding and exception control required by sqrtl(). Correct rounding and environment preservation are not assured on those paths.
float complex ctanhf( float complex z)
Return the complex hyperbolic tangent of z.
z - Float complex value x + i*y, with y in radians.
An approximation to sinh(z) / cosh(z) in float complex. For infinite x, the real part is 1 with the sign of x and the imaginary part is zero. For finite y, that zero has the sign of sin(y) * cos(y); for infinite y, it has the sign of y. Its sign is unspecified when y is NaN. For NaN x and a signed-zero y, returns NaN with that same imaginary zero. For NaN x and nonzero y, both components are NaN. For finite x and infinite or NaN y, both components are NaN.
Include <complex.h>. The mathematical function has poles at x = 0 and y = (k + 1/2) * pi for integer k. Rounded arguments near these poles can produce large results. Use round-to-nearest mode for argument reduction. Floating-point arithmetic can raise exceptions; enabled traps may prevent return. The function does not assign errno.
Large finite real parts can reach undefined signed-shift arithmetic in expf(). Results on those paths are not portable.
char * ctime( const time_t * tt)
The ctime() function converts the broken-down time value tt into a string. See ctime_r() for details.
tt - Convert this time.
A statically allocated buffer with the converted time. Note that the contents of the buffer might get lost with the call of any of the date and time functions.
time_t tt; char * str; // Get time time (&tt); // Convert to string str = ctime (&tt);
This function must not be used in a shared library or in a threaded application. Use ctime_r() instead.
double difftime( time_t time2, time_t time1)
difftime() returns the number of seconds elapsed between time time2 and time time1.
time2 - time value from which time1 is subtracted time1 - time value that is subtracted from time2
The number of seconds elapsed in double precision.
time_t tt1, tt2; double secs; time (&tt1); ... time (&tt2); secs = difftime(tt2, tt1);
div_t div( int numer, int denom)
Compute quotient en remainder of two int variables
numer = the numerator denom = the denominator
a struct with two ints quot and rem with
quot = numer / denom and rem = numer % denom.
typedef struct div_t {
int quot;
int rem;
} div_t;
NOTES
double erf( double x)
Computes the error function of x.
x - input value.
Returns the probability integral of the Gaussian distribution from 0 to x.
double val = erf(1.0);
Used in probability, statistics, and partial differential equations.
None known.
double erfc( double x)
Computes the complementary error function of x.
x - a double value.
The complementary error function, defined as 1 - erf(x).
double y = erfc(0.0); // y = 1.0 double z = erfc(1.0); // z ˜ 0.157299
erfc(x) approaches 0 as x ? 8 and 2 as x ? -8. Returns NaN if input is NaN. Useful for calculating tail probabilities in statistics.
Accuracy can degrade for very large negative inputs.
float erfcf( float x)
Computes the complementary error function of x.
x - a float value.
The complementary error function of x.
float y = erfcf(0.0f); // y = 1.0f float z = erfcf(1.0f); // z ˜ 0.157299f
Defined as 1 - erf(x). Returns NaN if input is NaN.
Reduced accuracy for large negative inputs.
long double erfcl( long double x)
Computes the complementary error function of x.
x - a long double value.
Returns 1 - erf(x).
long double r = erfcl(0.0L); // returns 1.0L
Useful for calculating tail probabilities.
None known.
float erfclf( float x)
Computes the complementary error function (long double variant).
x - input value.
The complementary error function value.
float val = erfclf(0.0f); // val == 1.0f
Similar to erfcf(), but for long double precision.
None known.
float erff( float x)
Computes the error function erf(x).
x - input float
Value of erf(x).
float r = erff(1.0f); // ˜ 0.8427008f
Common in statistics and PDEs.
None known.
long double erfl( long double x)
Computes the error function of x.
x - a long double value.
Returns erf(x).
long double r = erfl(0.0L); // returns 0.0L
Related to Gaussian integrals.
None known.
void exit( int code)
Terminates the running program. The code is returned to the program which has called the running program.
code - Exit code. 0 for success, other values for failure.
None. This function does not return.
This function must not be used in a shared library or in a threaded application.
double exp( double x)
Computes the exponential function of x, e raised to the power x.
x - a double value.
The value of e^x.
double y = exp(0.0); // y = 1.0 double z = exp(1.0); // z ˜ 2.718281828
Returns +Inf if x is large and positive (overflow). Returns 0 if x is large and negative (underflow). Returns NaN if input is NaN.
Precision may degrade for very large magnitude inputs.
double exp10( double x)
Computes 10 raised to the power of x (10^x).
x - the exponent to raise 10 to.
The value of 10 raised to the power x.
double val = exp10(2.0); // val == 100.0
Internally implemented as exp(x * M_LN10). Domain: all real numbers.
Accuracy depends on the precision of the underlying exp() implementation.
float exp10f( float x)
Computes 10^x using exp(x * ln(10)).
x - exponent.
10^x
float v = exp10f(2.0f); // 100.0
Domain: all real numbers.
None known.
float expf( float x)
Computes the exponential function of x, e raised to the power x.
x - a float value.
The value of e^x.
float y = expf(0.0f); // y = 1.0f float z = expf(1.0f); // z ˜ 2.7182817f
Returns +Inf on overflow, 0 on underflow. Returns NaN if input is NaN.
Precision loss for very large magnitude inputs.
long double expl( long double x)
Computes e raised to the power x.
x - exponent.
Returns e^x. Sets errno to ERANGE and raises FE_OVERFLOW on overflow.
double val = exp(1.0); // returns e (~2.71828)
Uses IEEE 754 semantics.
None known.
double expm1( double x)
Computes e^x - 1 with higher precision than using exp(x) - 1 directly, especially for small values of x.
x - a double value.
The value of e^x - 1.
double y = expm1(0.0); // y = 0.0 double z = expm1(1e-10); // z ˜ 1e-10
Provides better accuracy for small x where exp(x) is close to 1. Returns NaN if input is NaN. Returns -1 if x is large negative (underflow).
None known.
float expm1f( float x)
Computes e^x - 1 with improved precision for small x.
x - a float value.
The value of e^x - 1.
float y = expm1f(0.0f); // y = 0.0f float z = expm1f(1e-7f); // z ˜ 1e-7f
Especially accurate for values of x near zero. Returns NaN if input is NaN.
None known.
double fabs( double x)
Computes the absolute value of a double.
x - a double value.
Absolute value of x.
double a = fabs(-5.0); // 5.0 double b = fabs(3.2); // 3.2
Handles special cases like negative zero and NaN.
None known.
float fabsf( float x)
Returns absolute value of x.
x - value.
Absolute value.
float v = fabsf(-3.14f); // 3.14
Clears sign bit.
None known.
long double fabsl( long double x)
Returns absolute value of x.
x - input long double
Absolute value (non-negative) of x.
long double r = fabsl(-3.5L); // 3.5L
Works for all real numbers.
None known.
int fclose( FILE * stream)
Closes a stream.
stream - Stream to close.
Upon successful completion 0 is returned. Otherwise, EOF is returned and the global variable errno is set to indicate the error. In either case no further access to the stream is possible.
double fdim( double x, double y)
Return the positive difference between x and y.
x - First double operand. y - Second double operand.
Return x - y when x is greater than y; otherwise return +0. If x is NaN, return x; otherwise if y is NaN, return y. The subtraction may overflow to infinity or round to a finite result according to the floating-point environment.
Include <math.h>. This is not an absolute difference. Unlike fmax(x - y, 0), the subtraction is evaluated only when x > y. Subtraction may raise floating-point exceptions, but this implementation does not set errno on overflow. NaN payload and signaling behavior are not guaranteed.
float fdimf( float x, float y)
Return the positive difference between x and y.
x - First float operand. y - Second float operand.
Return x - y when x is greater than y; otherwise return +0. If x is NaN, return x; otherwise if y is NaN, return y. The subtraction may overflow to infinity or round to a finite result according to the floating-point environment.
Include <math.h>. This is not an absolute difference. Unlike fmax(x - y, 0), the subtraction is evaluated only when x > y. Subtraction may raise floating-point exceptions, but this implementation does not set errno on overflow. NaN payload and signaling behavior are not guaranteed.
long double fdiml( long double x, long double y)
Return the positive difference between x and y.
x - First long double operand. y - Second long double operand.
Return x - y when x is greater than y; otherwise return +0. If x is NaN, return x; otherwise if y is NaN, return y. The subtraction may overflow to infinity or round to a finite result according to the floating-point environment.
Include <math.h>. This is not an absolute difference. Unlike fmax(x - y, 0), the subtraction is evaluated only when x > y. Subtraction may raise floating-point exceptions, but this implementation does not set errno on overflow. NaN payload and signaling behavior are not guaranteed.
int feclearexcept( int excepts)
Clear the selected floating-point exception flags.
excepts - Zero, a supported FE_* exception constant, or a
bitwise OR of those constants. Use FE_ALL_EXCEPT
to select every supported exception.
Zero on success; -1 in the generic fallback. See BUGS for implementations that report success without clearing flags.
Include <fenv.h>. Clearing flags does not disable exception traps. On x86, clears selected flags in x87 and, when available, SSE. On PowerPC, selecting FE_INVALID also clears its associated invalid-operation cause flags.
On AArch64, ARM soft-float and RISC-V soft-float, the function returns zero without accessing exception flags. On m68k, only a software environment is accessed; hardware floating-point exceptions are not tracked. The generic fallback is unimplemented and returns -1.
int fegetenv( fenv_t *envp)
Save the current floating-point environment.
envp - Non-NULL pointer to writable storage for a fenv_t.
Zero on completion; -1 in the generic fallback. A supported implementation writes the environment to *envp. See BUGS before relying on the output after a zero return.
Include <fenv.h>. Keep the saved representation unchanged for a later fesetenv() or feupdateenv() call on the same architecture and ABI. It is not a portable file format. On x86, saves x87 state and available SSE control/status state. The x87 control word is restored after the save, so its exception-mask settings are preserved.
On AArch64, ARM soft-float and RISC-V soft-float, returns zero without writing *envp. The object retains its previous contents. On m68k, saves only the software environment, not hardware floating-point state. The generic fallback returns -1 without writing *envp.
int fegetexceptflag( fexcept_t *flagp, int excepts)
Save the selected floating-point exception flags without clearing them.
flagp - Non-NULL pointer to writable storage for a fexcept_t.
excepts - Zero, a supported FE_* exception constant, or their
bitwise OR. FE_ALL_EXCEPT selects all supported flags.
Zero on success; -1 in the generic fallback. The saved representation is written to *flagp. See BUGS for stub behavior.
Include <fenv.h>. Pass the saved value to fesetexceptflag() with a mask containing only flags included in this call. The representation is architecture-dependent. On x86, combines x87 and available SSE flags. The saved value does not preserve which unit reported each flag.
On AArch64, ARM soft-float and RISC-V soft-float, writes zero to *flagp and returns zero without reading exception state. On m68k, only a software environment is accessed; hardware floating-point exceptions are not tracked. The generic fallback returns -1 without accessing *flagp.
int feholdexcept( fenv_t *envp)
Save the floating-point environment, clear exception flags, and disable exception traps where supported.
envp - Non-NULL pointer to writable storage for a fenv_t.
Zero on completion; -1 on RISC-V hardware-float and in the generic fallback. See BUGS before relying on a zero return.
Include <fenv.h>. On x86 and ARM VFP, preserves the rounding mode while clearing exception flags and disabling traps. Use fesetenv() to restore the saved environment, or feupdateenv() to retain exceptions raised in the meantime.
On PowerPC, the saved value does not preserve the environment representation. Do not use it to restore the previous state. On m68k, copies only the software environment to *envp and sets errno to zero. It neither clears exception flags nor disables hardware traps. On AArch64, ARM soft-float and RISC-V soft-float, writes zero to *envp without saving or changing floating-point state. On RISC-V hardware-float and in the generic fallback, returns -1 without writing *envp or changing the environment.
int feof( FILE * stream)
Test the EOF-Flag of a stream. This flag is set automatically by any function which recognises EOF. To clear it, call clearerr().
stream - The stream to be tested.
!= 0, if the stream is at the end of the file, 0 otherwise.
int feraiseexcept( int excepts)
Request the selected floating-point exceptions.
excepts - Zero, a supported FE_* exception constant, or their
bitwise OR. FE_ALL_EXCEPT selects all supported
exceptions.
Zero on completion in the architecture-specific implementations; -1 in the generic fallback. See BUGS: zero does not establish that an exception was raised.
Include <fenv.h>. Enabled floating-point traps may prevent normal completion. Do not rely on a particular delivery order when requesting several exceptions. On x86, sets the selected x87 and available SSE flags, then waits for pending x87 exceptions. Unselected flags are retained.
On AArch64, ARM soft-float and RISC-V soft-float, returns zero without changing exception state. On m68k, does not set exception flags. A selection containing FE_OVERFLOW or FE_UNDERFLOW sets errno to ERANGE; any other nonzero selection sets errno to EDOM. Zero leaves errno unchanged. The function returns zero in each case. ARM VFP and RISC-V hardware-float paths only set exception status flags. The generic fallback is unimplemented and returns -1.
int ferror( FILE * stream)
Test the error flag of a stream. This flag is set automatically by any function that detects an error. To clear it, call clearerr().
stream - The stream to be tested.
!= 0, if the stream had an error, 0 otherwise.
int fesetenv( const fenv_t *envp)
Replace the floating-point environment with a saved or default environment.
envp - Non-NULL pointer to an unchanged environment saved by
fegetenv() or feholdexcept() on the same architecture
and ABI, or FE_DFL_ENV where supported. See BUGS for m68k.
Zero on completion; -1 in the generic fallback. See BUGS for implementations that report success without changing state.
Include <fenv.h>. Replaces the stored control settings and exception flags; it does not merge current exception flags into the saved state. Use feupdateenv() when that is required. On x86, restores x87 state and available SSE control/status state. The x87 tag word is also restored; floating-point register values themselves are not restored.
On m68k, only the software environment is replaced. Do not pass FE_DFL_ENV or FE_NOMASK_ENV: these special pointer values are dereferenced instead of recognized and may cause an invalid memory access. On AArch64, ARM soft-float and RISC-V soft-float, returns zero without reading *envp or changing the environment. The generic fallback is unimplemented and returns -1.
int fesetexceptflag( const fexcept_t *flagp, int excepts)
Restore selected floating-point exception flags from a saved representation.
flagp - Non-NULL pointer to a value saved by fegetexceptflag().
excepts - Zero, a supported FE_* exception constant, or their
bitwise OR. FE_ALL_EXCEPT selects all supported flags.
Select only flags included when the value was saved.
Zero on success; -1 in the generic fallback. See BUGS for implementations that return zero without restoring flags.
Include <fenv.h>. Replaces selected flags with their saved values. Unselected flags are preserved, except as noted below. This function restores flag state rather than performing the exceptional operations used by feraiseexcept(). On x86, installs the selected saved flags in both x87 and available SSE state. It does not restore their original distribution between the two units.
On PowerPC, selecting FE_INVALID also replaces every other flag in FE_ALL_EXCEPT. Flags outside the requested selection can therefore be cleared or changed. On AArch64, ARM soft-float and RISC-V soft-float, returns zero without reading *flagp or changing exception state. On m68k, only a software environment is accessed; hardware floating-point exceptions are not tracked. The generic fallback returns -1 without accessing *flagp.
int fetestexcept( int excepts)
Test the selected floating-point exception flags without clearing them.
excepts - Zero, a supported FE_* exception constant, or a
bitwise OR of those constants. Use FE_ALL_EXCEPT
to select every supported exception.
The bitwise OR of the selected flags that are set, or zero if none are set. The generic fallback returns -1. See BUGS before treating a zero result as evidence of clear flags.
Include <fenv.h>. On x86, reports a flag if it is set in either x87 or, when available, SSE. The result does not identify which unit raised it.
On AArch64, ARM soft-float and RISC-V soft-float, the function returns zero without accessing exception flags. On m68k, only a software environment is accessed; hardware floating-point exceptions are not tracked. The generic fallback is unimplemented and returns -1.
int feupdateenv( const fenv_t *envp)
Restore a floating-point environment and retain the currently raised exception flags.
envp - Non-NULL pointer to an unchanged environment saved by
a working fegetenv() or feholdexcept() implementation
on the same architecture and ABI, or FE_DFL_ENV where
supported. See BUGS for m68k.
Zero if the call returns; -1 in the generic fallback. See BUGS for implementations that do not restore state or retain current flags.
Include <fenv.h>. Restores the saved control settings and combines the saved and current exception flags. Restoring enabled traps can cause an exception before the call returns. On x86, combines current x87 and available SSE exception flags and raises them through feraiseexcept() after restoring the environment. The flags lose their original unit association. See feraiseexcept() for exception-delivery limitations.
On m68k, replaces only the software environment. Current flags are not merged into the restored flags. Instead, current overflow or underflow sets errno to ERANGE; any other nonzero software status sets it to EDOM. A zero status leaves errno unchanged. Do not pass FE_DFL_ENV or FE_NOMASK_ENV: these values are dereferenced and may cause an invalid memory access. On AArch64, ARM soft-float and RISC-V soft-float, returns zero without reading *envp or changing the environment. The generic fallback is unimplemented and returns -1.
int fflush( FILE * stream)
Flush a stream. If the stream is an input stream, then the stream is synchronized for unbuffered I/O. If the stream is an output stream, then any buffered data is written.
stream - Flush this stream. May be NULL. In this case, all
output streams are flushed.
0 on success or EOF on error.
int fgetc( FILE * stream)
Read one character from the stream. If there is no character available or an error occurred, the function returns EOF.
stream - Read from this stream
The character read or EOF on end of file or error. If EOF is returned feof() and ferror() indicate if it was an end-of-file situation or an error.
int fgetpos( FILE * stream, fpos_t * pos)
Get the current position in a stream. This function is equivalent to ftell(). However, on some systems fpos_t may be a complex structure, so this routine may be the only way to portably get the position of a stream.
stream - The stream to get the position from. pos - Pointer to the fpos_t position structure to fill.
0 on success and -1 on error. If an error occurred, the global variable errno is set.
char * fgets( char * buffer, int size, FILE * stream)
Read one line of characters from the stream into the buffer.
Reading will stop, when a newline ('\n') is encountered, EOF
or when the buffer is full. If a newline is read, then it is
put into the buffer. The last character in the buffer is always
'\0' (Therefore at most size-1 characters can be read in one go).
buffer - Write characters into this buffer size - This is the size of the buffer in characters. stream - Read from this stream
buffer or NULL in case of an error or EOF.
// Read a file line by line
char line[256];
// Read until EOF
while (fgets (line, sizeof (line), fh))
{
// Evaluate the line
}
wint_t fgetwc( FILE * stream)
Read the next wide character from the specified stream. Supports UTF-8 decoding if the stream is byte-oriented. Returns a pushed-back wide character if present via ungetwc.
stream - Pointer to the input stream.
Returns the next wide character as a wint_t. Returns WEOF on end-of-file or error.
The function handles UTF-8 sequences up to 4 bytes. If a wide character has been pushed back with ungetwc, it is returned first.
wchar_t *fgetws( wchar_t *ws, int n, FILE *stream)
Reads a wide-character string from the specified stream. Converts UTF-8 input bytes to wide characters and stores up to n-1 wide characters. Null-terminates the string.
ws - Buffer to store the wide string. n - Maximum number of wide characters to read (including null terminator). stream - Input stream to read from.
Returns ws on success, or NULL on error or end of file.
Handles UTF-8 decoding and stream buffering.
double floor( double x)
Returns the largest integer value less than or equal to x.
x - input floating point number.
The floor of x as a double.
double val = floor(2.7); // val == 2.0
If x is integral, returns x. Domain: all real numbers.
None known.
float floorf( float x)
Returns largest integer <= x.
x - value.
Floor of x.
float v = floorf(-2.3f); // -3.0
Handles negatives and special values.
None known.
long double floorl( long double x)
Returns the largest integer value less than or equal to x as a long double.
x - input long double number.
The floor of x as a long double.
long double val = floorl(2.7L); // val == 2.0L
If x is integral, returns x. Domain: all real numbers.
None known.
double fma( double x, double y, double z)
Compute x * y + z with one final rounding to double precision.
x, y - Multiplicands. z - Addend.
The fused result in the current rounding direction, subject to the implementation limits below. This can differ from evaluating x * y and then adding z as two separately rounded operations.
Include <math.h>. Zero times infinity and an infinite product added to an oppositely signed infinity produce NaN through invalid arithmetic. NaN operands propagate without a payload guarantee. Finite results can underflow or overflow; floating-point exceptions may be raised. The software path temporarily selects round-to-nearest and restores the incoming rounding mode before normal return. Exception flags are not restored to their previous values, and enabled traps may interrupt the operation. This entry point does not explicitly report errors through errno.
The software algorithm requires double-precision intermediate rounding. On x87, it does not establish that precision itself; extended-precision evaluation can invalidate its error-free transformations. The m68k FPU library-vector replacement uses single-precision operand and result moves with separate multiply and add instructions. It does not implement this double-precision fused contract.
float fmaf( float x, float y, float z)
Multiply x by y and add z without rounding the product to float first.
x - First factor. y - Second factor. z - Value to add to the product.
The value of x*y + z as a float, subject to the rounding limitations below. A zero multiplied by infinity, or an infinite product added to an infinity of the opposite sign, produces NaN. NaN operands produce NaN.
Include <math.h>. The calculation uses the current rounding mode. A correction in round-to-nearest mode temporarily selects round-toward-zero, then requests round-to-nearest again before returning. The function does not assign errno. Floating-point exceptions can occur; enabled traps may prevent return.
Correct rounding requires working floating-point environment support and compiler support for dynamic rounding. Failed rounding-mode changes are not reported. On m68k and AArch64, fegetround() returns -1, so the correction for double rounding is skipped. Some results can differ from a single correctly rounded operation.
long double fmal( long double x, long double y, long double z)
Compute x * y + z with one final rounding to long double precision.
x, y - Multiplicands. z - Addend.
The fused long double result in the current rounding direction, subject to the implementation limits below. Special-value behavior and floating-point side effects follow the fma() contract.
Include <math.h>. On targets where long double and double have equal precision, this function aliases the double implementation. Otherwise the software algorithm uses the target long double format; it requires intermediate arithmetic at that format's precision. The routine temporarily uses round-to-nearest and restores the incoming rounding mode before normal return. It does not establish the x87 precision-control setting for long double evaluation.
The extended-precision implementation calls double-precision ldexp() in its round-to-nearest subnormal-result path. The conversion and scaling can discard long double precision and turn a representable nonzero result into zero. Do not rely on correct fused rounding in this range. Equal-precision aliases inherit the fma() limitations.
double fmax( double x, double y)
Return the larger numeric operand, ignoring a lone NaN.
x - First double operand. y - Second double operand.
The larger value for numeric operands. For opposite-signed zeros, return +0. If one operand is NaN, return the other. If both are NaNs, return a NaN.
Include <math.h>. For two NaNs, this implementation evaluates x + y, which may raise FE_INVALID. The sign of zero and NaN handling differ from a simple conditional comparison. NaN payloads are not guaranteed.
float fmaxf( float x, float y)
Return the larger numeric operand, ignoring a lone NaN.
x - First float operand. y - Second float operand.
The larger value for numeric operands. For opposite-signed zeros, return +0. If one operand is NaN, return the other. If both are NaNs, return a NaN.
Include <math.h>. For two NaNs, the second argument is returned. The sign of zero and NaN handling differ from a simple conditional comparison. Signaling NaNs may affect the floating-point exception state; NaN payloads are not guaranteed.
long double fmaxl( long double x, long double y)
Return the larger numeric operand, ignoring a lone NaN.
x - First long double operand. y - Second long double operand.
The larger value for numeric operands. For opposite-signed zeros, return +0. If one operand is NaN, return the other. If both are NaNs, return a NaN.
Include <math.h>. For two NaNs, this implementation evaluates x + y, which may raise FE_INVALID. The sign of zero and NaN handling differ from a simple conditional comparison. NaN payloads are not guaranteed. Where long double has double precision, the double implementation supplies the long double symbol.
double fmin( double x, double y)
Return the smaller numeric operand, ignoring a lone NaN.
x - First double operand. y - Second double operand.
The smaller value for numeric operands. For opposite-signed zeros, return -0. If one operand is NaN, return the other. If both are NaNs, return a NaN.
Include <math.h>. For two NaNs, the second argument is returned. The sign of zero and NaN handling differ from a simple conditional comparison. Signaling NaNs may affect the floating-point exception state; NaN payloads are not guaranteed.
float fminf( float x, float y)
Return the smaller numeric operand, ignoring a lone NaN.
x - First float operand. y - Second float operand.
The smaller value for numeric operands. For opposite-signed zeros, return -0. If one operand is NaN, return the other. If both are NaNs, return a NaN.
Include <math.h>. For two NaNs, the second argument is returned. The sign of zero and NaN handling differ from a simple conditional comparison. Signaling NaNs may affect the floating-point exception state; NaN payloads are not guaranteed.
long double fminl( long double x, long double y)
Return the smaller numeric operand, ignoring a lone NaN.
x - First long double operand. y - Second long double operand.
The smaller value for numeric operands. For opposite-signed zeros, return -0. If one operand is NaN, return the other. If both are NaNs, return a NaN.
Include <math.h>. For two NaNs, the second argument is returned. The sign of zero and NaN handling differ from a simple conditional comparison. Signaling NaNs may affect the floating-point exception state; NaN payloads are not guaranteed. Where long double has double precision, the double implementation supplies the long double symbol.
double fmod( double x, double y)
Computes the floating-point remainder of x / y.
x - numerator. y - denominator (non-zero).
The remainder r = x - n*y, where n = trunc(x/y).
double r = fmod(5.3, 2.0); // r = 1.3 double s = fmod(-5.3, 2.0); // s = -1.3
Behavior undefined if y == 0. Result has same sign as x.
None known.
float fmodf( float x, float y)
Computes remainder of x / y.
x - numerator. y - denominator.
Floating-point remainder.
float v = fmodf(5.3f, 2.0f); // 1.3
Result sign matches x. y=0 returns NaN.
None known.
long double fmodl( long double x, long double y)
Computes floating-point remainder for long double precision.
x - numerator. y - denominator (non-zero).
Floating-point remainder.
long double r = fmodl(5.3L, 2.0L); // r = 1.3L
Same rules as fmod().
None known.
FILE * fopen( const char * restrict pathname, const char * restrict mode)
Opens a file with the specified name in the specified mode.
pathname - Path and filename of the file you want to open.
mode - How to open the file:
r: Open for reading. The stream is positioned at the
beginning of the file.
r+: Open for reading and writing. The stream is positioned
at the beginning of the file.
w: Open for writing. If the file doesn't exist, then
it is created. If it does already exist, then
it is truncated. The stream is positioned at the
beginning of the file.
w+: Open for reading and writing. If the file doesn't
exist, then it is created. If it does already
exist, then it is truncated. The stream is
positioned at the beginning of the file.
a: Open for writing. If the file doesn't exist, then
it is created. The stream is positioned at the
end of the file.
a+: Open for reading and writing. If the file doesn't
exist, then it is created. The stream is positioned
at the end of the file.
b: Open in binary more. This has no effect and is ignored.
A pointer to a FILE handle or NULL in case of an error. When NULL is returned, then errno is set to indicate the error.
Currently errno is not set on error.
int fprintf( FILE * restrict fh, const char * restrict format, ...)
Format a string with the specified arguments and write it to the stream.
fh - Write to this stream format - How to format the arguments ... - The additional arguments
The number of characters written to the stream or EOF on error.
int fputc( int c, FILE * stream)
Write one character to the specified stream.
c - The character to output stream - The character is written to this stream
The character written or EOF on error.
int fputs( const char * str, FILE * stream)
Write a string to the specified stream.
str - Output this string... fh - ...to this stream
> 0 on success and EOF on error.
wint_t fputwc( wint_t wc, FILE * stream)
Write a wide character to the specified stream. Converts the wide character to UTF-8 and writes the byte sequence.
wc - Wide character to write. stream - Pointer to the output stream.
Returns the wide character written, or WEOF on error.
Handles conversion from wchar_t (Unicode code point) to UTF-8.
wint_t fputws( const wchar_t *ws, FILE *stream)
Write a wide-character string to the specified stream. Converts each wide character to UTF-8 and writes the sequence of bytes.
ws - Pointer to the null-terminated wide-character string to write. stream - Pointer to the output stream.
Returns a non-negative number on success, or WEOF on error.
The null terminator is not written. Uses fputwc internally for each wide character.
size_t fread( void * restrict buf, size_t size, size_t nblocks, FILE * restrict stream)
Read an amount of bytes from a stream.
buf - The buffer to read the bytes into size - Size of one block to read nblocks - The number of blocks to read stream - Read from this stream
The number of blocks read. This may range from 0 when the stream contains no more blocks up to nblocks. In case of an error, 0 is returned.
void free( void * memory)
Return memory allocated with malloc() or a similar function to the system.
memory - The result of the previous call to malloc(), etc. or
NULL.
None.
FILE *freopen( const char * restrict path, const char * restrict mode, FILE * restrict stream )
Opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it.
path - the file to open, NULL to only change the mode of the stream.
mode - Mode to open file, see fopen for description of the string.
When path is NULL end-of-file and error indicator will be
cleared and indication if stream is read and/or write.
No change to position in file or no truncation will be
performed.
stream - the stream to which the file will be associated.
NULL on error or stream. When NULL is returned input stream is not changed.
double frexp( double x, int *exp)
Breaks the floating-point number x into its normalized fraction and an integral power of two. The fraction is returned, and the power of two is stored in *exp.
x - input floating point number. exp - pointer to integer where exponent will be stored.
The normalized fraction part of x in the range [0.5, 1.0) or zero.
int e; double frac = frexp(8.0, &e); // frac=0.5, e=4 (8.0 = 0.5 * 2^4)
Handles zero, infinity, NaN properly. Domain: all real numbers.
None known.
float frexpf( float x, int *eptr)
Decompose x into a normalized binary fraction and exponent. For finite nonzero x, return m and store e such that x = m * 2^e and 0.5 <= |m| < 1.
x - Value to decompose. eptr - Writable pointer receiving the integer exponent.
The signed fraction m. For zero, return the signed zero and store 0 in *eptr. For infinity or NaN, return x and store 0.
Include <math.h>. eptr must not be NULL. For example, an input of 12 yields a fraction of 0.75 and an exponent of 4.
long double frexpl( long double x, int *ex)
Decompose x into a normalized binary fraction and exponent. For finite nonzero x, return m and store e such that x = m * 2^e and 0.5 <= |m| < 1.
x - Value to decompose. ex - Writable pointer receiving the integer exponent.
The signed fraction m. For zero, return the signed zero and store 0 in *ex. For infinity or NaN, return x; the separate long double implementation leaves *ex unchanged.
Include <math.h>. ex must not be NULL. On targets where frexpl() aliases frexp(), nonfinite inputs instead store 0. Do not use the exponent output for a nonfinite input.
int fscanf( FILE * restrict fh, const char * restrict format, ...)
Scan a string with the specified arguments and write the results in the specified parameters.
fh - Read from this stream format - How to convert the input into the arguments ... - Write the result in these arguments
The number of converted arguments.
int fseek( FILE * stream, long offset, int whence)
Change the current position in a stream.
stream - Modify this stream
offset, whence - How to modify the current position. whence
can be SEEK_SET, then offset is the absolute position
in the file (0 is the first byte), SEEK_CUR then the
position will change by offset (ie. -5 means to move
5 bytes to the beginning of the file) or SEEK_END.
SEEK_END means that the offset is relative to the
end of the file (-1 is the last byte and 0 is
the EOF).
0 on success and -1 on error. If an error occurred, the global variable errno is set.
The seek is handled by the files system so effects of what happens when seeking after end of file may differ between file systems.
Not fully compatible with ISO fseek, especially in 'ab' and 'a+b' modes
int fsetpos( FILE * stream, const fpos_t * pos)
Change the current position in a stream. This function is equivalent to fseek() with whence set to SEEK_SET. However, on some systems fpos_t may be a complex structure, so this routine may be the only way to portably reposition a stream.
stream - Modify this stream pos - The new position in the stream.
0 on success and -1 on error. If an error occurred, the global variable errno is set.
long int ftell( FILE * stream)
Tell the current position in a stream.
stream - Obtain position of this stream
The position on success and -1 on error. If an error occurred, the global variable errno is set.
int fwide( FILE *stream, int mode)
Sets or queries the orientation of the given stream for wide or byte I/O. If mode > 0, sets stream orientation to wide-character. If mode < 0, sets stream orientation to byte-oriented. If mode == 0, returns current orientation without changing it.
stream - The stream to query or set orientation. mode - Orientation mode to set or 0 to query.
Returns positive value if stream is wide-oriented, negative if byte-oriented, or 0 if no orientation is set.
Orientation is locked after first I/O operation.
int fwprintf( struct __sFILE * restrict stream, const wchar_t * restrict format, ...)
Format a variable list of arguments according to a wide-character format string and write the output to the given stream.
stream - Output stream. format - A wide-character printf() format string. ... - Additional arguments matching the format specifiers.
The number of wide characters written to the stream, or a negative value if an error occurs.
This function uses wide-character output and formatting, similar to printf(), but targeting wchar_t output streams.
size_t fwrite( const void * restrict buf, size_t size, size_t nblocks, FILE * restrict stream)
Write an amount of bytes to a stream.
buf - The buffer to write to the stream size - Size of one block to write nblocks - The number of blocks to write stream - Write to this stream
The number of blocks written. If no error occurred, this is nblocks. Otherwise examine errno for the reason of the error.
int fwscanf( FILE * restrict stream, const wchar_t * restrict format, ...)
Reads formatted wide-character input from the given file stream and stores the results into the provided argument locations.
stream - Read from this wide-character file stream format - How to convert the input into the arguments ... - Write the result in these arguments
The number of converted arguments.
double gamma( double x)
Computes the gamma function G(x), which extends the factorial function to real and complex numbers.
x - input value.
The value of the gamma function at x.
double val = gamma(5.0); // val == 24.0 (factorial 4!)
Domain excludes non-positive integers (poles). Returns infinity or NaN on poles. Uses Lanczos approximation or similar.
Precision varies for large arguments. Overflow on large positive values.
double gamma_r( double x, int *signgamp)
Return the natural logarithm of the absolute value of Gamma(x), and store its sign separately.
x - Double argument.
signgamp - Non-NULL pointer to writable int storage. The
function writes this object for every argument,
including poles and nonfinite values.
An approximation to log(|Gamma(x)|) in double. For finite nonpole arguments, *signgamp is +1 or -1 according to the sign of Gamma(x), subject to BUGS. Returns zero for x equal to 1 or 2. Both signs of zero and negative integers are poles and return positive infinity. Either infinity returns positive infinity; NaN returns NaN. At negative zero, *signgamp is -1. At positive zero, negative integer poles, either infinity and NaN, it is +1. These special-case values do not indicate a valid finite Gamma value or successful evaluation.
Include <math.h>. This is the historical name for lgamma_r(). It has the same result and sign output. Use tgamma() when you need Gamma(x) itself. The result can be negative even when *signgamp is positive. The signgam variable is not used as implicit output. Passing &signgam explicitly still writes that object. Use separate output storage for independent concurrent calls. The function does not assign errno. Pole arithmetic can raise divide-by-zero; other arithmetic can raise overflow or inexact. Enabled traps may prevent return.
Large negative noninteger arguments can produce an incorrect Gamma sign. For example, x equal to -1125899906842625.5 can report -1 although Gamma(x) is positive.
float gammaf_r( float x, int *signgamp)
Return the natural logarithm of the absolute value of Gamma(x), and store its sign separately.
x - Float argument.
signgamp - Non-NULL pointer to writable int storage. The
function writes this object for every argument,
including poles and nonfinite values.
An approximation to log(|Gamma(x)|) in float. For finite nonpole arguments, *signgamp is +1 or -1 according to the sign of Gamma(x), subject to BUGS. Returns zero for x equal to 1 or 2. Both signs of zero and negative integers are poles and return positive infinity. Either infinity returns positive infinity; NaN returns NaN. At negative zero, *signgamp is -1. At positive zero, negative integer poles, either infinity and NaN, it is +1. These special-case values do not indicate a valid finite Gamma value or successful evaluation.
Include <math.h>. This is the historical name for lgammaf_r(). It has the same result and sign output. Use tgammaf() when you need Gamma(x) itself. The result can be negative even when *signgamp is positive. The signgam variable is not used as implicit output. Passing &signgam explicitly still writes that object. Use separate output storage for independent concurrent calls. The function does not assign errno. Pole arithmetic can raise divide-by-zero; other arithmetic can raise overflow or inexact. Enabled traps may prevent return.
Large negative noninteger arguments can produce an incorrect Gamma sign. For example, x equal to -2097153.5f can report -1 although Gamma(x) is positive.
int getc( FILE * stream)
Read one character from the stream. If there is no character available or an error occurred, the function returns EOF.
stream - Read from this stream
The character read or EOF on end of file or error.
int getchar(
Read one character from the standard input stream. If there is no character available or an error occurred, the function returns EOF.
The character read or EOF on end of file or error.
char *getenv( const char *name)
Get an environment variable.
name - Name of the environment variable.
Pointer to the variable's value, or NULL on failure. When no memory is available errno will be set to ENOMEM.
The returned contents of the environment variable is cached per StdCIOBase. So the returned value is valid and does not change until a next call to getenv on the same StdCIOBase.
char * gets( char * buffer)
Read one line of characters from the standard input stream into
the buffer. Reading will stop, when a newline ('\n') is encountered,
EOF or when the buffer is full. If a newline is read, then it is
replaced by '\0'. The last character in the buffer is always '\0'.
buffer - Write characters into this buffer
buffer when successful. NULL in case of an error or when EOF without any characters read. In the latter case buffer array is unchanged.
Never use this function. gets() does not know how large the buffer is and will continue to store characters past the end of the buffer if it has not encountered a newline or EOF yet. Use fgets() instead.
wint_t getwc( FILE *stream)
Read a wide character by calling fgetwc(). Return a pending character from ungetwc() first, without reading bytes. Otherwise decode one one-to-four-byte UTF-8 sequence from the stream.
stream - Open input stream. The stream remains owned by the caller.
The decoded or pushed-back value, or WEOF on end-of-file or error. NULL stream returns WEOF and sets errno to EINVAL. An invalid lead byte, invalid continuation byte or incomplete sequence sets EILSEQ. A stream not open for reading normally returns WEOF with EACCES and its error indicator set; a pending wide pushback is returned first.
Include <wchar.h>. This is a function wrapper and evaluates its argument once. It does not close the stream or allocate a returned object. Decoding is fixed to UTF-8 and does not use the current locale's encoding. Bytes consumed before a decoding error are not restored, including an invalid continuation byte. A byte I/O error encountered after a multibyte lead byte is reported as EILSEQ by the decoder. feof() and ferror() reflect the underlying byte read. A decoding error does not itself set the stream error indicator; inspect errno when WEOF is returned. Successful reads do not clear earlier indicators or errno. Returning a pushed-back character does not clear an EOF flag left by this implementation of ungetwc(). Use a valid stream in DOS process context with the C runtime active. Reading can block in the underlying file handler. No timeout or cancellation mechanism is supplied. Coordinate access to the stream; this wrapper adds no locking around a complete multibyte sequence.
The decoder checks byte prefixes but does not reject overlong forms, surrogate code points or values above U+10FFFF. Do not use this call as a strict UTF-8 validator. Neither this wrapper nor fgetwc() sets or checks stream orientation; the byte-read path does not enforce it.
t_t getwchar( void) FUNCTION The getwchar() function is the wide-character equivalent of getchar(). It reads the next wide character from stdin and returns it as a wint_t value. If the end-of-file is reached or an error occurs, WEOF is returned.
None.
Returns the next wide character read from stdin as a wint_t. Returns WEOF if end-of-file is encountered or an error occurs.
wint_t wc;
while ((wc = getwchar()) != WEOF)
putwchar(wc);
The behavior of getwchar() depends on the current locale, particularly the LC_CTYPE category, which affects the interpretation of multibyte sequences as wide characters. Internally, getwchar() is equivalent to calling fgetwc(stdin).
If stdin is not a valid input stream or the locale is misconfigured, results may be undefined or incorrect.
struct tm * gmtime( const time_t * tt)
The gmtime() function converts the calendar time tt to broken-down time representation, expressed in Coordinated Universal Time (UTC). See gmtime_r() for details.
tt - The time to convert
A statically allocated buffer with the broken down time in Coordinated Universal Time (UTC). Note that the contents of the buffer might get lost with the call of any of the date and time functions.
time_t tt; struct tm * tm; // Get the time time (&tt); // and convert it tm = gmtime (&tt);
Resulting tm struct is buffered per stdc.library and shared with localtime().
double hypot( double x, double y)
Computes sqrt(x*x + y*y) without intermediate overflow or underflow.
x, y - double values.
Hypotenuse sqrt(x² + y²).
double h = hypot(3.0, 4.0); // h = 5.0
More accurate than direct sqrt(x*x + y*y).
None known.
float hypotf( float x, float y)
Returns sqrt(x² + y²) without overflow/underflow.
x, y - values.
Euclidean distance.
float v = hypotf(3.0f, 4.0f); // 5.0
Safer than naive sqrt(x*x + y*y).
None known.
long double hypotl( long double x, long double y)
Computes sqrt(x² + y²) without undue overflow or underflow.
x - first value. y - second value.
Returns the Euclidean norm.
long double r = hypotl(3.0L, 4.0L); // returns 5.0L
Accurate even if x or y is large/small.
None known.
int ilogbf( float x)
Return the binary exponent of |x| as an integer.
x - Float value to classify.
The integer exponent e such that 2^e <= |x| < 2^(e+1) for finite nonzero x. Zero returns FP_ILOGB0; NaN returns FP_ILOGBNAN; infinity returns INT_MAX. In AROS, FP_ILOGBNAN equals INT_MAX, so these results are ambiguous.
Include <math.h>. Use isnan() or isinf() on the input to distinguish NaN from infinity. Unlike logbf(), the result is an integer sentinel for exceptional inputs.
The subnormal scan shifts a signed 32-bit integer into its sign bit, an operation with undefined behavior in C. Subnormal results may depend on the compiler.
int ilogbl( long double x)
Return the binary exponent of |x| as an integer.
x - Long double value to classify.
The integer exponent e such that 2^e <= |x| < 2^(e+1) for finite nonzero x. Zero returns FP_ILOGB0; NaN returns FP_ILOGBNAN; infinity returns INT_MAX. In AROS, FP_ILOGBNAN equals INT_MAX, so these results are ambiguous.
Include <math.h>. Use isnan() or isinf() on the input to distinguish NaN from infinity. Unlike logbl(), the result is an integer sentinel for exceptional inputs. Where long double equals double, ilogbl() aliases ilogb().
The separate long double subnormal scan assumes unsigned long can hold the significand field. On 32-bit-long targets using binary128, shifts by 63 or 47 bits are undefined. The equal-precision double alias has its own signed-shift defect for subnormal inputs.
intmax_t imaxabs( intmax_t j)
Compute the absolute value of an integer "j".
Return the absolute value.
imaxdiv_t imaxdiv( intmax_t num, intmax_t denom)
Computes the value num/denom and returns the quotient and remainder in a structure named imaxdiv_t.
Return quotient and remainder from division.
int ioerr2errno( int ioerr)
Convert a DOS error number to a stdc error number.
ioerr - Zero or a positive DOS error number no greater than
INT_MAX - MAX_ERRNO.
Zero for input zero. The following DOS errors map to errno constants: ERROR_OBJECT_WRONG_TYPE EINVAL ERROR_INVALID_COMPONENT_NAME EINVAL ERROR_NO_FREE_STORE ENOMEM ERROR_DEVICE_NOT_MOUNTED ENOENT ERROR_OBJECT_NOT_FOUND ENOENT ERROR_OBJECT_EXISTS EEXIST ERROR_BUFFER_OVERFLOW ENOBUFS ERROR_BREAK EINTR ERROR_FILE_NOT_OBJECT ENOEXEC ERROR_NOT_EXECUTABLE ENOEXEC ERROR_OBJECT_IN_USE EBUSY ERROR_DIR_NOT_FOUND ENOTDIR ERROR_RENAME_ACROSS_DEVICES EXDEV Other values return MAX_ERRNO + ioerr.
Include <errno.h>. The function neither reads IoErr() nor changes errno or the DOS error state. Assign the result to errno when required. These mappings describe stdc.library. The selected C link library may override ioerr2errno(); __stdc_ioerr2errno() selects the stdc.library implementation. The stdc strerror() implementation recognizes positive DOS errors encoded with the MAX_ERRNO offset.
int isalnum( int c)
Test if a character is an alphabetic character or a digit. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is alphabetic character or a digit, 0 otherwise.
isalnum ('A') -> true
isalnum ('a') -> true
isalnum ('0') -> true
isalnum ('.') -> false
isalnum ('\n') -> false
isalnum ('\001') -> false
isalnum (EOF) -> false
int isalpha( int c)
Test if a character is an alphabetic character. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is an alphabetic character, 0 otherwise.
isalpha ('A') -> true
isalpha ('a') -> true
isalpha ('0') -> false
isalpha ('.') -> false
isalpha ('\n') -> false
isalpha ('\001') -> false
isalpha (EOF) -> false
int isascii( int c)
Test if a character is an ascii character. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is an ascii character, 0 otherwise.
isascii ('A') -> true
isascii ('a') -> true
isascii ('0') -> true
isascii ('.') -> true
isascii ('\n') -> true
isascii ('\001') -> true
isascii (EOF) -> false
int isblank( int c)
Test if a character is a space or a tab. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is a space or tab, 0 otherwise.
isblank ('A') -> false
isblank ('a') -> false
isblank ('0') -> false
isblank ('.') -> false
isblank (' ') -> true
isblank ('\n') -> false
isblank ('\001') -> false
isblank (EOF) -> false
int iscntrl( int c)
Test if a character is a control character. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is a control character, 0 otherwise.
iscntrl ('A') -> false
iscntrl ('a') -> false
iscntrl ('0') -> false
iscntrl ('.') -> false
iscntrl ('\n') -> true
iscntrl ('\001') -> true
iscntrl (EOF) -> false
int isdigit( int c)
Test if a character is a digit. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is a digit, 0 otherwise.
isdigit ('A') -> false
isdigit ('a') -> false
isdigit ('0') -> true
isdigit ('.') -> false
isdigit ('\n') -> false
isdigit ('\001') -> false
isdigit (EOF) -> false
int isgraph( int c)
Test if a character is a printable character but no whitespace. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is a printable character but no whitespace, 0 otherwise.
isgraph ('A') -> true
isgraph ('a') -> true
isgraph ('0') -> true
isgraph ('.') -> true
isgraph ('\n') -> false
isgraph ('\001') -> false
isgraph (EOF) -> false
int islower( int c)
Test if a character is lowercase. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is lowercase, 0 otherwise.
islower ('A') -> false
islower ('a') -> true
islower ('0') -> false
islower ('.') -> false
islower ('\n') -> false
islower ('\001') -> false
islower (EOF) -> false
int isprint( int c)
Test if a character is a printable character. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is a printable character, 0 otherwise.
isprint ('A') -> true
isprint ('a') -> true
isprint ('0') -> true
isprint ('.') -> true
isprint ('\n') -> true
isprint ('\001') -> false
isprint (EOF) -> false
int ispunct( int c)
Test if a character is printable but not alphanumeric. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is printable but not alphanumeric, 0 otherwise.
ispunct ('A') -> false
ispunct ('a') -> false
ispunct ('0') -> false
ispunct ('.') -> true
ispunct ('\n') -> false
ispunct ('\001') -> false
ispunct (EOF) -> false
int isspace( int c)
Test if a character is whitespace. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is whitespace, 0 otherwise.
isspace ('A') -> false
isspace ('a') -> false
isspace ('0') -> false
isspace ('.') -> false
isspace ('\n') -> true
isspace ('\001') -> false
isspace (EOF) -> false
int isupper( int c)
Test if a character is uppercase. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is uppercase, 0 otherwise.
isupper ('A') -> true
isupper ('a') -> false
isupper ('0') -> false
isupper ('.') -> false
isupper ('\n') -> false
isupper ('\001') -> false
isupper (EOF) -> false
int iswctype( wint_t wc, wctype_t desc)
Tests whether a wide character `wc` has the property indicated by `desc`, which must be a value returned by `wctype()`.
wc - the wide character code point to test. desc - classification descriptor returned by `wctype()`.
Non-zero if the character has the property; zero otherwise.
if (iswctype(L'9', wctype("digit"))) {
// Character is a digit
}
The `desc` value must be obtained from a prior call to `wctype()`. Behavior is undefined if `desc` is invalid or comes from a different implementation.
Only standard ASCII and Latin-1 Supplement classifications are supported. No locale-specific behavior or Unicode categories beyond U+00FF are recognized.
int isxdigit( int c)
Test if a character is a hexadecimal digit. Works for all characters between -128 and 255 inclusive both.
c - The character to test.
!= 0 if the character is a hexadecimal digit, 0 otherwise.
isxdigit ('A') -> true
isxdigit ('a') -> true
isxdigit ('x') -> false
isxdigit ('0') -> true
isxdigit ('.') -> false
isxdigit ('\n') -> false
isxdigit ('\001') -> false
isxdigit (EOF) -> false
double j0( double x)
Computes the Bessel function of the first kind of order zero, J0(x).
x - input value.
The value of J0(x).
double val = j0(0.0); // val == 1.0
Oscillatory function, used in many physics and engineering problems. Domain: all real numbers.
May lose precision for very large x.
float j0f( float x)
Evaluate the Bessel function of the first kind, J_0(x), of order zero.
x - Real argument. Negative arguments are accepted.
An approximation to J_0(x) as a float. Both signs of zero return 1. Both infinities return positive zero. NaN returns NaN.
Include <math.h>. This is a BSD extension. The function does not assign errno. Floating-point exceptions may occur; enabled traps may prevent return. Use round-to-nearest. The trigonometric argument reduction used for large arguments assumes this rounding mode. J_0 is even: J_0(-x) = J_0(x).
double j1( double x)
Computes the Bessel function of the first kind of order one, J1(x).
x - input value.
The value of J1(x).
double val = j1(0.0); // val == 0.0
Oscillatory function, important in wave propagation. Domain: all real numbers.
May lose precision for very large x.
float j1f( float x)
Evaluate the Bessel function of the first kind, J_1(x), of order one.
x - Real argument. Negative arguments are accepted.
An approximation to J_1(x) as a float. Zero arguments retain their sign. Infinite arguments return zero with the sign of x. NaN returns NaN.
Include <math.h>. This is a BSD extension. The function does not assign errno. Floating-point exceptions may occur; enabled traps may prevent return. Use round-to-nearest. The trigonometric argument reduction used for large arguments assumes this rounding mode. J_1 is odd: J_1(-x) = -J_1(x).
double jn( int n, double x)
Computes the Bessel function of the first kind of order `n` at `x`.
n - order of the Bessel function (integer). x - the point at which to evaluate.
Returns the value of the Bessel function \( J_n(x) \). If `x` is infinite or NaN, forwards to __ieee754_jn.
double r = jn(0, 1.0); // J0(1.0)
Commonly appears in solutions to wave and diffusion equations with cylindrical symmetry.
None known.
float jnf( int n, float x)
Evaluate the Bessel function of the first kind, J_n(x), for integer order n.
n - Integer order; see BUGS for unsupported extreme orders. x - Real argument. Negative arguments are accepted.
An approximation to J_n(x) as a float. NaN returns NaN. For n = 0, either sign of zero returns 1 and either infinity returns positive zero. For other supported orders, zero and infinite arguments return zero, with the sign determined by the parity of n and the signs of n and x.
Include <math.h>. This is a BSD extension. The function does not assign errno. Floating-point exceptions may occur; enabled traps may prevent return. Use round-to-nearest. The trigonometric argument reduction used for large arguments assumes this rounding mode. Evaluation time can grow with the magnitude of n. For positive integer m, J_-m(x) = (-1)^m J_m(x) and J_m(-x) = (-1)^m J_m(x).
INT_MIN is not supported: negating this order overflows signed int for non-NaN arguments. Large orders can also overflow integer recurrence calculations; for example, n = 1073741824 and x = 1 are unsafe with 32-bit int. For |x| < 2^-29 and |n| > 33, the function returns zero without raising underflow for the discarded result.
long labs( long j)
Compute the absolute value of j.
j - A signed long
The absolute value of j.
// returns 1 labs (1L); // returns 1 labs (-1L);
double ldexp( double x, int exp)
Computes x * 2^exp.
x - base double exp - exponent integer
x scaled by 2 to the exp.
double r = ldexp(1.5, 3); // 12.0
Used for binary exponent scaling.
None known.
float ldexpf( float x, int n)
Multiply x by 2 raised to n.
x - Value to scale. n - Base-two exponent.
The scaled float value. Inexact results are rounded according to the current floating-point rounding direction. Signed zero and infinity retain their signs; NaN produces NaN.
Include <math.h>. ldexpf() is a symbol alias of scalbnf(), with identical numerical and exception behavior. This implementation does not set errno. Overflow and underflow may raise floating-point exceptions.
The shared implementation adds n to a signed exponent without checking for overflow. For x = 1 and n = INT_MAX, this causes undefined signed integer arithmetic before the range check.
long double ldexpl( long double x, int n)
Multiply x by 2 raised to n.
x - Value to scale. n - Base-two exponent.
The scaled long double value, subject to the limitations described in BUGS. Inexact results depend on the current floating-point rounding direction. Signed zero and infinity retain their signs; NaN produces NaN.
Include <math.h>. ldexpl() aliases scalbnl() where long double has a separate implementation, or scalbn() where double and long double have equal precision. Neither path sets errno. Overflow and underflow may raise floating-point exceptions.
The scaling implementations add n to a signed exponent without checking for overflow. For x = 1 and n = INT_MAX, this causes undefined signed integer arithmetic before the range check. The separate long double implementation narrows its underflow constant through double-precision copysign(). Under downward rounding, a negative input can yield negative zero where a negative subnormal is required. The equal-precision alias does not use this implementation.
ldiv_t ldiv( long int numer, long int denom)
Compute quotient en remainder of two long variables
numer = the numerator denom = the denominator
a struct with two long ints quot and rem with
quot = numer / denom and rem = numer % denom.
typedef struct ldiv_t {
long int quot;
long int rem;
} ldiv_t;
double lgamma( double x)
Computes the natural logarithm of the absolute value of the gamma function.
x - input value.
Returns ln(|G(x)|). Domain errors set errno to EDOM.
double val = lgamma(5.0);
Useful for large arguments to avoid overflow.
None known.
double lgamma_r( double x, int *signgamp)
Return the natural logarithm of the absolute value of Gamma(x), and store its sign separately.
x - Double argument.
signgamp - Non-NULL pointer to writable int storage. The
function writes this object for every argument,
including poles and nonfinite values.
An approximation to log(|Gamma(x)|) in double. For finite nonpole arguments, *signgamp is +1 or -1 according to the sign of Gamma(x), subject to BUGS. Returns zero for x equal to 1 or 2. Both signs of zero and negative integers are poles and return positive infinity. Either infinity returns positive infinity; NaN returns NaN. At negative zero, *signgamp is -1. At positive zero, negative integer poles, either infinity and NaN, it is +1. These special-case values do not indicate a valid finite Gamma value or successful evaluation.
Include <math.h>. Use tgamma() when you need Gamma(x) itself. The result can be negative even when *signgamp is positive. The signgam variable is not used as implicit output. Passing &signgam explicitly still writes that object. Use separate output storage for independent concurrent calls. The function does not assign errno. Pole arithmetic can raise divide-by-zero; other arithmetic can raise overflow or inexact. Enabled traps may prevent return.
Large negative noninteger arguments can produce an incorrect Gamma sign. For example, x equal to -1125899906842625.5 can report -1 although Gamma(x) is positive.
float lgammaf( float x)
Return the natural logarithm of the absolute value of Gamma(x), and store its sign in signgam.
x - Float argument.
An approximation to log(|Gamma(x)|) in float. For finite nonpole arguments, signgam is +1 or -1 according to the sign of Gamma(x), subject to BUGS. Returns zero for x equal to 1 or 2. Both signs of zero and negative integers are poles and return positive infinity. Either infinity returns positive infinity; NaN returns NaN. At negative zero, signgam is -1. At positive zero, negative integer poles, either infinity and NaN, it is +1. These values do not indicate successful evaluation.
Include <math.h> to access signgam. On AROS it is a macro; do not replace the header with an extern int declaration. Read or copy signgam before another call that overwrites it. Use lgammaf_r() with your own output storage when the sign must remain independent of other calls. Use tgammaf() for Gamma(x) itself. The return value here can be negative even when signgam is positive. The function does not assign errno. Pole arithmetic can raise divide-by-zero; other arithmetic can raise overflow or inexact. Enabled traps may prevent return.
Large negative noninteger arguments can produce an incorrect Gamma sign. For example, x equal to -2097153.5f can report -1 although Gamma(x) is positive.
float lgammaf_r( float x, int *signgamp)
Return the natural logarithm of the absolute value of Gamma(x), and store its sign separately.
x - Float argument.
signgamp - Non-NULL pointer to writable int storage. The
function writes this object for every argument,
including poles and nonfinite values.
An approximation to log(|Gamma(x)|) in float. For finite nonpole arguments, *signgamp is +1 or -1 according to the sign of Gamma(x), subject to BUGS. Returns zero for x equal to 1 or 2. Both signs of zero and negative integers are poles and return positive infinity. Either infinity returns positive infinity; NaN returns NaN. At negative zero, *signgamp is -1. At positive zero, negative integer poles, either infinity and NaN, it is +1. These special-case values do not indicate a valid finite Gamma value or successful evaluation.
Include <math.h>. Use tgammaf() when you need Gamma(x) itself. The result can be negative even when *signgamp is positive. The signgam variable is not used as implicit output. Passing &signgam explicitly still writes that object. Use separate output storage for independent concurrent calls. The function does not assign errno. Pole arithmetic can raise divide-by-zero; other arithmetic can raise overflow or inexact. Enabled traps may prevent return.
Large negative noninteger arguments can produce an incorrect Gamma sign. For example, x equal to -2097153.5f can report -1 although Gamma(x) is positive.
long double lgammal( long double x)
Computes the natural logarithm of the absolute value of the gamma function.
x - input value.
Returns ln|G(x)|.
long double r = lgammal(5.0L); // ˜ ln(24)
Useful for large factorials: lgammal(n+1) ˜ ln(n!)
None known.
long double lgammal_r( long double x, int *signgamp)
Compute the natural logarithm of the absolute gamma function and its sign.
x - Argument to the gamma function.
signgamp - Non-NULL pointer to writable int storage. Receives the sign
of Gamma(x), normally +1 or -1 for finite non-pole arguments.
An approximation to log(|Gamma(x)|), not Gamma(x). Returns zero for x equal to 1 or 2, positive infinity at either signed zero or a negative integer, positive infinity for either infinite input, and NaN for NaN. Large positive finite inputs can overflow. At -0, *signgamp is -1; at +0, negative integer poles, infinities and NaN, it is +1. These values at poles and non-finite inputs do not establish a valid finite Gamma value.
Include <math.h>. The sign of the logarithm is independent of the reported Gamma sign. Use tgammal() when Gamma(x) itself is required. The function writes through signgamp on every returning path and does not use signgam as implicit output. Use separate output storage for independent concurrent calls; passing &signgam still writes that object. No explicit errno assignment is made here. Pole evaluation uses division by zero; overflow and inexact exceptions can arise during arithmetic. Enabled traps may prevent return. Precision follows the target long double format; equal-precision targets alias lgamma_r().
Argument reduction for large negative nonintegers can select the wrong reflection interval, producing an incorrect Gamma sign and logarithm. This affects the extended-precision variants as well as the double alias; avoid relying on these results for large negative arguments.
long long llabs( long long j)
Compute the absolute value of j.
j - A signed long long
The absolute value of j.
// returns 1 labs (1L); // returns 1 labs (-1L);
lldiv_t lldiv( long long int numer, long long int denom)
Compute quotient en remainder of two long long variables
numer = the numerator denom = the denominator
a struct with two long ints quot and rem with
quot = numer / denom and rem = numer % denom.
typedef struct lldiv_t {
long long int quot;
long long int rem;
} lldiv_t;
long long llrint( double x)
Round x in the current floating-point rounding mode and convert the result to long long. Nearest rounding selects the even integer at a tie.
x - Finite double value whose rounded result fits in long long.
The integer result. Both signed zeros become zero. No error value is reserved for an invalid conversion.
Include <math.h>. Use <fenv.h> to control the rounding mode. With functioning environment support, the wrapper restores the caller's environment and clears new FE_INEXACT if FE_INVALID was raised. Preexisting exception flags are preserved.
Conversion of NaN, infinity or an out-of-range rounded value is undefined; the wrapper does not validate the integer cast. Floating-point environment failures are ignored, and some AROS targets provide incomplete or stub implementations. On RISC-V hard-float, a failed save can lead to restoration of uninitialized environment state. The rint() delegate has undefined C behavior for some small negative inputs.
long long llrintf( float x)
Round x in the current floating-point rounding mode and convert the result to long long. Nearest rounding selects the even integer at a tie.
x - Finite float value whose rounded result fits in long long.
The integer result. Both signed zeros become zero. No error value is reserved for an invalid conversion.
Include <math.h>. Use <fenv.h> to control the rounding mode. With functioning environment support, the wrapper restores the caller's environment and clears new FE_INEXACT if FE_INVALID was raised. Preexisting exception flags are preserved.
Conversion of NaN, infinity or an out-of-range rounded value is undefined; the wrapper does not validate the integer cast. Floating-point environment failures are ignored, and some AROS targets provide incomplete or stub implementations. On RISC-V hard-float, a failed save can lead to restoration of uninitialized environment state. The rintf() delegate has undefined C behavior for some small negative inputs.
long long llrintl( long double x)
Round x in the current floating-point rounding mode and convert the result to long long. Nearest rounding selects the even integer at a tie.
x - Finite long double value whose rounded result fits in long long.
The integer result. Both signed zeros become zero. No error value is reserved for an invalid conversion.
Include <math.h>. Use <fenv.h> to control the rounding mode. With functioning environment support, the wrapper restores the caller's environment and clears new FE_INEXACT if FE_INVALID was raised. Preexisting exception flags are preserved. Where long double has the same precision as double, this symbol is an alias of the double-input variant.
Conversion of NaN, infinity or an out-of-range rounded value is undefined; the wrapper does not validate the integer cast. Floating-point environment failures are ignored, and some AROS targets provide incomplete or stub implementations. On RISC-V hard-float, a failed save can lead to restoration of uninitialized environment state. The separate rintl() delegate depends on long double evaluation precision; reduced x87 precision can produce an incorrect result. The double alias inherits the double rint() limitation.
long long llround( double x)
Round x to the nearest integer, with halfway cases away from zero, and return the result as long long. The current rounding direction does not affect the result.
x - Finite double value whose rounded result fits in long long.
The rounded integer. Both signs of zero return 0. No defined result is guaranteed for nonfinite inputs or an out-of-range conversion.
Include <math.h>. The implementation calls round() before conversion to long long. It does not assign errno. Rounding can affect floating-point exception flags.
The range check can accept NaNs, infinities and out-of-range values, allowing undefined floating-to-integer conversions. The explicit rejection path raises FE_INVALID and returns LLONG_MAX if execution continues, but not all invalid inputs reach it. LLONG_MAX is also a valid result, not a unique error sentinel.
long long llroundf( float x)
Round x to the nearest integer, with halfway cases away from zero, and return the result as long long. The current rounding direction does not affect the result.
x - Finite float value whose rounded result fits in long long.
The rounded integer. Both signs of zero return 0. No defined result is guaranteed for nonfinite inputs or an out-of-range conversion.
Include <math.h>. The implementation calls roundf() before conversion to long long. It does not assign errno. Rounding can affect floating-point exception flags.
The range check can accept NaNs, infinities and out-of-range values, allowing undefined floating-to-integer conversions. The explicit rejection path raises FE_INVALID and returns LLONG_MAX if execution continues, but not all invalid inputs reach it. LLONG_MAX is also a valid result, not a unique error sentinel.
long long llroundl( long double x)
Round x to the nearest integer, with halfway cases away from zero, and return the result as long long. The current rounding direction does not affect the result.
x - Finite long double value whose rounded result fits in long long.
The rounded integer. Both signs of zero return 0. No defined result is guaranteed for nonfinite inputs or an out-of-range conversion.
Include <math.h>. The implementation calls roundl() before conversion to long long. It does not assign errno. Rounding can affect floating-point exception flags. On targets where long double and double have equal precision, this symbol aliases the corresponding double implementation.
The range check can accept NaNs, infinities and out-of-range values, allowing undefined floating-to-integer conversions. The explicit rejection path raises FE_INVALID and returns LLONG_MAX if execution continues, but not all invalid inputs reach it. LLONG_MAX is also a valid result, not a unique error sentinel.
struct lconv *localeconv( void)
The localeconv function sets the components of an object with type struct lconv with values appropriate for the formatting of numeric quantities (monetary and otherwise) according to the rules of the current locale.
-
The lconv struct
stdc.library only support "C" locale so always the same data is returned.
struct tm * localtime( const time_t * tt)
Splits the system time in seconds into a structure. See localtime_r() for details.
tt - A time in seconds from the 1. Jan 1970
A statically allocated buffer with the broken up time. Note that the contents of the buffer might get lost with the call of any of the date and time functions.
time_t tt; struct tm * tm; // Get time time (&tt); // Break time up tm = localtime (&tt);
Resulting tm struct is buffered per stdc.library and shared with gmtime().
double log( double x)
Computes the natural logarithm (base e) of x.
x - input value (must be positive).
Returns ln(x). Returns NaN and sets errno to EDOM if x = 0.
double val = log(2.718281828); // approximately 1.0
Uses IEEE 754 semantics for special values.
None known.
double log10( double x)
Computes the base-10 logarithm of x.
x - input value (must be positive).
Returns log10(x). Returns NaN and sets errno to EDOM if x = 0.
double val = log10(100.0); // returns 2.0
Uses IEEE 754 semantics.
None known.
float log10f( float x)
Return the base-10 logarithm of x.
x - Positive float value, including positive subnormal values.
An approximation to the base-10 logarithm in float. Returns positive zero for x = 1. Both signs of zero return negative infinity. Negative values, including negative infinity, return NaN. Positive infinity returns positive infinity; NaN returns NaN.
Include <math.h>. The function does not assign errno. Zero arguments can raise divide-by-zero; negative arguments can raise invalid. Other arithmetic can raise inexact. Enabled traps may prevent return.
long double log10l( long double x)
Computes the base-10 logarithm of x.
x - a positive number.
Returns log10(x), or -8 if x == 0.
long double r = log10l(1000.0L); // returns 3.0L
Domain error if x <= 0.
None known.
double log1p( double x)
Computes the natural logarithm of (1 + x), i.e. ln(1 + x), with high accuracy even for values of x near zero.
x - input value.
Returns ln(1 + x). If x == -1.0, returns -INFINITY and sets errno to ERANGE. If x < -1.0, returns NaN and sets errno to EDOM.
double val = log1p(1e-9); // accurate result close to 1e-9 double val2 = log1p(-1.0); // returns -INFINITY, sets errno = ERANGE
This function is more accurate than using log(1 + x) directly for small x, due to reduced cancellation error. The result is well-defined for all x > -1. If x < -1, the result is undefined (logarithm of a negative number).
None known.
float log1pf( float x)
Return the natural logarithm of 1 + x without losing small x to rounding in the addition.
x - Float value greater than -1 for a finite result.
An approximation to log(1 + x) in float. Signed zero retains its sign. At x = -1, returns negative infinity. For x < -1, including negative infinity, returns NaN. Positive infinity returns positive infinity; NaN returns NaN.
Include <math.h>. Prefer log1pf(x) to logf(1.0f + x) when x is close to zero. The latter can lose x before the logarithm is evaluated. The function does not assign errno. The pole at -1 can raise divide-by-zero; arguments below -1 can raise invalid. Other arithmetic can raise inexact. Enabled traps may prevent return.
long double log1pl( long double x)
Computes log(1 + x) accurately for small x.
x - a number greater than -1.
Returns log(1 + x).
long double r = log1pl(1.0e-10L);
Accurate even if x is near zero.
None known.
double log2( double x)
Computes the base-2 logarithm of x.
x - input value (must be positive).
Returns log2(x). Returns NaN and sets errno to EDOM if x = 0.
double val = log2(8.0); // returns 3.0
Uses IEEE 754 semantics.
None known.
float log2f( float x)
Return the base-2 logarithm of x.
x - Positive float value, including positive subnormal values.
An approximation to the base-2 logarithm in float. Returns positive zero for x = 1. Both signs of zero return negative infinity. Negative values, including negative infinity, return NaN. Positive infinity returns positive infinity; NaN returns NaN.
Include <math.h>. The function does not assign errno. Zero arguments can raise divide-by-zero; negative arguments can raise invalid. Other arithmetic can raise inexact. Enabled traps may prevent return.
long double log2l( long double x)
Computes the base-2 logarithm of x.
x - a positive number.
Returns log2(x), or -8 if x == 0.
long double r = log2l(8.0L); // returns 3.0L
Domain error if x <= 0.
None known.
float logbf( float x)
Return the base-two exponent of the magnitude of x as a floating-point value.
x - Float value to examine.
For finite nonzero x, e such that 2^e <= |x| < 2^(e+1). Zero returns negative infinity, infinity returns positive infinity, and NaN returns NaN.
Include <math.h>. The zero path divides by zero and can raise FE_DIVBYZERO. A floating-point trap may prevent return. Unlike ilogbf(), special inputs produce floating-point values rather than integer sentinels.
long double logbl( long double x)
Return the base-two exponent of the magnitude of x as a floating-point value.
x - Long double value to examine.
For finite nonzero x, e such that 2^e <= |x| < 2^(e+1). Zero returns negative infinity, infinity returns positive infinity, and NaN returns NaN.
Include <math.h>. The zero path divides by zero and can raise FE_DIVBYZERO. A floating-point trap may prevent return. Unlike ilogbl(), special inputs produce floating-point values rather than integer sentinels. Where long double equals double, logbl() aliases logb().
The separate long double subnormal scan requires an unsigned long wide enough for the significand field. Binary128 on a 32-bit-long target can shift by 63 or 47 bits, which is undefined behavior in C.
float logf( float x)
Return the natural logarithm of x.
x - Positive float value, including positive subnormal values.
An approximation to the natural logarithm in float. Returns positive zero for x = 1. Both signs of zero return negative infinity. Negative values, including negative infinity, return NaN. Positive infinity returns positive infinity; NaN returns NaN.
Include <math.h>. The function does not assign errno. Zero arguments can raise divide-by-zero; negative arguments can raise invalid. Other arithmetic can raise inexact. Enabled traps may prevent return.
long double logl( long double x)
Computes the natural logarithm (base e) of x.
x - input value (must be positive).
Returns ln(x). Returns NaN and sets errno to EDOM if x = 0.
double val = log(2.718281828); // approximately 1.0
Uses IEEE 754 semantics for special values.
None known.
void longjmp( jmp_buf env, int val)
Resume execution at the environment most recently saved in env.
env - Intact jmp_buf initialized by setjmp() in the current thread.
Its saving function and the relevant variable-length scopes must
still be active.
val - Value returned by the resumed setjmp(). Zero is converted to 1.
Does not return to its caller.
Restores the saved stack pointer, return address and CPU-specific register state. It does not run cleanup code in skipped functions, release locks, close files or free heap allocations. Arrange cleanup before jumping or in the resumed path. Use only an environment saved by setjmp(), with the same target ABI. Invalid, expired or cross-thread environments are not diagnosed before restoring the stack and transferring control. See setjmp() for the rules governing local variables and permitted save expressions. No signal mask is restored. Do not rely on this operation to restore floating-point control or exception state.
setjmp() posixc/siglongjmp()
long lrint( double x)
Round x in the current floating-point rounding mode and convert the result to long. Nearest rounding selects the even integer at a tie.
x - Finite double value whose rounded result fits in long.
The integer result. Both signed zeros become zero. No error value is reserved for an invalid conversion.
Include <math.h>. Use <fenv.h> to control the rounding mode. With functioning environment support, the wrapper restores the caller's environment and clears new FE_INEXACT if FE_INVALID was raised. Preexisting exception flags are preserved.
Conversion of NaN, infinity or an out-of-range rounded value is undefined; the wrapper does not validate the integer cast. Floating-point environment failures are ignored, and some AROS targets provide incomplete or stub implementations. On RISC-V hard-float, a failed save can lead to restoration of uninitialized environment state. The rint() delegate has undefined C behavior for some small negative inputs.
long lrintf( float x)
Round x in the current floating-point rounding mode and convert the result to long. Nearest rounding selects the even integer at a tie.
x - Finite float value whose rounded result fits in long.
The integer result. Both signed zeros become zero. No error value is reserved for an invalid conversion.
Include <math.h>. Use <fenv.h> to control the rounding mode. With functioning environment support, the wrapper restores the caller's environment and clears new FE_INEXACT if FE_INVALID was raised. Preexisting exception flags are preserved.
Conversion of NaN, infinity or an out-of-range rounded value is undefined; the wrapper does not validate the integer cast. Floating-point environment failures are ignored, and some AROS targets provide incomplete or stub implementations. On RISC-V hard-float, a failed save can lead to restoration of uninitialized environment state. The rintf() delegate has undefined C behavior for some small negative inputs.
long lrintl( long double x)
Round x in the current floating-point rounding mode and convert the result to long. Nearest rounding selects the even integer at a tie.
x - Finite long double value whose rounded result fits in long.
The integer result. Both signed zeros become zero. No error value is reserved for an invalid conversion.
Include <math.h>. Use <fenv.h> to control the rounding mode. With functioning environment support, the wrapper restores the caller's environment and clears new FE_INEXACT if FE_INVALID was raised. Preexisting exception flags are preserved. Where long double has the same precision as double, this symbol is an alias of the double-input variant.
Conversion of NaN, infinity or an out-of-range rounded value is undefined; the wrapper does not validate the integer cast. Floating-point environment failures are ignored, and some AROS targets provide incomplete or stub implementations. On RISC-V hard-float, a failed save can lead to restoration of uninitialized environment state. The separate rintl() delegate depends on long double evaluation precision; reduced x87 precision can produce an incorrect result. The double alias inherits the double rint() limitation.
long lround( double x)
Round x to the nearest integer, with halfway cases away from zero, and return the result as long. The current rounding direction does not affect the result.
x - Finite double value whose rounded result fits in long.
The rounded integer. Both signs of zero return 0. No defined result is guaranteed for nonfinite inputs or an out-of-range conversion.
Include <math.h>. The implementation calls round() before conversion to long. It does not assign errno. Rounding can affect floating-point exception flags.
The range check can accept NaNs, infinities and out-of-range values, allowing undefined floating-to-integer conversions. The explicit rejection path raises FE_INVALID and returns LONG_MAX if execution continues, but not all invalid inputs reach it. LONG_MAX is also a valid result, not a unique error sentinel.
long lroundf( float x)
Round x to the nearest integer, with halfway cases away from zero, and return the result as long. The current rounding direction does not affect the result.
x - Finite float value whose rounded result fits in long.
The rounded integer. Both signs of zero return 0. No defined result is guaranteed for nonfinite inputs or an out-of-range conversion.
Include <math.h>. The implementation calls roundf() before conversion to long. It does not assign errno. Rounding can affect floating-point exception flags.
The range check can accept NaNs, infinities and out-of-range values, allowing undefined floating-to-integer conversions. The explicit rejection path raises FE_INVALID and returns LONG_MAX if execution continues, but not all invalid inputs reach it. LONG_MAX is also a valid result, not a unique error sentinel.
long lroundl( long double x)
Round x to the nearest integer, with halfway cases away from zero, and return the result as long. The current rounding direction does not affect the result.
x - Finite long double value whose rounded result fits in long.
The rounded integer. Both signs of zero return 0. No defined result is guaranteed for nonfinite inputs or an out-of-range conversion.
Include <math.h>. The implementation calls roundl() before conversion to long. It does not assign errno. Rounding can affect floating-point exception flags. On targets where long double and double have equal precision, this symbol aliases the corresponding double implementation.
The range check can accept NaNs, infinities and out-of-range values, allowing undefined floating-to-integer conversions. The explicit rejection path raises FE_INVALID and returns LONG_MAX if execution continues, but not all invalid inputs reach it. LONG_MAX is also a valid result, not a unique error sentinel.
void *malloc( size_t size)
Allocate size bytes of memory and return the address of the first byte.
size - How much memory to allocate.
A pointer to the allocated memory or NULL. If you don't need the memory anymore, you can pass this pointer to free(). If you don't, the memory will be freed for you when the application exits.
int mblen( const char *s, size_t n)
Determines the number of bytes comprising the next multibyte character in the input string 's', examining at most 'n' bytes. This function is typically used to scan or measure multibyte strings when the actual wide character value is not needed.
s - Pointer to the multibyte character string to examine.
If NULL, the function is used to test whether the current encoding
has state-dependent encodings.
n - Maximum number of bytes to examine in 's'.
Returns the number of bytes that make up the next multibyte character if the sequence is valid. Returns 0 if the character is the null byte (`'\0'`). Returns -1 if the sequence is invalid or incomplete, and sets errno to EILSEQ. If 's' is NULL, returns 0 in UTF-8 or "C" locale, indicating a stateless encoding.
const char *mb = "Ã?";
int len = mblen(mb, MB_CUR_MAX);
if (len > 0) {
// len indicates how many bytes 'Ã?' takes in the current encoding
}
stdc.library currently only implements "C" or UTF-8-compatible encodings. Therefore, this function always returns 0 when 's' is NULL and does not track shift states. The function relies on UTF-8 byte patterns to determine the multibyte length.
Does not support locale-specific or stateful encodings. No shift state is maintained between calls, even in encodings where this might be necessary.
size_t mbrlen( const char * restrict s, size_t n, mbstate_t * restrict ps)
Determines the number of bytes needed to represent the next multibyte character in the input string 's'.
s - Pointer to the input multibyte string. n - Maximum number of bytes to examine from 's'. ps - Conversion state object (unused in this stateless implementation).
Returns the number of bytes that comprise the next multibyte character. Returns 0 if the character is the null character. Returns (size_t)-1 on encoding error and sets errno to EILSEQ. Returns (size_t)-2 if more bytes are needed to complete a valid character.
const char *mbs = "Ã?"; size_t len = mbrlen(mbs, strlen(mbs), NULL);
Only UTF-8 multibyte sequences are supported. Implemented in terms of mbrtowc(NULL, s, n, ps) as required by C99 7.24.6.2, so the two functions always agree on what constitutes a valid sequence (including overlong/surrogate/out-of-range rejection).
size_t mbrtoc16( char16_t * restrict pc16, const char * restrict s, size_t n, mbstate_t * restrict ps)
Converts a single multibyte character to a 16-bit (UTF-16) character. Code points outside the Basic Multilingual Plane are returned as a UTF-16 surrogate pair over two successive calls.
pc16 - Where to store the converted code unit (may be NULL). s - Multibyte sequence to convert, or NULL. n - Maximum number of bytes from 's' to examine. ps - Conversion state (a static internal state is used if NULL).
The number of bytes consumed, 0 for a null character, (size_t)-1 on an encoding error (errno = EILSEQ), (size_t)-2 for an incomplete sequence, or (size_t)-3 when the stored code unit is the low surrogate produced from a preceding call (no further input is consumed).
Only UTF-8 multibyte sequences are supported.
size_t mbrtoc32( char32_t * restrict pc32, const char * restrict s, size_t n, mbstate_t * restrict ps)
Converts a single multibyte character to a 32-bit (UTF-32) character.
pc32 - Where to store the converted character (may be NULL). s - Multibyte sequence to convert, or NULL. n - Maximum number of bytes from 's' to examine. ps - Conversion state (a static internal state is used if NULL).
As mbrtowc(): the number of bytes consumed, 0 for a null character, (size_t)-1 on an encoding error (errno = EILSEQ) or (size_t)-2 for an incomplete sequence.
char32_t holds a complete Unicode code point, so on AROS - where wchar_t is 32 bits wide - this is equivalent to mbrtowc().
size_t mbrtowc( wchar_t * restrict pwc, const char * restrict s, size_t n, mbstate_t * restrict ps)
Converts the multibyte character at 's' to a wide character stored in *pwc.
pwc - Pointer to output wide character (can be NULL). s - Pointer to the input multibyte character. n - Maximum number of bytes to examine from 's'. ps - Conversion state object (unused in this stateless implementation).
Returns the number of bytes consumed to produce the wide character. Returns 0 if the null character was converted and stored. Returns (size_t)-1 on encoding error and sets errno to EILSEQ. Returns (size_t)-2 if 's' is NULL or points to an incomplete character.
const char *mbs = "Ã?"; wchar_t wc; size_t len = mbrtowc(&wc, mbs, strlen(mbs), NULL);
Only UTF-8 multibyte sequences are supported. Locale-specific or stateful encodings are not implemented.
size_t mbsrtowcs( wchar_t * restrict dst, const char ** restrict src, size_t len, mbstate_t * restrict ps)
Converts a null-terminated multibyte character string pointed to by *src into a corresponding wide character string. The conversion uses the current locale (UTF-8 assumed here) and updates the src pointer to point past the last converted multibyte character.
dst - Pointer to destination wide character buffer (may be NULL).
src - Address of the multibyte string pointer. The pointer is updated
during conversion. If dst is NULL, the function returns the
number of wide characters that would result from the conversion.
len - Maximum number of wide characters to write.
ps - Conversion state object (ignored in this implementation).
Returns the number of wide characters written or needed. Returns (size_t)-1 on conversion error and sets errno to EILSEQ.
This implementation assumes stateless UTF-8 encoding and does not currently use mbstate_t. It wraps around mbrtowc().
size_t mbstowcs( wchar_t * restrict dest, const char * restrict src, size_t n)
Converts a null-terminated multibyte character string (char*) into its corresponding wide character string (wchar_t*), using the current locale's encoding. At most 'n' wide characters are written into 'dest'. Conversion stops on the first invalid multibyte sequence, or when a null byte is encountered.
dest - Pointer to the output wide character buffer. If NULL, the function
returns the number of wide characters that would result from the conversion,
excluding the terminating null wide character.
src - Pointer to the null-terminated multibyte string to convert.
n - Maximum number of wide characters to write into 'dest'.
Returns the number of wide characters converted (excluding the terminating L'\0'). Returns (size_t)-1 if an invalid multibyte sequence is encountered during conversion, and sets errno to EILSEQ. If 'dest' is NULL, the function returns the number of wide characters that would be generated from the conversion, not counting the final null wide character.
const char *utf8 = "Hello ??!";
wchar_t wbuf[64];
size_t count = mbstowcs(wbuf, utf8, 64);
if (count != (size_t)-1) {
// wbuf now contains wide character equivalents
}
stdc.library currently only implements "C" or UTF-8-compatible locales. The encoding is stateless, and no locale-dependent shift state is used. Conversion uses mbtowc() for each multibyte sequence encountered in 'src'.
Does not support locale-specific encodings or stateful encodings like ISO 2022 or Shift-JIS. Buffer overflow may occur if 'n' is smaller than the number of resulting wide characters.
int mbtowc( wchar_t * restrict pwc, const char * restrict s, size_t n)
Converts the multibyte sequence starting at 's' into a wide character and stores it at the location pointed to by 'pwc'. The function examines up to 'n' bytes to determine the length of the multibyte character. If 's' is NULL, the function is used to reset the conversion state.
pwc - Pointer to the location where the resulting wide character will be stored.
If NULL, the function still parses the multibyte sequence to determine length,
but does not store the result.
s - Pointer to the multibyte character sequence to convert.
If NULL, the function returns 0 (for stateless encodings like UTF-8).
n - Maximum number of bytes to examine from 's'.
Returns the number of bytes that were consumed to produce a valid wide character. Returns 0 if the character is the null byte (`'\0'`). Returns -1 if an invalid or incomplete multibyte sequence is encountered, and sets errno to EILSEQ.
const char *mb = "??";
wchar_t wc;
int len = mbtowc(&wc, mb, MB_CUR_MAX);
if (len > 0) {
// wc now holds the wide character value for '??'
}
stdc.library currently only implements "C" or UTF-8-compatible locales. The encoding is treated as stateless, so no shift state is used or stored. This function is not thread-safe with stateful encodings unless all calls use the same static state, which is not applicable here.
Does not support stateful or locale-dependent encodings. Returns -1 on partial or invalid sequences without giving detailed error context.
void * memccpy( void * restrict dest, const void * restrict src, int c, size_t n)
Copy bytes from src to dest, stopping after the first occurrence of the byte c (converted to unsigned char) has been copied, or after n bytes have been copied, whichever comes first.
dest - destination buffer. src - source buffer. c - stop copying once this byte (as unsigned char) is copied. n - maximum number of bytes to copy.
A pointer to the byte in dest immediately following the copy of c, or NULL if c was not found in the first n bytes of src.
void * memchr( const void * mem, int c, size_t n)
Locate the first occurrence of c which is converted to an unsigned char in the first n bytes of the memory pointed to by mem.
mem - pointer to memory that is searched for c c - the character to search for n - how many bytes to search through starting at mem
pointer to the located byte or null if c was not found
int memcmp( const void * s1, const void * s2, size_t n)
Calculate s1 - s2 for the n bytes after s1 and s2 and stop when the difference is not 0.
s1, s2 - Begin of the memory areas to compare n - The number of bytes to compare
The difference of the memory areas. The difference is 0, if both are equal, < 0 if s1 < s2 and > 0 if s1 > s2. Note that it may be greater then 1 or less than -1.
This function is not part of a library and may thus be called any time.
void *memcpy( void * restrict dst0, const void * restrict src0, size_t length)
Copy a block of memory; handling of overlapping regions is not guaranteed.
dst0: destination for copy src0: source for copy length: number of bytes to copy
dst0
stdc.library/memcpy() is an alias to stdc.library/memmove() So overlapping regions are handled OK if this function is used.
void *memmove( void *dst0, const void *src0, size_t length)
Copy a block of memory, handling overlap.
dst0: destination for copy src0: source for copy length: number of bytes to copy
dst0
void * memset( void * dest, int c, size_t count)
Fill the memory at dest with count times c.
dest - The first byte of the destination area in memory c - The byte to fill memory with count - How many bytes to write
dest.
time_t mktime( struct tm * utim)
The mktime() function converts the broken-down time utim to calendar time representation.
utim - The broken-down time to convert
The converted calendar time
time_t tt; struct tm * tm; //Computation which results in a tm tm = ... // and convert it tt = mktime (tm);
At the moment sanity check is not performed nor a normalization on the structure is done
double modf( double x, double *iptr)
Splits the input number into fractional and integer parts.
x - the input value to split. iptr - pointer to store the integer part of x.
Returns the fractional part of x and stores the integer part at *iptr. If `iptr` is NULL, returns NaN and sets errno to EDOM.
double i; double f = modf(3.14, &i); // f = 0.14, i = 3.0
The sum of the return value and *iptr equals x (except for rounding).
None known.
float modff( float x, float *iptr)
Splits the float x into integer and fractional parts.
x - floating point number to split. iptr - pointer to float that will receive the integer part.
Returns the fractional part of x.
float i; float f = modff(3.14f, &i); // i = 3.0f, f = 0.14f
The result and *iptr have the same sign as x.
None known.
long double modfl( long double x, long double *iptr)
Splits x into integer and fractional parts.
x - input value. iptr - pointer to store the integer part.
Returns the fractional part (x - *iptr).
long double i; long double f = modfl(2.718L, &i); // i = 2.0L, f ˜ 0.718L
Does not raise domain errors.
None known.
float nanf( const char *s)
Construct a quiet NaN from a hexadecimal payload string.
s - Non-NULL, NUL-terminated string of hexadecimal digits,
optionally prefixed with 0x or 0X.
A quiet float NaN. Digits after the first nonhexadecimal character are ignored; an empty tag supplies zero payload bits. Different tags can produce the same NaN.
Include <math.h>. Payload encoding is target-dependent and is not suitable as a portable serialized representation.
Payload assembly shifts signed digits into the high nibble; digits 8 through F can cause undefined C behavior. The big-endian scanner uses a different nibble order from the little-endian scanner, so equal tags need not give matching payload bits across these targets.
long double nanl( const char *s)
Construct a quiet long double NaN from a hexadecimal tag. An optional 0x or 0X prefix is followed by hexadecimal digits. Scanning stops at the first other character.
s - Readable, null-terminated ASCII string. May be empty,
but must not be NULL. Leading whitespace and signs
are not skipped. The string is not modified or retained.
The initial digit sequence must fit in an int index.
A quiet NaN, subject to the scanner limitation below. An empty tag, or a tag with no initial digits after the optional prefix, supplies zero payload bits. Trailing nonhexadecimal text does not produce an error. Payload and sign are representation-dependent. Excess high-order digits are discarded before exponent and quiet bits are imposed; distinct tags may produce the same value. The implementation does not set or clear errno.
Include <math.h>. The implementation allocates no storage. It scans the entire initial digit sequence even when only a fixed number of digits contributes to the result. The 80-bit implementation uses three 32-bit words; the 128-bit implementation uses four. When long double has the same precision as double, nanl is an alias of nan. Do not use NaN tags as a portable serialization format.
The shared scanner uses signed left shifts. On targets with 32-bit int, shifting a hexadecimal digit of 8 through F into bit position 28 has undefined behavior. Such tags have no reliable source-level result. The big-endian scanner reverses nibble placement within each word relative to the little-endian scanner. The same tag need not preserve the same payload across targets.
double nearbyint( double x)
Round x to an integral floating-point value according to the current rounding direction, without retaining newly raised floating-point exception flags when environment save and restore succeed.
x - Double value to round.
The value returned by rint(), in double precision. Signed zeros and infinities retain their sign; NaNs remain NaNs. The result is not a C integer conversion.
Include <math.h> and <fenv.h>. The wrapper saves the entire floating-point environment before rounding and restores it afterward. It does not disable enabled traps.
The wrapper ignores errors from fegetenv() and fesetenv(). On targets where these operations are ineffective or unsupported, exception flags may not be preserved. A trap can prevent restoration. The delegated rint implementation has undefined signed-shift behavior for some small negative inputs.
float nearbyintf( float x)
Round x to an integral floating-point value according to the current rounding direction, without retaining newly raised floating-point exception flags when environment save and restore succeed.
x - Float value to round.
The value returned by rintf(), in float precision. Signed zeros and infinities retain their sign; NaNs remain NaNs. The result is not a C integer conversion.
Include <math.h> and <fenv.h>. The wrapper saves the entire floating-point environment before rounding and restores it afterward. It does not disable enabled traps.
The wrapper ignores errors from fegetenv() and fesetenv(). On targets where these operations are ineffective or unsupported, exception flags may not be preserved. A trap can prevent restoration. The delegated rint implementation has undefined signed-shift behavior for some small negative inputs.
long double nearbyintl( long double x)
Round x to an integral floating-point value according to the current rounding direction, without retaining newly raised floating-point exception flags when environment save and restore succeed.
x - Long double value to round.
The value returned by rintl(), in long double precision. Signed zeros and infinities retain their sign; NaNs remain NaNs. The result is not a C integer conversion.
Include <math.h> and <fenv.h>. The wrapper saves the entire floating-point environment before rounding and restores it afterward. It does not disable enabled traps. Where long double equals double, nearbyintl() aliases nearbyint().
The wrapper ignores errors from fegetenv() and fesetenv(). On targets where these operations are ineffective or unsupported, exception flags may not be preserved. A trap can prevent restoration. The separate rintl() implementation requires correctly set long double evaluation precision; equal-precision aliases inherit the rint() signed-shift defect.
float nextafterf( float x, float y)
Return the adjacent float value in the direction of y.
x - Starting value. y - Direction value, supplied as float.
The adjacent value toward y, or y converted to float when x and y compare equal. Equal zeros return the sign of y. A zero starting value and nonzero direction select the smallest subnormal with the sign of y. If either argument is NaN, the result is NaN. Stepping from infinity toward a finite value returns the largest finite value with the same sign. See BUGS for outward steps at the finite limit.
Include <math.h>. Subnormal results and steps to zero can raise FE_UNDERFLOW and FE_INEXACT. Outward steps at the finite limit can raise FE_OVERFLOW and FE_INEXACT. Enabled traps may prevent return. This function does not set errno.
An outward step from the largest positive or negative finite value can return that same finite value under directed rounding, instead of the corresponding infinity.
long double nextafterl( long double x, long double y)
Return the adjacent long double value in the direction of y.
x - Starting value. y - Value that determines the direction.
If x and y compare equal, return y, including its zero sign. A zero starting value and nonzero direction select the smallest subnormal with the sign of y. If either argument is NaN, the result is NaN. An inward step from infinity returns the largest finite value with the same sign. See BUGS for outward steps at the finite limit.
Include <math.h>. This function has the same behavior as nexttowardl(). Subnormal results can raise FE_UNDERFLOW and FE_INEXACT. Outward steps at the finite limit can raise FE_OVERFLOW and FE_INEXACT. Enabled traps may prevent return. This function does not set errno.
An outward step from the largest positive or negative finite value can return that same finite value under directed rounding, instead of the corresponding infinity. Where long double has greater precision than double, a step from the smallest subnormal to zero does not raise FE_UNDERFLOW or FE_INEXACT. Existing exception flags are not cleared.
float nexttowardf( float x, long double y)
Return the adjacent float value in the direction of y. The direction is determined using the full long double value of y, even when y would round to x if converted to float.
x - Starting value. y - Direction value, supplied as long double.
The adjacent value toward y, or y converted to float when x and y compare equal. Equal zeros return the sign of y. A zero starting value and nonzero direction select the smallest subnormal with the sign of y. If either argument is NaN, the result is NaN. Stepping from infinity toward a finite value returns the largest finite value with the same sign. See BUGS for outward steps at the finite limit.
Include <math.h>. Subnormal results and steps to zero can raise FE_UNDERFLOW and FE_INEXACT. Outward steps at the finite limit can raise FE_OVERFLOW and FE_INEXACT. Enabled traps may prevent return. This function does not set errno.
An outward step from the largest positive or negative finite value can return that same finite value under directed rounding, instead of the corresponding infinity. Stepping from zero toward a negative value is affected by undefined C behavior in this implementation.
long double nexttowardl( long double x, long double y)
Return the adjacent long double value in the direction of y.
x - Starting value. y - Value that determines the direction.
If x and y compare equal, return y, including its zero sign. A zero starting value and nonzero direction select the smallest subnormal with the sign of y. If either argument is NaN, the result is NaN. An inward step from infinity returns the largest finite value with the same sign. See BUGS for outward steps at the finite limit.
Include <math.h>. This function has the same behavior as nextafterl(). Subnormal results can raise FE_UNDERFLOW and FE_INEXACT. Outward steps at the finite limit can raise FE_OVERFLOW and FE_INEXACT. Enabled traps may prevent return. This function does not set errno.
An outward step from the largest positive or negative finite value can return that same finite value under directed rounding, instead of the corresponding infinity. Where long double has greater precision than double, a step from the smallest subnormal to zero does not raise FE_UNDERFLOW or FE_INEXACT. Existing exception flags are not cleared.
int on_exit( void (*func)(int, void *), void *arg)
void perror( const char *string )
looks up the language-dependent error message string affiliated with an error number and writes it, followed by a newline, to the standard error stream.
string - the string to prepend the error message. If NULL only the error
message will be printed, otherwise the error message will be
separated from string by a colon.
double pow( double x, double y)
Computes x raised to the power of y (x^y).
x - the base. y - the exponent.
Returns x raised to y. If the result overflows, sets errno to ERANGE. If x < 0 and y is not an integer, result is NaN and errno is set to EDOM.
double r = pow(2.0, 3.0); // returns 8.0
Domain and range errors are handled per IEEE 754.
Some edge cases may differ slightly from hardware FPU behavior.
float powf( float x, float y)
Computes x raised to the power y.
x - base value. y - exponent.
x raised to the power y as a float.
float r = powf(2.0f, 3.0f); // 8.0f
If x is negative and y is not an integer, the result is a domain error.
May return NaN for invalid domains, like powf(-2.0f, 0.5f)
long double powl( long double x, long double y)
Computes x raised to the power y.
x - base value. y - exponent.
Returns x^y.
long double r = powl(2.0L, 3.0L); // returns 8.0L
Domain error if x < 0 and y is not an integer.
None known.
int printf( const char * restrict format, ...)
Formats a list of arguments and prints them to standard out.
The format string is composed of zero or more directives: ordinary
characters (not %), which are copied unchanged to the output
stream; and conversion specifications, each of which results in
fetching zero or more subsequent arguments Each conversion
specification is introduced by the character %. The arguments must
correspond properly (after type promotion) with the conversion
specifier. After the %, the following appear in sequence:
\begin{itemize}
\item Zero or more of the following flags:
\begin{description}
\item[#] specifying that the value should be converted to an
``alternate form''. For c, d, i, n, p, s, and u conversions, this
option has no effect. For o conversions, the precision of the
number is increased to force the first character of the output
string to a zero (except if a zero value is printed with an
explicit precision of zero). For x and X conversions, a non-zero
result has the string `0x' (or `0X' for X conversions) prepended to
it. For e, E, f, g, and G conversions, the result will always
contain a decimal point, even if no digits follow it (normally, a
decimal point appears in the results of those conversions only if a
digit follows). For g and G conversions, trailing zeros are not
removed from the result as they would otherwise be.
\item[0] specifying zero padding. For all conversions except n, the
converted value is padded on the left with zeros rather than
blanks. If a precision is given with a numeric conversion (d, i, o,
u, i, x, and X), the 0 flag is ignored.
\item[-] (a negative field width flag) indicates the converted
value is to be left adjusted on the field boundary. Except for n
conversions, the converted value is padded on the right with
blanks, rather than on the left with blanks or zeros. A -
overrides a 0 if both are given.
\item[ ] (a space) specifying that a blank should be left before a
positive number produced by a signed conversion (d, e, E, f, g, G,
or i). + specifying that a sign always be placed before a number
produced by a signed conversion. A + overrides a space if both are
used.
\item['] specifying that in a numerical argument the output is to
be grouped if the locale information indicates any. Note that many
versions of gcc cannot parse this option and will issue a warning.
\end{description}
\item An optional decimal digit string specifying a minimum field
width. If the converted value has fewer characters than the field
width, it will be padded with spaces on the left (or right, if the
left-adjustment flag has been given) to fill out the field width.
\item An optional precision, in the form of a period (`.') followed
by an optional digit string. If the digit string is omitted, the
precision is taken as zero. This gives the minimum number of digits
to appear for d, i, o, u, x, and X conversions, the number of
digits to appear after the decimal-point for e, E, and f
conversions, the maximum number of significant digits for g and G
conversions, or the maximum number of characters to be printed from
a string for s conversions.
\item The optional character h, specifying that a following d, i,
o, u, x, or X conversion corresponds to a short int or unsigned
short int argument, or that a following n conversion corresponds to
a pointer to a short int argument.
\item The optional character l (ell) specifying that a following d,
i, o, u, x, or X conversion applies to a pointer to a long int or
unsigned long int argument, or that a following n conversion
corresponds to a pointer to a long int argument. Linux provides a
non ANSI compliant use of two l flags as a synonym to q or L. Thus
ll can be used in combination with float conversions. This usage
is, however, strongly discouraged.
\item The character L specifying that a following e, E,
f, g, or G conversion corresponds to a long double
argument, or a following d, i, o, u, x, or X conversion corresponds to a long long argument. Note
that long long is not specified in ANSI C and
therefore not portable to all architectures.
\item The optional character q. This is equivalent to L. See the
STANDARDS and BUGS sections for comments on the use of ll, L, and
q.
\item A Z character specifying that the following integer (d, i, o,
u, i, x, and X), conversion corresponds to a size_t argument.
\item A character that specifies the type of conversion to be
applied.
A field width or precision, or both, may be indicated by an
asterisk `*' instead of a digit string. In this case, an int
argument supplies the field width or precision. A negative field
width is treated as a left adjustment flag followed by a positive
field width; a negative precision is treated as though it were
missing.
The conversion specifiers and their meanings are:
\begin{description}
\item[diouxX] The int (or appropriate variant) argument is
converted to signed decimal (d and i), unsigned octal (o, unsigned
decimal (u, or unsigned hexadecimal (x and X) notation. The letters
abcdef are used for x conversions; the letters ABCDEF are used for
X conversions. The precision, if any, gives the minimum number of
digits that must appear; if the converted value requires fewer
digits, it is padded on the left with zeros.
\item[eE] The double argument is rounded and converted in the style
[<->]d.dddedd where there is one digit before the decimal-point
character and the number of digits after it is equal to the
precision; if the precision is missing, it is taken as 6; if the
precision is zero, no decimal-point character appears. An E
conversion uses the letter E (rather than e) to introduce the
exponent. The exponent always contains at least two digits; if the
value is zero, the exponent is 00.
\item[f] The double argument is rounded and converted to decimal
notation in the style [-]ddd.ddd, where the number of digits after
the decimal-point character is equal to the precision
specification. If the precision is missing, it is taken as 6; if
the precision is explicitly zero, no decimal-point character
appears. If a decimal point appears, at least one digit appears
before it.
\item[g] The double argument is converted in style f or e (or E for
G conversions). The precision specifies the number of significant
digits. If the precision is missing, 6 digits are given; if the
precision is zero, it is treated as 1. Style e is used if the
exponent from its conversion is less than -4 or greater than or
equal to the precision. Trailing zeros are removed from the
fractional part of the result; a decimal point appears only if it
is followed by at least one digit.
\item[c] The int argument is converted to an unsigned char, and the
resulting character is written.
\item[s] The ``char *'' argument is expected to be a pointer to an
array of character type (pointer to a string). Characters from the
array are written up to (but not including) a terminating NUL
character; if a precision is specified, no more than the number
specified are written. If a precision is given, no null character
need be present; if the precision is not specified, or is greater
than the size of the array, the array must contain a terminating
NUL character.
\item[p] The ``void *'' pointer argument is printed in hexadecimal
(as if by %#x or %#lx).
\item[n] The number of characters written so far is stored into the
integer indicated by the ``int *'' (or variant) pointer argument.
No argument is converted.
\item[%] A `%' is written. No argument is converted. The complete
conversion specification is `%%'.
\end{description}
\end{itemize}
In no case does a non-existent or small field width cause
truncation of a field; if the result of a conversion is wider than
the field width, the field is expanded to contain the conversion
result.
format - Format string as described above ... - Arguments for the format string
The number of characters written to stdout or EOF on error.
To print a date and time in the form `Sunday, July 3,
10:02', where weekday and month are pointers to strings:
#include <stdio.h>
fprintf (stdout, "%s, %s %d, %.2d:%.2d\n",
weekday, month, day, hour, min);
To print to five decimal places:
#include <math.h>
#include <stdio.h>
fprintf (stdout, "pi = %.5f\n", 4 * atan(1.0));
To allocate a 128 byte string and print into it:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
char *newfmt(const char *fmt, ...)
{
char *p;
va_list ap;
if ((p = malloc(128)) == NULL)
return (NULL);
va_start(ap, fmt);
(void) vsnprintf(p, 128, fmt, ap);
va_end(ap);
return (p);
}
All functions are fully ANSI C3.159-1989 conformant, but provide the additional flags q, Z and ' as well as an additional behavior of the L and l flags. The latter may be considered to be a bug, as it changes the behavior of flags defined in ANSI C3.159-1989. The effect of padding the %p format with zeros (either by the 0 flag or by specifying a precision), and the benign effect (i.e., none) of the # flag on %n and %p conversions, as well as nonsensical combinations such as are not standard; such combinations should be avoided. Some combinations of flags defined by ANSI C are not making sense in ANSI C (e.g. %Ld). While they may have a well-defined behavior on Linux, this need not to be so on other architectures. Therefore it usually is better to use flags that are not defined by ANSI C at all, i.e. use q instead of L in combination with diouxX conversions or ll. The usage of q is not the same as on BSD 4.4, as it may be used in float conversions equivalently to L. Because sprintf and vsprintf assume an infinitely long string, callers must be careful not to overflow the actual space; this is often impossible to assure.
int putc( int c, FILE * stream)
Write one character to the specified stream.
c - The character to output stream - The character is written to this stream
The character written or EOF on error.
int puts( const char * str)
Print a string to stdout. A newline ('\n') is emmitted after the
string.
str - Print this string
> 0 on success and EOF on error. On error, the reason is put in errno.
#include <errno.h>
if (puts ("Hello World.") != EOF)
fprintf (stderr, "Success");
else
fprintf (stderr, "Failure: errno=%d", errno);
wint_t putwc( wchar_t wc, FILE *stream)
Write a wide character by calling fputwc(). The current conversion routine encodes the value as UTF-8 and writes the bytes in order.
wc - Unicode scalar value to write. The supported domain excludes
surrogate values and values above U+10FFFF. See BUGS before writing
non-ASCII values with the current implementation.
stream - Non-NULL open output stream. Remains owned by the caller.
The character value on success, or WEOF on a reported error. A stream not open for writing sets errno to EACCES and its error indicator. A rejected conversion sets EILSEQ and the error indicator. A failed byte write sets the error indicator and maps the DOS error to errno. Allocation failure is not safely reported; see BUGS.
Include <wchar.h>. This wrapper evaluates each argument once and does not close the stream. L'\0' writes one zero byte. The converter is stateless and ignores the stream's conversion-state object. A write error may occur after earlier bytes have been written. There is no rollback, so the stream can contain a partial UTF-8 sequence. A successful call does not establish that buffered output has reached persistent storage. Append mode attempts to seek to the end before writing, but the seek result is not checked. Call from DOS process context with the C runtime active. Allocation and file-handler writes can block; no timeout or cancellation is supplied. Coordinate access to both the stream and locale state. The wrapper adds no lock spanning conversion and all byte writes.
fputwc() allocates the current locale's maximum multibyte size, but wcrtomb() always emits UTF-8. The default C locale supplies one byte; non-ASCII conversion can therefore exceed the requested buffer size. This is an implementation defect, not a supported encoding mode. The allocation result is unchecked. If allocation fails, wcrtomb() treats NULL as a length query; the subsequent write loop dereferences that NULL pointer for an otherwise valid character. There is no safe ENOMEM return path in this implementation. Stream orientation is neither established nor checked. Conversion of signed negative wchar_t values is not consistently rejected by the underlying converter; pass only values in the stated scalar domain.
t_t putwchar( wchar_t wc) FUNCTION The putwchar() function is the wide-character equivalent of putchar(). It writes the wide character wc to the standard output stream using the current locale to convert it to its multibyte representation.
wc - The wide character to be written to stdout.
Returns the wide character written as a wint_t value on success. Returns WEOF if an error occurs.
putwchar(L'?');
The output is affected by the current locale, particularly LC_CTYPE, which governs the multibyte encoding used during output. Internally, putwchar() is equivalent to fputwc(wc, stdout).
If stdout is not a valid output stream or the locale does not support the character, the function may fail or produce unexpected results.
void qsort( void * a, size_t n, size_t es, int (* cmp)(const void *, const void *))
Sort the array a. It contains n elements of the size es. Elements are compares using the function cmp().
a - The array to sort
n - The number of elements in the array
es - The size of a single element in the array
cmp - The function which is called when two elements must be
compared. The function gets the addresses of two elements
of the array and must return 0 is both are equal, < 0 if
the first element is less than the second and > 0 otherwise.
None.
// Use this function to compare to stringpointers
int cmp_strptr (const char ** sptr1, const char ** sptr2)
{
return strcmp (*sptr1, *sptr2);
}
// Sort an array of strings
char ** strings;
// fill the array
strings = malloc (sizeof (char *)*4);
strings[0] = strdup ("h");
strings[1] = strdup ("a");
strings[2] = strdup ("f");
strings[3] = strdup ("d");
// Sort it
qsort (strings, sizeof (char *), 4, (void *)cmp_strptr);
void qsort_r( void * a, size_t n, size_t es, int (* cmp)(const void *, const void *, void *), void * arg)
Sort the array a, which contains n elements of size es, exactly like qsort(), except that the comparison function cmp() takes a third argument. The pointer arg is passed unchanged as that third argument on every call, letting the comparison capture context without using global variables (so it is reentrant and thread safe).
a - The array to sort
n - The number of elements in the array
es - The size of a single element in the array
cmp - The comparison function. It is called with the addresses of two
elements and the arg pointer, and must return 0 if both are
equal, < 0 if the first element is less than the second and
> 0 otherwise.
arg - An arbitrary pointer passed through to every cmp() call.
None.
// Sort integers relative to a pivot supplied via arg.
int cmp_rel (const void *a, const void *b, void *arg)
{
int pivot = *(int *)arg;
int da = abs(*(const int *)a - pivot);
int db = abs(*(const int *)b - pivot);
return da - db;
}
int pivot = 5;
qsort_r (array, count, sizeof(int), cmp_rel, &pivot);
This implementation uses the GNU/glibc argument order: the context pointer is the last parameter of qsort_r() and the last parameter of the comparison function (compar(a, b, arg)).
void quick_exit( int status)
Cause normal-ish program termination: the functions registered with at_quick_exit() are called (in reverse order of registration), then control is handed to _Exit(status).
status - the exit status reported to the host.
This function does not return.
Unlike exit(), quick_exit() does not call atexit() handlers and does not flush or close C streams (it terminates via _Exit()).
int raise( int signum)
Calls the handler of a signal
Signal handler to be called.
0: OK -1: error calling handler, errno will be set.
The behavior of raise() follows the BSD semantics. For each signal the system keeps track of a signal handler is already being called. If not, the signal handler is called; when yes this will logged and the handler will be recalled when the first handler returns. If the a new handler is registered that one will be used then. When sigaction() has been used to register a handler the following flags are honored: SA_SIGINFO - call sa_sigaction(signum, NULL, NULL) instead of sa_handler SA_RESETHAND - reset to SIG_DFL after one delivery SA_NODEFER - don't block the signal during its own handler
int rand( void)
A random number generator.
None.
A pseudo-random integer between 0 and RAND_MAX.
void * realloc( void * oldmem, size_t size)
Change the size of an allocated part of memory. The memory must have been allocated by malloc() or calloc(). If you reduce the size, the old contents will be lost. If you enlarge the size, the new contents will be undefined.
oldmem - What you got from malloc() or calloc(). size - The new size.
A pointer to the allocated memory or NULL. If you don't need the memory anymore, you can pass this pointer to free(). If you don't, the memory will be freed for you when the application exits.
If you get NULL, the memory at oldmem will not have been freed and can still be used.
void * realloc_nocopy( void * oldmem, size_t size)
Change the size of an allocated part of memory. The memory must have been allocated by malloc(), calloc(), realloc() or realloc_nocopy(). The reallocated buffer, unlike with realloc(), is not guaranteed to hold a copy of the old one.
oldmem - What you got from malloc(), calloc(), realloc() or realloc_nocopy().
If NULL, the function will behave exactly like malloc().
size - The new size. If 0, the buffer will be freed.
A pointer to the allocated memory or NULL. If you don't need the memory anymore, you can pass this pointer to free(). If you don't, the memory will be freed for you when the application exits.
If you get NULL, the memory at oldmem will not have been freed and can still be used. This function is AROS specific.
double remainder( double x, double y)
Returns the IEEE 754-style remainder of x with respect to y.
x - dividend. y - divisor.
Remainder r such that r = x - n*y, where n is the integer nearest to x/y.
double r = remainder(5.3, 2.0); // r = 1.3
If the result is exactly halfway between two integers, the even integer is used.
Returns NaN if y is zero or x or y is NaN.
float remainderf( float x, float y)
Computes IEEE remainder of x/y.
x - dividend y - divisor
Remainder with magnitude less than y/2.
float r = remainderf(5.3f, 2.0f); // 1.3f
Different from fmodf(); may be negative.
Returns NaN if y == 0.
long double remainderl( long double x, long double y)
Compute x - n * y, where n is the integer nearest to the exact quotient x / y. Ties select the even integer, independently of the current rounding direction.
x - Dividend. y - Divisor.
For finite operands and nonzero y, return a remainder with magnitude at most half of |y|. A zero result has the sign of x. With finite x and infinite y, return x. If x is infinite, y is zero, or either argument is NaN, return NaN.
Include <math.h>. A zero divisor or infinite dividend raises FE_INVALID unless a quiet NaN operand suppresses the exception. Enabled traps may prevent return. This function does not set errno.
Where long double has greater precision than double, results are not reliable when the nearest integer quotient has magnitude 2^31 or greater.
int remove( const char * pathname)
Deletes a file or directory.
pathname - Complete path to the file or directory.
0 on success and -1 on error. In case of an error, errno is set.
double remquo( double x, double y, int *quo)
Computes the remainder of dividing x by y and returns part of the quotient via `quo`.
x - the dividend. y - the divisor. quo - pointer to an int to store part of the quotient.
Returns the remainder and stores low bits of quotient in *quo. If `quo` is NULL or y is zero, returns NaN and sets errno to EDOM.
int q; double r = remquo(7.0, 2.0, &q); // r = 1.0, q = 3
The remainder has the same sign as x and magnitude less than y.
Some platforms may not produce identical quotients for equal inputs.
float remquof( float x, float y, int *quo)
Compute the floating-point remainder and low quotient bits. For finite x and nonzero finite y, the remainder is x - n * y, where n is the integer nearest to x / y; ties select the even integer. The current rounding direction does not select n.
x - Dividend.
y - Divisor.
quo - Pointer to a writable int that receives the low 31 bits
of the magnitude of n, with the sign of x / y. If those
bits are all zero, the stored value is zero.
Return the remainder, whose magnitude is at most half of |y|. A zero result has the sign of x. With finite x and infinite y, return x and store zero in *quo. If x is infinite, y is zero, or either argument is NaN, return NaN and leave *quo unchanged.
Include <math.h>. A zero divisor or infinite dividend raises FE_INVALID unless a quiet NaN operand suppresses the exception. Enabled traps may prevent return. This function does not set errno.
Results are not reliable when finite operands satisfy |x| > |y| and y is subnormal.
g double remquol( long double x, long double y, int *quo)
Computes the remainder of dividing x by y and returns part of the quotient via `quo`.
x - the dividend. y - the divisor. quo - pointer to an int to store part of the quotient.
Returns the remainder and stores low bits of quotient in *quo. If `quo` is NULL or y is zero, returns NaN and sets errno to EDOM.
int q; double r = remquo(7.0, 2.0, &q); // r = 1.0, q = 3
The remainder has the same sign as x and magnitude less than y.
Some platforms may not produce identical quotients for equal inputs.
int rename( const char * oldpath, const char * newpath)
Renames a file or directory.
oldpath - Complete path to existing file or directory. newpath - Complete path to the new file or directory.
0 on success and -1 on error. In case of an error, errno is set.
void rewind( FILE * stream)
Change the current position in a stream to the beginning. It also clears the error indication of the stream.
stream - Modify this stream
float rintf( float x)
Round x to an integral floating-point value using the current rounding direction.
x - Float value to round.
The rounded float value. Nearest ties select the even integer; other modes follow the current rounding direction. Signed zeros and infinities keep their sign; NaNs remain NaNs.
Include <math.h> and <fenv.h>. Unlike nearbyintf(), rounding may raise FE_INEXACT. Unlike roundf(), ties are not always rounded away from zero.
The small negative-input path shifts a signed integer into its sign bit, which is undefined behavior in C. Results for that path may depend on the compiler.
long double rintl( long double x)
Round x to an integral floating-point value using the current rounding direction.
x - Long double value to round.
The rounded long double value. Nearest ties select the even integer; other modes follow the current rounding direction. Signed zeros and infinities keep their sign; NaNs remain NaNs.
Include <math.h> and <fenv.h>. Unlike nearbyintl(), rounding may raise FE_INEXACT. Unlike roundl(), ties are not always rounded away from zero.
The separate implementation requires intermediate arithmetic evaluated in long double precision. A narrower x87 precision setting can give incorrect results; wider evaluation can double-round. Equal-precision aliases inherit the rint() signed-shift defect for small negative inputs.
double round( double x)
Round x to the nearest integral floating-point value, with halfway cases rounded away from zero.
x - Double value to round.
For finite x, an integral-valued double result. For example, 0.5 rounds to 1 and -0.5 rounds to -1. The sign of zero is preserved; infinities remain infinite and NaNs remain NaNs.
Include <math.h>. Rounding is independent of the current rounding direction; unlike rint(), halfway values round away from zero. Exception flags may change.
float roundf( float x)
Round x to the nearest integral floating-point value, with halfway cases rounded away from zero.
x - Float value to round.
For finite x, an integral-valued float result. For example, 0.5 rounds to 1 and -0.5 rounds to -1. The sign of zero is preserved; infinities remain infinite and NaNs remain NaNs.
Include <math.h>. Rounding is independent of the current rounding direction; unlike rintf(), halfway values round away from zero. Exception flags may change.
long double roundl( long double x)
Round x to the nearest integral floating-point value, with halfway cases rounded away from zero.
x - Long double value to round.
For finite x, an integral-valued long double result. For example, 0.5 rounds to 1 and -0.5 rounds to -1. The sign of zero is preserved; infinities remain infinite and NaNs remain NaNs.
Include <math.h>. Rounding is independent of the current rounding direction; unlike rintl(), halfway values round away from zero. Exception flags may change. On equal-precision long double targets, roundl() aliases round().
double scalb( double x, double fn)
Scale x by 2 raised to the integral value fn.
x - Double value to scale.
fn - Exponent, supplied as a double. Finite values must be
integral. See BUGS for negative fractional exponents.
The scaled value in double. Exact representable results require no rounding; inexact subnormal results and range limits depend on the current rounding direction. For finite integral fn, signed zero and infinity retain the sign of x. A NaN argument produces a NaN. A finite nonintegral fn produces a NaN, subject to BUGS. For fn equal to positive infinity, returns x * infinity. For fn equal to negative infinity, returns x / infinity. Thus zero with positive infinity, or infinite x with negative infinity, produces a NaN.
Include <math.h>. Prefer scalbn() for an int exponent or scalbln() for a long exponent. The function does not assign errno. Invalid arguments and range errors can raise floating-point exceptions; the integrality check can also raise inexact. Enabled traps may prevent return.
For -1 < fn < 0, the integrality check invokes undefined C behavior. Do not rely on a NaN result for these inputs.
float scalbf( float x, float fn)
Scale x by 2 raised to the integral value fn.
x - Float value to scale.
fn - Exponent, supplied as a float. Finite values must be
integral. See BUGS for negative fractional exponents.
The scaled value in float. Exact representable results require no rounding; inexact subnormal results and range limits depend on the current rounding direction. For finite integral fn, signed zero and infinity retain the sign of x. A NaN argument produces a NaN. A finite nonintegral fn produces a NaN, subject to BUGS. For fn equal to positive infinity, returns x * infinity. For fn equal to negative infinity, returns x / infinity. Thus zero with positive infinity, or infinite x with negative infinity, produces a NaN.
Include <math.h>. Prefer scalbnf() for an int exponent or scalblnf() for a long exponent. The function does not assign errno. Invalid arguments and range errors can raise floating-point exceptions; the integrality check can also raise inexact. Enabled traps may prevent return.
For -1 < fn < 0, the integrality check invokes undefined C behavior. Do not rely on a NaN result for these inputs.
double scalbln( double x, long n)
Scale x by an integral power of two. The exponent is clamped to [-65536, 65536] before calling scalbn().
x - Double value to scale.
n - Base-two exponent. Values outside the clamp interval are
treated as the nearest endpoint.
The scaled double value. An exact result is returned without rounding; otherwise the current rounding mode applies. Signed zero retains its sign. Infinities and NaNs propagate.
Include <math.h>. Overflow and underflow may raise floating-point exceptions. Enabled traps may prevent the function from returning.
float scalblnf( float x, long n)
Scale x by an integral power of two. The exponent is clamped to [-65536, 65536] before calling scalbnf().
x - Float value to scale.
n - Base-two exponent. Values outside the clamp interval are
treated as the nearest endpoint.
The scaled float value. An exact result is returned without rounding; otherwise the current rounding mode applies. Signed zero retains its sign. Infinities and NaNs propagate.
Include <math.h>. Overflow and underflow may raise floating-point exceptions. Enabled traps may prevent the function from returning.
long double scalblnl( long double x, long n)
Scale x by an integral power of two. The exponent is clamped to [-65536, 65536] before calling scalbnl().
x - Long double value to scale.
n - Base-two exponent. Values outside the clamp interval are
treated as the nearest endpoint.
The scaled long double value, subject to the current rounding mode and the limitation described in BUGS. Signed zero retains its sign. Infinities and NaNs propagate.
Include <math.h>. Overflow and underflow may raise floating-point exceptions. Enabled traps may prevent the function from returning.
When long double has a separate extended-precision implementation, scalbnl() narrows a long double underflow constant through the double-precision copysign() function. Under downward rounding, a negative input can produce negative zero when a negative subnormal result is required. The equal-precision double alias does not use this implementation path.
float scalbnf( float x, int n)
Scale x by an integral power of two.
x - Value to scale. n - Base-two exponent.
The scaled float value. Inexact results are rounded according to the current floating-point rounding direction. Signed zero and infinity retain their signs; NaN produces NaN.
Include <math.h>. Overflow and underflow may raise floating-point exceptions. This implementation does not set errno. ldexpf() is an alias of scalbnf().
The implementation adds n to a signed exponent without checking for overflow. For x = 1 and n = INT_MAX, this causes undefined signed integer arithmetic before the range check.
int scanf( const char * restrict format, ...)
The number of converted parameters
void setbuf( FILE * restrict stream, char * restrict buf)
Sets a buffer associated with a stream.
stream: stream to set a buffer for.
buf: if it points to an array of at least size BUFSIZ it will be used
as a buffer with mode _IOFBF. If it is NULL mode will be set to
_IONBF
-
int setjmp( jmp_buf env)
Save the calling environment for a later nonlocal return with longjmp().
env - Writable jmp_buf object. Keep it intact and alive until no further
jump will use it. A new save replaces the previous environment.
Zero on the initial return. After longjmp(), its nonzero val argument, or 1 when val was zero.
Include <setjmp.h> and use jmp_buf with its declared alignment. The saved register and stack layout depends on the target CPU. Use setjmp() as a complete statement, a complete if/while condition, or in such a condition with unary ! or comparison against an integer constant expression. Do not assign its result to a variable or embed it in another expression. Only jump back while the saving function is still active in the same thread. Do not leave and then re-enter the scope of a variably modified object this way. Changed non-volatile automatic locals in the saving function have indeterminate values after the jump. This is not a snapshot of memory, files or acquired resources. Floating- point state saved by the CPU implementation varies; do not use this interface to save or restore a floating-point environment. No signal mask is saved.
longjmp() posixc/sigsetjmp()
char *setlocale( int category, const char *locale)
category - category as defined in locale.h locale - string representing the desired locale (see notes)
The lconv struct
stdc.library supports "C" (and if the compiler has been compiled with __WCHAR_MAX__ > 255, "UTF8") locale(s). Currently accepted values for locale are "C", and "C.UTF-8".
int setvbuf( FILE *stream, char *buf, int mode, size_t size)
Sets the buffer and the mode associated with a stream.
stream: stream to set buffer on
buf: the buffer to be associated, when NULL a buffer will be allocated
and freed on close or new setvbuf. Should be longword aligned.
mode: mode for buffering
- _IOFBF: fully buffered
- _IOLBF: line buffered
- _IONBF: Not buffered
size: size of the buffer (needs to be at least 208).
0 on success, EOF on error. errno indicated error. Function fails when size < 208 and buf != NULL.
__sighandler_t *signal( int signum, __sighandler_t *handler)
Set signal handler for a signal.
signum - the signal number to register a handler for
handler - the signal handler; can be SIG_IGN, SIG_DFL or a function
pointer that will handle the signal
The old handler that was replaced by the new handler.
float significandf( float x)
Return the signed binary significand of x.
x - Float value to normalize. See BUGS for subnormal inputs.
For finite nonzero x, the intended result is x scaled by 2 raised to -ilogbf(x), with magnitude at least 1 and less than 2. Normal inputs produce this result exactly. Signed zero and infinity retain their sign. NaN produces a NaN.
Include <math.h>. Unlike frexpf(), this function returns a significand with magnitude in [1, 2) and does not return an exponent. For example, 12.0f yields 1.5f and -0.5f yields -1.0f. The function does not assign errno. Signaling-NaN handling and exception delivery depend on the target.
Subnormal inputs invoke undefined C behavior during exponent extraction. Their normalized result is not guaranteed.
double sin( double x)
Computes the sine of x (x in radians).
x - input angle in radians.
Returns sin(x).
double val = sin(3.14159 / 2); // approximately 1.0
Uses range reduction and polynomial approximation internally.
None known.
void sincos( double x, double *sn, double *cs)
Compute the sine and cosine of x.
x - Angle in radians. sn - Pointer to a writable double for the sine. cs - Pointer to a separate writable double for the cosine.
Store sin(x) in *sn and cos(x) in *cs. No value is returned. For positive or negative zero, store x in *sn and 1 in *cs. For infinity or NaN, both outputs are NaN.
Include <math.h>. An infinite argument raises FE_INVALID. Enabled floating-point traps may prevent completion.
Argument reduction assumes round-to-nearest. Other rounding modes can produce inaccurate results.
void sincosf( float x, float *sn, float *cs)
Compute the sine and cosine of x.
x - Angle in radians. sn - Pointer to a writable float for the sine. cs - Pointer to a separate writable float for the cosine.
Store sin(x) in *sn and cos(x) in *cs. No value is returned. For positive or negative zero, store x in *sn and 1 in *cs. For infinity or NaN, both outputs are NaN.
Include <math.h>. An infinite argument raises FE_INVALID. Enabled floating-point traps may prevent completion.
Argument reduction assumes round-to-nearest. Other rounding modes can produce inaccurate results.
void sincosl( long double x, long double *sn, long double *cs)
Compute the sine and cosine of x.
x - Angle in radians. sn - Pointer to a writable long double for the sine. cs - Pointer to a separate writable long double for the cosine.
Store sin(x) in *sn and cos(x) in *cs. No value is returned. For positive or negative zero, store x in *sn and 1 in *cs. For infinity or NaN, both outputs are NaN.
Include <math.h>. An infinite argument raises FE_INVALID. Enabled floating-point traps may prevent completion.
Argument reduction assumes round-to-nearest. Other rounding modes can produce inaccurate results. With a 113-bit long-double significand, calls that require argument reduction may leave one output unwritten or negate its previous value instead of producing the requested result.
float sinf( float x)
Computes the sine of x (x in radians).
x - input angle in radians.
The sine of x.
float val = sinf(3.14159f / 2); // val approx 1.0f
Domain: all real numbers.
None known.
double sinh( double x)
Computes the hyperbolic sine of x.
x - input value.
Returns sinh(x) = (e^x - e^{-x}) / 2.
double val = sinh(1.0);
Uses exponentials internally for calculation.
None known.
float sinhf( float x)
Computes the hyperbolic sine of x.
x - input float
Returns sinh(x).
float r = sinhf(1.0f); // ˜ 1.175201
Uses exponential functions internally.
None known.
long double sinhl( long double x)
Computes the hyperbolic sine of x.
x - input value.
Returns sinh(x) = (e^x - e^{-x}) / 2.
double val = sinh(1.0);
Uses exponentials internally for calculation.
None known.
long double sinl( long double x)
Computes the sine of x (x in radians).
x - input angle in radians.
Returns sin(x).
double val = sin(3.14159 / 2); // approximately 1.0
Uses range reduction and polynomial approximation internally.
None known.
int snprintf( char * str, size_t n, const char * format, ...)
C99 says:The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.
str - The formatted string is written into this variable. You
must make sure that it is large enough to contain the
result.
n - At most n characters are written into the string. This
includes the final 0.
format - Format string as described above
... - Arguments for the format string
The snprintf function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.
int sprintf( char * str, const char * format, ...)
Formats a list of arguments and writes them into the string str.
str - The formatted string is written into this variable. You
must make sure that it is large enough to contain the
result.
format - Format string as described above
... - Arguments for the format string
The number of characters written into the string.
No checks are made that str is large enough for the result.
double sqrt( double x)
Computes the square root of x.
x - input value (must be non-negative).
Returns vx. Returns NaN and sets errno to EDOM if x < 0.
double val = sqrt(4.0); // returns 2.0
Uses IEEE 754 semantics.
None known.
float sqrtf( float x)
Computes square root of x.
x - input float (= 0)
Square root of x.
float r = sqrtf(4.0f); // 2.0f
Returns NaN if x < 0.
None known.
long double sqrtl( long double x)
Computes the square root of x with extended precision.
x - input value (must be non-negative).
Returns vx as a long double. Returns NaN and sets errno to EDOM if x < 0.
long double val = sqrtl(4.0L); // returns 2.0L
Provides higher precision than sqrt().
None known.
void srand( unsigned int seed)
Set the starting value for the random number generator rand() If a seed value is set to a value the same stream of pseudo-random numbers will be generated by rand() for the same seed value.
seed - New start value
None.
One seed value per stdc.library is kept which normally corresponds with per task.
int sscanf( const char *str, const char *format, ...)
Scan the specified string and convert it into the arguments as specified by format.
str - The routine examines this string. format - Format string. See scanf() for a description ... - Arguments for the result
The number of converted parameters.
size_t stccpy( char * dest, const char * src, size_t n)
Copy a string. Works like an assignment "dest=src;". At most n characters are copied.
dest - The string is copied into this variable. Make sure it is
large enough.
src - This is the new contents of dest.
n - How many characters to copy at most. If the string src is
smaller than that, only strlen(str)+1 bytes are copied.
The number of copied characters.
No check is made that dest is large enough for src. SAS/C specific.
int stcd_l( const char * in, long * lvalue)
Convert decimal string to a long integer
in - The decimal string to be converted lvalue - Pointer to long where the result is saved
length of characters converted. >= 1 means success. 0 means failure.
SAS/C specific
int stch_l( const char * in, long * lvalue)
Convert hexadecimal string to a long integer
in - The hexadecimal string to be converted lvalue - Pointer to long where the result is saved
Number of characters converted
SAS/C specific
int stcl_d( char * out, long lvalue)
Convert an long integer to a decimal string
out - Result will be put into this string uivalue - the value to convert
The number of characters written into the string
SAS/C specific
int stcl_h( char * out, long lvalue)
Convert an long integer to a hex string
out - Result will be put into this string uivalue - the value to convert
The number of characters written into the string
SAS/C specific
int stcl_o( char * out, long lvalue)
Convert an long integer to an octal string
out - Result will be put into this string uivalue - the value to convert
The number of characters written into the string
SAS/C specific
int stco_l( const char * in, long * lvalue)
Convert octal string to a long integer
in - The octal string to be converted lvalue - Pointer to long where the result is saved
1 means success. 0 means failure.
SAS/C specific
int stcu_d( char * out, unsigned uivalue)
Convert an unsigned integer to a decimal string
out - Result will be put into this string uivalue - the value to convert
The number of characters written into the string
SAS C specific
char * stpblk( const char * str )
Searches for the first non-blank character in a string. A blank character is defined as one that isspace() treats like one (ie. spaces, tabs and newlines).
str - String to search.
A pointer to the first occurrence of a non-blank character in str.
char *hello = " Hello"; char *empty = " "; printf( stpblk( hello ) ); --> Hello printf( stpblk( empty ) ); --> printf( "%d", strlen( stpblk( hello ) ) ); --> 5 printf( "%d", strlen( stpblk( empty ) ) ); --> 0
This function always returns a valid pointer as provided str isn't NULL. If there are no non-blank characters in the string, a pointer to the trailing '\0' is returned (ie. an empty string).
char * stpcpy( char * dest, const char * src)
Copy a string returning pointer to its end.
dest - The string is copied into this variable. Make sure it is
large enough.
src - This is the new contents of dest.
pointer to the end of the string dest (address of it's null character)
No check is made that dest is large enough for src.
char * stpsym( char * str_ptr, char * dest_ptr, int dest_size)
Searches for a symbol in a string.
str_ptr - points to the string to scan dest_ptr - points to the string where stpsym stores the symbol dest_size - specifies the size in bytes of *dest_ptr
Pointer to the next character in the string after the symbol. If stpsym could not find a symbol, it returns str_ptr.
#include <string.h>
#include <stdio.h>
int main(void)
{
char *text;
char symbol[10];
char *r;
text = "alpha1 2";
r = stpsym(text,symbol,10);
printf("%s",symbol); // prints "alpha1"
}
A symbol consists of an alphabetic character followed by zero or more alphanumeric characters. stpsym() does not skip leading space characters. Note that if you want to retrieve a symbol of length n, you need to ensure that *dest_ptr can accommodate at least n+1 elements, and that dest_size == n+1. This extra element is needed for the terminating null character.
int strcasecmp( const char * str1, const char * str2)
Calculate str1 - str2 ignoring case.
str1, str2 - Strings to compare
The difference of the strings. The difference is 0, if both are equal, < 0 if str1 < str2 and > 0 if str1 > str2. Note that it may be greater then 1 or less than -1.
This function is not part of a library and may thus be called any time.
char * strcasestr( const char * str, const char * search)
Searches for a string in a string.
str - Search this string search - Look for this string
A pointer to the first occurrence of search in str or NULL if search is not found in str.
char buffer[64]; strcpy (buffer, "Hello "); // This returns a pointer to the first l in buffer. strcasestr (buffer, "llo "); // This returns NULL strcasestr (buffer, "llox");
char * strcat( char * dest, const char * src)
Concatenates two strings.
dest - src is appended to this string. Make sure that there
is enough room for src.
src - This string is appended to dest
dest.
char buffer[64]; strcpy (buffer, "Hello "); strcat (buffer, "World."); // Buffer now contains "Hello World."
The routine makes no checks if dest is large enough.
char * strchr( const char * str, int c)
Searches for a character in a string.
str - Search this string c - Look for this character
A pointer to the first occurrence of c in str or NULL if c is not found in str.
char buffer[64]; strcpy (buffer, "Hello "); // This returns a pointer to the first l in buffer. strchr (buffer, 'l'); // This returns NULL strchr (buffer, 'x');
int strcmp( const char * str1, const char * str2)
Calculate str1 - str2.
str1, str2 - Strings to compare
The difference of the strings. The difference is 0, if both are equal, < 0 if str1 < str2 and > 0 if str1 > str2. Note that it may be greater then 1 or less than -1.
This function is not part of a library and may thus be called any time.
int strcoll( const char * str1, const char * str2)
Calculate str1 - str2. The operation is based on strings interpreted as appropriate for the program's current locale for category LC_COLLATE.
str1, str2 - Strings to compare
The difference of the strings. The difference is 0, if both are equal, < 0 if str1 < str2 and > 0 if str1 > str2. Note that it may be greater then 1 or less than -1.
stdc.library only implements "C" locale so strcoll() is equivalent to strcmp()
char * strcpy( char * dest, const char * src)
Copy a string. Works like an assignment "dest=src;".
dest - The string is copied into this variable. Make sure it is
large enough.
src - This is the new contents of dest.
dest.
No check is made that dest is large enough for src.
size_t strcspn( const char * str, const char * reject)
Calculates the length of the initial segment of str which consists entirely of characters not in reject.
str - The string to check. reject - Characters which must not be in str.
Length of the initial segment of str which doesn't contain any characters from reject.
char buffer[64]; strcpy (buffer, "Hello "); // Returns 5 strcspn (buffer, " "); // Returns 0 strcspn (buffer, "H");
char * strdup( const char * orig)
Create a copy of a string. The copy can be freed with free() or will be freed when the program ends.
str1 - Strings to duplicate
A copy of the string which can be freed with free().
char * strerror( int n)
Returns a readable string for an error number in errno.
n - The contents of errno or a #define from errno.h
A string describing the error.
This functions only handles the error codes needed by C99 and the ones used in stdc.library. This function is aliased as strerror() in libstdc.a Other libraries may override this function by providing this function also in their libxxx.a file. They can internally call __stdc_strerror to get the strings for the errors handled by this function.
size_t strftime(
char *s,
size_t maxsize,
const char *format,
const struct tm *timeptr)
Converts the time information in the struct tm pointed to by 'timeptr' into a formatted string according to the 'format' specification. The resulting string is placed in the buffer pointed to by 's', which can contain up to 'maxsize' characters, including the terminating null.
s - Pointer to the destination character buffer.
maxsize - Maximum number of characters to store in the destination,
including the null terminator.
format - Format control string containing ordinary characters and
conversion specifiers, similar to ANSI strftime().
timeptr - Pointer to a struct tm containing the time values to format.
The number of characters written to the destination buffer, excluding the terminating null character. Returns 0 if an error occurs (e.g., invalid arguments or formatting failure).
struct tm now = { .tm_year = 124, .tm_mon = 6, .tm_mday = 7, .tm_wday = 0,
.tm_hour = 15, .tm_min = 30, .tm_sec = 45 };
char buf[64];
strftime(buf, sizeof(buf), "%A, %B %d, %Y %H:%M:%S %p", &now);
// Example output: "Sunday, July 07, 2024 15:30:45 PM"
Supports a subset of ANSI C strftime() specifiers: %a %A - abbreviated and full weekday names %b %B - abbreviated and full month names %p - AM/PM indicator %d %m %y %Y %H %I %M %S - numeric date/time fields %n %t %% - special characters Composite formats (%c, %x, %X, etc.) and locale-specific date/time formats are not yet implemented.
- Does not support all strftime() specifiers. - Does not use the userï¿?s actual locale settings.
size_t strlcat( char *dst, const char *src, size_t siz)
size_t strlcpy( char *dst, const char *src, size_t siz)
size_t strlen( const char * ptr)
Calculate the length of a string (without the terminating 0 byte).
ptr - The string to get its length for
The length of the string.
char * strlwr( char * str)
Converts a string to all lower case characters. Modifies the given string.
str - The string to convert.
The same string buffer is passed back with all characters converted.
int strncasecmp( const char * str1, const char * str2, size_t n)
Calculate str1 - str2 ignoring case. Up to n characters are taken into account.
str1, str2 - Strings to compare
The difference of the strings. The difference is 0, if both are equal, < 0 if str1 < str2 and > 0 if str1 > str2. Note that it may be greater then 1 or less than -1.
This function is not part of a library and may thus be called any time.
char * strncat( char * dest, const char * src, size_t n)
Concatenates two strings. If src is longer than n characters, then only the first n characters are copied.
dest - src is appended to this string. Make sure that there
is enough room for src.
src - This string is appended to dest
n - No more than this number of characters of src are copied.
dest.
char buffer[64]; strcpy (buffer, "Hello "); strncat (buffer, "World.!!", 6); // Buffer now contains "Hello World."
The routine makes no checks if dest is large enough. The size of dest must be at least strlen(dest)+n+1.
int strncmp( const char * str1, const char * str2, size_t n)
Calculate str1 - str2 for up to n chars or up to the first 0 byte.
str1, str2 - Strings to compare
The difference of the strings. The difference is 0, if both are equal, < 0 if str1 < str2 and > 0 if str1 > str2. Note that it may be greater then 1 or less than -1.
This function is not part of a library and may thus be called any time.
char * strncpy( char * dest, const char * src, size_t n)
Copy a string. Works like an assignment "dest=src;". At most n characters are copied.
dest - The string is copied into this variable. Make sure it is
large enough.
src - This is the new contents of dest.
n - How many characters to copy at most. If the string src is
smaller than that, only strlen(str)+1 bytes are copied.
dest.
No check is made that dest is large enough for src.
char * strndup( const char *s, size_t n)
Create a copy of a string. The copy can be freed with free() or will be freed when then program ends. The copy will be at most n character long, excluding the trailing \000
s - String to duplicate n - Maximum length
A copy of the string which can be freed with free().
size_t strnlen( const char * ptr, size_t n)
Calculate the length of a string (without the terminating 0 byte).
ptr - The string to get its length for n - The max length
The length of the string.
char * strpbrk( const char * str, const char * accept)
Locate the first occurrence of any character in accept in str.
str - Search this string accept - Look for these characters
A pointer to the first occurrence of any character in accept in str or NULL if no character of accept is not found in str.
char buffer[64]; strcpy (buffer, "Hello "); // This returns a pointer to the first l in buffer. strpbrk (buffer, "lo"); // This returns NULL strpbrk (buffer, "xyz");
char * strrchr( const char * str, int c)
Searches for the last character c in a string.
str - Search this string c - Look for this character
A pointer to the first occurrence of c in str or NULL if c is not found in str.
char buffer[64]; strcpy (buffer, "Hello "); // This returns a pointer to the second l in buffer. strrchr (buffer, 'l'); // This returns NULL strrchr (buffer, 'x');
char * strrev( char * s)
Reverse a string (rotate it about its midpoint)
s - The string to be reversed
The original string pointer
char buffer[64]; strcpy (buffer, "Hello); strrev(buffer); // buffer now contains "olleH"
SAS C specific
char * strsep( char ** strptr, const char * sep)
Separates a string by the characters in sep. Unlike strtok(), strsep() does not merge adjacent delimiters: an empty field (two delimiters in a row, or a leading delimiter) yields an empty string. This makes it suitable for parsing records whose fields may be empty.
strptr - Address of the string to scan. Updated to point just after
the delimiter that terminated the returned token, or set to
NULL once the end of the string has been reached.
sep - Characters which separate "words" in the string.
A pointer to the (possibly empty) token, or NULL when *strptr is already NULL (no more tokens).
char buffer[64]; char *bufptr, *word; strcpy (buffer, "a,bb,,ccc"); bufptr = buffer; word = strsep (&bufptr, ","); // Returns "a" word = strsep (&bufptr, ","); // Returns "bb" word = strsep (&bufptr, ","); // Returns "" (empty field!) word = strsep (&bufptr, ","); // Returns "ccc" word = strsep (&bufptr, ","); // Returns NULL
The function changes the scanned string (it writes a NUL over the delimiter that terminates each token).
size_t strspn( const char * str, const char * accept)
Calculates the length of the initial segment of str which consists entirely of characters in accept.
str - The string to check. accept - Characters which have to be in str.
Length of the initial segment of str which contains only characters from accept.
char buffer[64]; strcpy (buffer, "Hello "); // Returns 5 strspn (buffer, "Helo"); // Returns 0 strspn (buffer, "xyz");
char * strstr( const char * str, const char * search)
Searches for a string in a string.
str - Search this string search - Look for this string
A pointer to the first occurrence of search in str or NULL if search is not found in str.
char buffer[64]; strcpy (buffer, "Hello "); // This returns a pointer to the first l in buffer. strstr (buffer, "llo "); // This returns NULL strstr (buffer, "llox");
double strtod( const char * str, char ** endptr)
Convert the initial part of a string to a double.
str - The string to convert. Leading whitespace is skipped. The
number may be prefixed by '+' or '-', and is either a
decimal number with an optional 'e' exponent, a hexadecimal
number introduced by "0x" with an optional 'p' binary
exponent, "inf", "infinity" or "nan" with an optional
parenthesised character sequence, all case-insensitive.
endptr - If this is non-NULL, the address of the first character
after the number is stored here.
The value of the string, correctly rounded to the nearest double, ties to even. If no conversion can be performed, *endptr is set to str and 0 is returned. If the value overflows, HUGE_VAL with the sign of the number is returned and errno is set to ERANGE. If the value underflows, 0 or a denormal with the sign of the number is returned and errno is set to ERANGE.
The decimal point is the one in __stdc_char_decimalpoint.
float strtof( const char * str, char ** endptr)
Convert a floating-point number from an ASCII decimal representation into a double-precision format.
str - The string which should be converted. Leading
whitespace are ignored.
endptr - If this is non-NULL, then the address of the first
character after the number in the string is stored
here.
The float value of the string. The first character after the number is returned in *endptr, if endptr is non-NULL. If no digits can be converted, *endptr contains str (if non-NULL) and 0 is returned.
intmax_t strtoimax( const char * nptr, char ** endptr, int base)
Convert a string of digits into an integer according to the given base. This function is like strtol() except the fact, that it returns a value of type intmax_t.
str - The string which should be converted.
endptr - If this is non-NULL, then the address of the first
character after the number in the string is stored
here.
base - The base for the number.
The value of the string. The first character after the number is returned in *endptr, if endptr is non-NULL. If no digits can be converted, *endptr contains str (if non-NULL) and 0 is returned.
errno is not set as required by C99 standard
char * strtok( char * str, const char * sep)
Separates a string by the characters in sep.
str - The string to check or NULL if the next word in
the last string is to be searched.
sep - Characters which separate "words" in str.
The first word in str or the next one if str is NULL.
char buffer[64]; strcpy (buffer, "Hello, this is a test."); // Init. Returns "Hello" strtok (str, " \t,."); // Next word. Returns "this" strtok (NULL, " \t,."); // Next word. Returns "is" strtok (NULL, " \t"); // Next word. Returns "a" strtok (NULL, " \t"); // Next word. Returns "test." strtok (NULL, " \t"); // Next word. Returns NULL. strtok (NULL, " \t");
The function changes str !
long strtol( const char * str, char ** endptr, int base)
Convert a string of digits into an integer according to the given base.
str - The string which should be converted. Leading
whitespace are ignored. The number may be prefixed
by a '+' or '-'. If base is above 10, then the
alphabetic characters from 'A' are used to specify
digits above 9 (ie. 'A' or 'a' is 10, 'B' or 'b' is
11 and so on until 'Z' or 'z' is 35).
endptr - If this is non-NULL, then the address of the first
character after the number in the string is stored
here.
base - The base for the number. May be 0 or between 2 and 36,
including both. 0 means to autodetect the base. strtoul()
selects the base by inspecting the first characters
of the string. If they are "0x", then base 16 is
assumed. If they are "0", then base 8 is assumed. Any
other digit will assume base 10. This is like in C.
If you give base 16, then an optional "0x" may
precede the number in the string.
The value of the string. The first character after the number is returned in *endptr, if endptr is non-NULL. If no digits can be converted, *endptr contains str (if non-NULL) and 0 is returned.
// returns 1, ptr points to the 0-Byte
strol (" \t +0x1", &ptr, 0);
// Returns 15. ptr points to the a
strol ("017a", &ptr, 0);
// Returns 215 (5*36 + 35)
strol ("5z", &ptr, 36);
long double strtold( const char * str, char ** endptr)
Convert a string of digits into a long double.
str - The string which should be converted. Leading
whitespace are ignored. The number may be prefixed
by a '+' or '-'. An 'e' or 'E' introduces the exponent.
Comma is only allowed before exponent.
endptr - If this is non-NULL, then the address of the first
character after the number in the string is stored
here.
The value of the string. The first character after the number is returned in *endptr, if endptr is non-NULL. If no digits can be converted, *endptr contains str (if non-NULL) and 0 is returned.
We make the compiler do an internal conversion from a double to a long double. Because of this we lose a some precision, but for now it works.
NAN is not handled at the moment
long long strtoll( const char * restrict str, char ** restrict endptr, int base)
Convert a string of digits into an integer according to the given base.
str - The string which should be converted. Leading
whitespace are ignored. The number may be prefixed
by a '+' or '-'. If base is above 10, then the
alphabetic characters from 'A' are used to specify
digits above 9 (ie. 'A' or 'a' is 10, 'B' or 'b' is
11 and so on until 'Z' or 'z' is 35).
endptr - If this is non-NULL, then the address of the first
character after the number in the string is stored
here.
base - The base for the number. May be 0 or between 2 and 36,
including both. 0 means to autodetect the base. strtoul()
selects the base by inspecting the first characters
of the string. If they are "0x", then base 16 is
assumed. If they are "0", then base 8 is assumed. Any
other digit will assume base 10. This is like in C.
If you give base 16, then an optional "0x" may
precede the number in the string.
The value of the string. The first character after the number is returned in *endptr, if endptr is non-NULL. If no digits can be converted, *endptr contains str (if non-NULL) and 0 is returned.
// returns 1, ptr points to the 0-Byte
strtoll (" \t +0x1", &ptr, 0);
// Returns 15. ptr points to the a
strtoll ("017a", &ptr, 0);
// Returns 215 (5*36 + 35)
strtoll ("5z", &ptr, 36);
unsigned long strtoul( const char * str, char ** endptr, int base)
Convert a string of digits into an integer according to the given base.
str - The string which should be converted. Leading
whitespace are ignored. The number may be prefixed
by a '+' or '-'. If base is above 10, then the
alphabetic characters from 'A' are used to specify
digits above 9 (ie. 'A' or 'a' is 10, 'B' or 'b' is
11 and so on until 'Z' or 'z' is 35).
endptr - If this is non-NULL, then the address of the first
character after the number in the string is stored
here.
base - The base for the number. May be 0 or between 2 and 36,
including both. 0 means to autodetect the base. strtoul()
selects the base by inspecting the first characters
of the string. If they are "0x", then base 16 is
assumed. If they are "0", then base 8 is assumed. Any
other digit will assume base 10. This is like in C.
If you give base 16, then an optional "0x" may
precede the number in the string.
The value of the string. The first character after the number is returned in *endptr, if endptr is non-NULL. If no digits can be converted, *endptr contains str (if non-NULL) and 0 is returned.
// Returns 1, ptr points to the 0-Byte
strtoul (" \t +0x1", &ptr, 0);
// Returns 15. ptr points to the a
strtoul ("017a", &ptr, 0);
// Returns 215 (5*36 + 35)
strtoul ("5z", &ptr, 36);
unsigned long long strtoull( const char * restrict str, char ** restrict endptr, int base)
Convert a string of digits into an integer according to the given base.
str - The string which should be converted. Leading
whitespace are ignored. The number may be prefixed
by a '+' or '-'. If base is above 10, then the
alphabetic characters from 'A' are used to specify
digits above 9 (ie. 'A' or 'a' is 10, 'B' or 'b' is
11 and so on until 'Z' or 'z' is 35).
endptr - If this is non-NULL, then the address of the first
character after the number in the string is stored
here.
base - The base for the number. May be 0 or between 2 and 36,
including both. 0 means to autodetect the base. strtoull()
selects the base by inspecting the first characters
of the string. If they are "0x", then base 16 is
assumed. If they are "0", then base 8 is assumed. Any
other digit will assume base 10. This is like in C.
If you give base 16, then an optional "0x" may
precede the number in the string.
The value of the string. The first character after the number is returned in *endptr, if endptr is non-NULL. If no digits can be converted, *endptr contains str (if non-NULL) and 0 is returned.
// Returns 1, ptr points to the 0-Byte
strtoull (" \t +0x1", &ptr, 0);
// Returns 15. ptr points to the a
strtoull ("017a", &ptr, 0);
// Returns 215 (5*36 + 35)
strtoull ("5z", &ptr, 36);
uintmax_t strtoumax( const char * nptr, char ** endptr, int base)
Convert a string of digits into an integer according to the given base. This function is like strtoul() except the fact, that it returns a value of type uintmax_t.
str - The string which should be converted.
endptr - If this is non-NULL, then the address of the first
character after the number in the string is stored
here.
base - The base for the number.
The value of the string. The first character after the number is returned in *endptr, if endptr is non-NULL. If no digits can be converted, *endptr contains str (if non-NULL) and 0 is returned.
errno is not set as required by C99 standard
char * strupr( char * str)
Converts a string to all upper case characters. Modifies the given string.
str - The string to convert.
The same string buffer is passed back with all characters converted.
size_t strxfrm( char * restrict dst, const char * restrict src, size_t n)
The strxfrm() function transforms a null-terminated string pointed to by src according to the current locale collation if any, then copies the transformed string into dst. Not more than n characters are copied into dst, including the terminating null character added. If n is set to 0 (it helps to determine an actual size needed for transformation), dst is permitted to be a NULL pointer. Comparing two strings using strcmp() after strxfrm() is equal to compar- ing two original strings with strcoll().
dst - the destination string's buffer src - the source string n - the size of the dst buffer.
Upon successful completion, strxfrm() returns the length of the trans- formed string not including the terminating null character. If this value is n or more, the contents of dst are indeterminate.
stdc.library only support "C" locale so strxfrm is equivalent to strncpy.
int swprintf( wchar_t * restrict str, size_t maxsize, const wchar_t * restrict format, ...)
Format a variable list of arguments according to a wide-character format string and store the result in the specified buffer.
s - Destination buffer for the formatted wide-character string.
maxsize - Maximum number of wide characters to store in the buffer,
including the null terminator.
format - A wide-character printf() format string.
... - Additional arguments matching the format specifiers.
The number of wide characters written to the buffer, excluding the terminating null character. A negative value is returned if an error occurs.
The result is always null-terminated unless maxsize is zero.
int swscanf( const wchar_t * restrict ws, const wchar_t * restrict format, ...)
Reads formatted wide-character input from the given wide-character string and stores the results into the provided argument locations.
ws - Read from this wide-character string format - How to convert the input into the arguments ... - Write the result in these arguments
The number of converted arguments.
int system( const char *string)
Execute a command string. If string is NULL then 1 will be returned.
string - command to execute or NULL
Return value of command executed. If value < 0 errno indicates error. 1 is return if string is NULL.
The system() version of stdcio.library just passes the command to SystemTags() dos.library call.
double tan( double x)
Computes the tangent of x (x in radians).
x - input angle in radians.
Returns tan(x).
double val = tan(3.14159 / 4); // approximately 1.0
Uses range reduction and polynomial approximation internally. Returns NaN and sets errno to EDOM if x is an odd multiple of p/2.
None known.
float tanf( float x)
Computes the tangent of x (in radians).
x - angle in radians.
Tangent of x.
float r = tanf(0.785398f); // ˜ 1.0 (p/4 radians)
tan(x) = sin(x) / cos(x), undefined at (p/2 + kp)
Near p/2 and odd multiples, large errors or infinities may result.
double tanh( double x)
Computes the hyperbolic tangent of x.
x - input value.
Returns tanh(x) = sinh(x) / cosh(x).
double val = tanh(1.0);
Uses exponentials internally for calculation.
None known.
float tanhf( float x)
Computes hyperbolic tangent of x.
x - input float
Returns tanh(x).
float r = tanhf(1.0f); // ˜ 0.761594
Approaches ±1 for large |x|.
None known.
long double tanhl( long double x)
Computes the hyperbolic tangent of x.
x - input value.
Returns tanh(x) = sinh(x) / cosh(x).
double val = tanh(1.0);
Uses exponentials internally for calculation.
None known.
long double tanl( long double x)
Computes the tangent of x.
x - angle in radians.
Returns tan(x), or may overflow near odd multiples of p/2.
long double r = tanl(0.0L); // returns 0.0L
Long double variant of tan().
None known.
double tgamma( double x)
Computes the gamma function G(x).
x - input value.
Returns the gamma function value. Domain errors set errno to EDOM.
double val = tgamma(5.0); // returns 24.0 (4!)
Extends the factorial function to real numbers.
None known.
long double tgammal( long double x)
Computes the gamma function G(x).
x - input value.
Returns G(x), or 8 for poles.
long double r = tgammal(5.0L); // returns 24.0L
Undefined for negative integers.
None known.
time_t time( time_t * tloc)
time() returns the time since 00:00:00 GMT, January 1, 1970, measured in seconds.
tloc - If this pointer is non-NULL, then the time is written into
this variable as well.
The number of seconds.
time_t tt1, tt2; // tt1 and tt2 are the same tt1 = time (&tt2); // This is valid, too tt1 = time (NULL);
This function must not be used in a shared library or in a threaded application.
int timespec_get( struct timespec *ts, int base)
Store the current calendar time, based on the given time base, into *ts. The only base required by C11 is TIME_UTC, for which the time is the number of seconds and nanoseconds since the epoch (UTC).
ts - the timespec to fill in. base - the time base; TIME_UTC is supported.
base on success, or 0 if base is not supported or the time could not be obtained.
FILE * tmpfile( void)
The tmpfile() function creates a temporary file that is different from any other existing file and that will automatically be removed when it is closed or at program termination. The file is opened for update with "wb+" mode.
Pointer to the stream that was created. On error NULL is returned.
#include <errno.h>
#include <stdio.h>
#include <string.h>
main()
{
FILE * fp;
fp = tmpfile();
if ( fp == NULL)
{
perror(strerror(errno));
return;
}
fprintf(fp, "do a bit of writing to the temp file");
}
This function uses tmpnam(NULL) to get the file name.
char *tmpnam( char *s)
The tmpnam function generates a string that is a valid file name and that is not the same as the name of an existing file. The function is potentially capable of generating TMP_MAX different strings, but any or all of them may already be in use by existing files and thus not be suitable return values.
Pointer to a string of at least L_tmpnam characters.
The resulting file name is returned in the input string pointer or a pointer to an internal buffer if NULL was passed to the function. If file name generation failed a NULL is returned.
wint_t towctrans( wint_t wc, wctrans_t desc)
Transforms a wide character according to the mapping identified by the wctrans_t descriptor.
wc - the wide character to transform. desc - transformation descriptor from `wctrans()`.
The transformed wide character, or the original character if the descriptor is invalid.
wctrans_t t = wctrans("tolower");
wint_t lc = towctrans(L'Z', t); // 'z'
Behavior is undefined if `desc` was not obtained from `wctrans()`.
wint_t towlower( wint_t wc)
Converts an uppercase wide character to its lowercase equivalent.
wc - a wide character code point.
The lowercase equivalent of the input character if applicable; otherwise returns the character unchanged.
wint_t c = towlower(L'Ä'); // returns L'ä'
Supports all characters in the ASCII and Latin-1 Supplement ranges. For example, `L'É'` ? `L'é`.
wint_t towupper( wint_t wc)
Converts a lowercase wide character to its uppercase equivalent.
wc - a wide character code point.
The uppercase equivalent of the input character if applicable; otherwise returns the character unchanged.
wint_t c = towupper(L'è'); // returns L'È'
Supports all characters in the ASCII and Latin-1 Supplement ranges. For example, `L'ö'` ? `L'Ö'`.
Characters outside U+00FF are returned unchanged.
double trunc( double x)
Truncates fractional part of x toward zero.
x - input double
Integral part of x without fraction.
double r = trunc(3.9); // 3.0 double r2 = trunc(-3.9); // -3.0
Differs from floor() by rounding toward zero.
None known.
float truncf( float x)
Truncates fractional part of x toward zero.
x - input float
Integral part with fraction discarded.
float r = truncf(2.9f); // 2.0f float r2 = truncf(-2.9f); // -2.0f
Differs from floorf() by rounding toward zero.
None known.
long double truncl( long double x)
Truncates fractional part of x (long double) toward zero.
x - input long double
Integral part without fraction.
long double r = truncl(3.9L); // 3.0L long double r2 = truncl(-3.9L); // -3.0L
Same behavior as trunc() for long double.
None known.
int ungetc( int c, FILE * stream)
Puch the character c character back into the stream.
c - Put this character back into the stream. The next read will
return this character. If you push back more than one
character, then they will be returned in reverse order.
The function guarantees that one character can be
pushed back but no more. It is possible to push the EOF
character back into the stream.
stream - Read from this stream
c or EOF on error.
wint_t ungetwc( wint_t wc, FILE * stream)
Push a wide character back onto the input stream. The next read operation will return this character.
wc - Wide character to push back (can be WEOF). stream - Pointer to the stream.
Returns the wide character pushed back, or WEOF on error.
Only one wide character can be pushed back at a time. Subsequent calls without reading will overwrite the previous pushed-back character.
int vasprintf( char **restrict str, const char *restrict format, va_list args)
Analog of vsprintf, except that sotrage is allocated for a string large enough to hold the output including the terminating null byte
str - Where to store the pointer for the allocated string. format - A printf() format string. args - A list of arguments for the format string.
The number of characters written, or EOF on error.
int vfprintf( FILE * restrict stream, const char * restrict format, va_list args)
Format a list of arguments and print them on the specified stream.
stream - A stream on which one can write format - A printf() format string. args - A list of arguments for the format string.
The number of characters written.
int vfscanf( FILE * stream, const char * format, va_list args)
Read the scream, scan it as the format specified and write the result of the conversion into the specified arguments.
stream - A stream to read from format - A scanf() format string. args - A list of arguments for the results.
The number of converted arguments.
int vfwprintf( struct __sFILE * restrict stream, const wchar_t * restrict format, va_list arg)
Format a va_list of arguments according to a wide-character format string and write the output to the given stream.
stream - Output stream. format - A wide-character printf() format string. arg - A va_list containing the arguments for the format string.
The number of wide characters written to the stream, or a negative value if an error occurs.
This is the va_list version of fwprintf(), similar to vprintf().
int vfwscanf( FILE * restrict stream, const wchar_t * restrict format, va_list arg)
Reads formatted wide-character input from the given file stream, parsing according to the given format string, and stores the results into the locations described by the argument list.
stream - Read from this wide-character file stream format - How to convert the input into the arguments arg - List of argument pointers to receive results
The number of converted arguments.
int vprintf( const char * format, va_list args)
Format a list of arguments and print them on the standard output.
format - A printf() format string. args - A list of arguments for the format string.
The number of characters written.
int vscanf( const char * format, va_list args)
Scan the standard input and convert it into the arguments as specified by format.
format - A scanf() format string. args - A list of arguments for the results
The number of converted parameters.
int vsnprintf( char * str, size_t n, const char * format, va_list args)
Format a list of arguments and put them into the string str. The function makes sure that no more than n characters (including the terminal 0 byte) are written into str. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.
str - The formatted result is stored here n - The size of str format - A printf() format string. args - A list of arguments for the format string.
Function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.
int vsprintf( char * str, const char * format, va_list args)
Format a list of arguments and put them into the string str.
str - The formatted result is stored here format - A printf() format string. args - A list of arguments for the format string.
The number of characters written.
No check is made that str is large enough to contain the result.
int vsscanf( const char *str, const char *format, va_list args)
Scan a string and convert it into the arguments as specified by format.
str - Scan this string format - A scanf() format string. args - A list of arguments for the results
The number of arguments converted.
int vswprintf( wchar_t * restrict str, size_t maxsize, const wchar_t * restrict format, va_list args)
Format a va_list of arguments according to a wide-character format string and store the result in the specified buffer.
s - Destination buffer for the formatted wide-character string.
maxsize - Maximum number of wide characters to store in the buffer,
including the null terminator.
format - A wide-character printf() format string.
arg - A va_list containing the arguments for the format string.
The number of wide characters written to the buffer, excluding the terminating null character. A negative value is returned if an error occurs.
The result is always null-terminated unless maxsize is zero.
int vswscanf( const wchar_t * restrict ws, const wchar_t * restrict format, va_list arg)
Reads formatted wide-character input from the given wide-character string, parsing according to the given format string, and stores the results into the locations described by the argument list.
ws - Read from this wide-character string format - How to convert the input into the arguments arg - List of argument pointers to receive results
The number of converted arguments.
int vwprintf( const wchar_t * restrict format, va_list args)
Format a va_list of arguments according to a wide-character format string and print the output to the standard output stream.
format - A wide-character printf() format string. arg - A va_list containing the arguments for the format string.
The number of wide characters written to the standard output, or a negative value if an error occurs.
Equivalent to vfwprintf() with stdout as the output stream.
int vwscanf( const wchar_t * restrict format, va_list arg)
Reads formatted wide-character input from the standard input stream and stores the results into the locations described by the argument list.
format - How to convert the input into the arguments arg - List of argument pointers to receive results
The number of converted arguments.
e_t wcrtomb( char * restrict s, wchar_t wc, mbstate_t * restrict ps)
Converts a single wide character (wchar_t) to its multibyte representation and stores it in the output buffer 's'.
s - Pointer to the destination buffer to receive the multibyte sequence.
If NULL, the function returns the length of the encoding sequence used
to reset the shift state (which is 1 for UTF-8 or 0 for state-independent encodings).
wc - The wide character to convert.
ps - Pointer to an mbstate_t object that keeps conversion state between calls.
May be NULL for stateless encodings like UTF-8.
Returns the number of bytes written to 's' if successful. If 'wc' is the null wide character, a single null byte is written and 1 is returned. If the conversion fails (invalid code point or sequence), (size_t)-1 is returned and errno is set to EILSEQ.
wchar_t wc = L'ü'; char buf[MB_CUR_MAX]; size_t len = wcrtomb(buf, wc, NULL);
This implementation assumes a stateless encoding (UTF-8). If 'ps' is NULL, an internal static conversion state is not maintained — behavior is stateless. Surrogate pairs and values above U+10FFFF are treated as invalid.
Does not support stateful encodings. No locale-specific behavior is implemented — assumes UTF-8 or ASCII compatible only.
wchar_t *wcscat( wchar_t *wcdst, const wchar_t *wcsrc)
Appends a wide string, onto another wide string.
wcdst - the wide string that will have the text appended to it. wcsrc - the wide string to append.
A pointer to the resulting wide string.
ar_t *wcschr( const wchar_t* s, wchar_t c)
Find the first occurrence of c in the wide string s.
s - source wide string. c - wide character to locate.
Returns a pointer to the located wide character c. If c does not occur in the wide string s a null pointer is returned.
int wcscmp( const wchar_t *wcstra, const wchar_t *wcstrb)
Lexicographically compares two null-terminated wide strings.
wcstra - wide string to compare. wcstrb - wide string to compare.
If wcstra appears before wcstrb lexographically, then -1 is returned. If wcstrb appears before wcstra lexographically, then 1 is returned. If the strings are equal, 0 is returned.
nt wcscoll( const wchar_t *ws1, const wchar_t *ws2)
Compares the two wide-character strings 'ws1' and 'ws2' according to the current locale's collation order.
ws1 -- first wide-character string ws2 -- second wide-character string
Returns < 0 if ws1 < ws2, 0 if ws1 == ws2, > 0 if ws1 > ws2.
This implementation ignores locale collation and performs a binary comparison using wcscmp().
wchar_t *wcscpy( wchar_t *wcdst, const wchar_t *wcsrc)
Copies a wide string, to another wide string.
wcdst - the wide string that will be copied to. wcsrc - the wide string to copy.
A pointer to the resulting wide string.
e_t wcscspn( const wchar_t *s1, const wchar_t *s2)
Scans s1 for the first occurrence of any of the wide characters that are part of s2, returning the number of wide characters of s1 read before this first occurrence..
s1 - wide string to be scanned. s2 - wide string containing the characters to match.
Returns the length of the segment.
size_t wcsftime( wchar_t *s, size_t maxsize, const wchar_t *format, const struct tm *timeptr)
Format time/date according to locale-dependent format. This is the wide character version of strftime().
s - buffer to store the formatted string maxsize - maximum number of wide characters to store format - format string with conversion specifiers timeptr - pointer to tm structure containing time/date
Number of wide characters stored in s (excluding null terminator), or 0 if the result would not fit in maxsize characters.
wchar_t buffer[100]; struct tm *timeinfo; time_t rawtime; time(&rawtime); timeinfo = localtime(&rawtime); wcsftime(buffer, 100, L"Today is %A, %B %d, %Y", timeinfo);
Function does not take localization into account at the moment. Conversion specifiers are the same as strftime().
size_t wcslen( const wchar_t *wcstr)
Returns the length of a wide string.
wcstr - wide string to tally.
The number of non-null wide characters, in the wide string.
ar_t *wcsncat( wchar_t *dest, const wchar_t *src, size_t n)
Appends at most n wide characters from the wide string src to the end of the wide string dest, and null-terminates the result.
dest - Destination wide string buffer. Must be large enough to hold the
resulting concatenated string including the terminating null.
src - Source wide string to append.
n - Maximum number of wide characters to append from src.
Returns a pointer to the destination string dest.
wchar_t buf[20] = L"Hello, "; wcsncat(buf, L"World!", 3); // buf now contains L"Hello, Wor"
Appends characters up to n or until a null wide character in src is encountered, whichever comes first. The resulting string in dest is always null-terminated. Behavior is undefined if dest and src overlap.
int wcsncmp( const wchar_t *wcstra, const wchar_t *wcstrb, size_t cnt)
Lexicographically compares two null-terminated wide strings, upto the specified length
wcstra - wide string to compare. wcstrb - wide string to compare. cnt - maximum number of wide characters to compare.
wchar_t *wcsncpy( wchar_t *wcdst, const wchar_t *wcsrc, size_t cnt)
Copies upto the specified length of wide characters from a wide string, to another wide string.
wcdst - the wide string that will be copied to. wcsrc - the wide string to copy. cnt - maximum number of wide characters to copy.
A pointer to the resulting wide string.
ar_t *wcspbrk( const wchar_t *s, const wchar_t *accept)
Scans the wide string s for the first occurrence of any character in the wide string accept.
s - Wide string to scan. accept - Wide string containing characters to match.
Returns a pointer to the first occurrence in s of any character from accept, or NULL if no such character is found.
ar_t *wcsrchr( const wchar_t *s, wchar_t c)
Locates the last occurrence of the wide character c in the wide string s.
s - Wide string to search. c - Wide character to locate.
Returns a pointer to the last occurrence of c in s, or NULL if c is not found. If c is the null character, returns a pointer to the null terminator.
size_t wcsrtombs( char * restrict dst, const wchar_t ** restrict src, size_t len, mbstate_t * restrict ps)
Converts a null-terminated wide character string pointed to by *src into a corresponding multibyte character string. The conversion uses the current locale (UTF-8 assumed here) and updates the src pointer to point past the last converted wide character.
dst - Pointer to destination multibyte buffer (may be NULL).
src - Address of the wide character string pointer. The pointer is updated
during conversion. If dst is NULL, the function returns the number
of bytes that would result from the conversion.
len - Maximum number of bytes to write.
ps - Conversion state object (ignored in this implementation).
Returns the number of bytes written or needed. Returns (size_t)-1 on conversion error and sets errno to EILSEQ.
This implementation assumes stateless UTF-8 encoding and does not currently use mbstate_t. It wraps around wcrtomb().
e_t wcsspn( const wchar_t *s1, const wchar_t *s2)
Calculates the length of the initial segment of s1 which consists entirely of wide characters in s2.
s1 - wide string to be scanned. s2 - wide string containing the characters to match.
Length of the initial segment of s1 which contains only wide characters from s2.
ar_t *wcsstr( const wchar_t *s1, const wchar_t *s2)
Locates the first occurrence in the wide string pointed to by s1 of the sequence of wide characters (excluding the terminating null wide character) in the wide string pointed to by s2.
s1 - wide string to be scanned. s2 - wide string containing the sequence of characters to match.
Returns a pointer to the first occurrence in s1 of the entire sequence of characters specified in s2, or a null pointer if the sequence is not present in s1.
ble wcstod( const wchar_t *nptr, wchar_t **endptr)
Converts the initial portion of the wide string nptr to a double-precision floating-point number. Conversion stops at the first invalid character.
nptr - Wide string to convert.
endptr - If not NULL, set to point to the character after the last used
in conversion.
Returns the converted double value. Returns 0.0 if no conversion could be performed. On overflow, returns HUGE_VAL and sets errno to ERANGE.
wchar_t *end; double val = wcstod(L"3.14159xyz", &end); // val == 3.14159, *end == L'x'
Recognizes optional whitespace, optional sign, decimal and exponential notation, and special values such as "inf" and "nan".
at wcstof( const wchar_t *nptr, wchar_t **endptr)
Converts the initial portion of the wide string nptr to a single-precision floating-point number. Stops at the first invalid character.
nptr - Wide string to convert. endptr - If not NULL, updated to point after the last consumed character.
Returns the converted float value, or 0.0 if no conversion was possible. On overflow, returns HUGE_VALF and sets errno to ERANGE.
wchar_t *end; float val = wcstof(L"2.71828abc", &end); // val == 2.71828f, *end == L'a'
Supports whitespace, optional sign, decimal/exponential notation, and special values like "inf" and "nan".
intmax_t wcstoimax( const wchar_t * restrict nptr, wchar_t ** restrict endptr, int base)
Converts a wide-character string of digits into an integer of type intmax_t, according to the specified base. This function behaves like wcstol() but returns an intmax_t result.
nptr - Pointer to the wide-character string to convert.
endptr - If non-NULL, stores the address of the first character
after the number.
base - The base for conversion (e.g., 10 for decimal, 16 for hex).
Returns the converted value as an intmax_t. If no valid conversion could be performed, returns 0 and stores nptr in *endptr (if endptr is non-NULL).
wchar_t *str = L"12345"; wchar_t *end; intmax_t value = wcstoimax(str, &end, 10);
Does not set errno on overflow or underflow, contrary to the C99 standard. Behavior is otherwise compatible with the standard library definition.
errno is not set on conversion errors or range overflows.
ar_t *wcstok( wchar_t * restrict s1, const wchar_t * restrict s2, wchar_t ** restrict ptr)
Split wide string into tokens.
s1 - wide string to truncate. s2 - wide string containing the delimiter wide characters. ptr - Pointer to a wchar_t pointer.
Returns a pointer to the first wide character of a token, or a null pointer if there is no token.
g wcstol( const wchar_t *nptr, wchar_t **endptr, int base)
Converts the initial part of wide string nptr to a long integer value, using the specified base (2 to 36) or auto-detect if base is 0.
nptr - Wide string to convert. endptr - If not NULL, set to character after last used in conversion. base - Numeric base for conversion (0, or 2 to 36).
Returns the converted long integer. On overflow, returns LONG_MAX or LONG_MIN and sets errno to ERANGE. Returns 0 if no conversion was done.
wchar_t *end; long val = wcstol(L"0x10abc", &end, 0); // val == 16, *end == L'a'
Skips optional whitespace and supports optional '+' or '-' sign. Base 0 auto-detects hexadecimal (0x), octal (0), or decimal.
g double wcstold( const wchar_t *nptr, wchar_t **endptr)
Converts the initial portion of the wide string nptr to a long double floating-point number. Stops at first invalid character.
nptr - Wide string input. endptr - If not NULL, set to the character after last converted character.
Returns converted long double value. Returns 0.0L if no conversion. On overflow, returns HUGE_VALL and sets errno to ERANGE.
wchar_t *end; long double val = wcstold(L"1.2345e10xyz", &end); // val == 1.2345e10L, *end == L'x'
Handles optional whitespace, sign, decimal and exponential notation, and special values "inf" and "nan".
g long wcstoll( const wchar_t *nptr, wchar_t **endptr, int base)
Converts the initial part of wide string nptr to a long long integer, respecting the base (2 to 36) or auto-detect if base is 0.
nptr - Wide string input. endptr - If not NULL, updated to point after last converted character. base - Numeric base for conversion.
Returns converted long long integer. On overflow, returns LLONG_MAX or LLONG_MIN and sets errno to ERANGE. Returns 0 if no conversion.
wchar_t *end; long long val = wcstoll(L"123456789LLxyz", &end, 10); // val == 123456789LL, *end == L'x'
Handles optional whitespace and sign. Base 0 auto-detects hex/octal/decimal.
size_t wcstombs( char * restrict dest, const wchar_t * restrict src, size_t n)
Converts a null-terminated wide character string (wchar_t*) into its corresponding multibyte string (char*), using the current locale's encoding. At most 'n' bytes are written into 'dest', not including the terminating null byte.
dest - Pointer to the destination buffer that receives the converted multibyte string.
If NULL, the function returns the number of bytes that would be written, not
including the null terminator.
src - Pointer to the null-terminated wide character string to convert.
n - Maximum number of bytes to write into 'dest'.
Returns the number of bytes stored in 'dest', excluding the terminating null byte. If a wide character cannot be converted to a valid multibyte sequence, the function returns (size_t)-1 and sets errno to EILSEQ. If 'dest' is NULL, the function returns the number of bytes that would be needed to encode the wide string, excluding the terminating null byte.
wchar_t wstr[] = L"Hello ??!";
char buffer[64];
size_t len = wcstombs(buffer, wstr, sizeof(buffer));
if (len != (size_t)-1) {
// buffer now contains UTF-8-encoded string
}
stdc.library currently only implements "C" or UTF-8 compatible locale behavior. The encoding is treated as stateless and locale-independent. The terminating null character (L'\0') is converted, but the function does not include it in the returned count.
Does not handle stateful encodings or locale-specific behavior. Buffer overflow is possible if 'n' is too small to hold even one multibyte character.
igned long wcstoul( const wchar_t *nptr, wchar_t **endptr, int base)
Converts the initial part of the wide string nptr to an unsigned long integer according to the specified base or auto-detect if base is 0.
nptr - Wide string input. endptr - If not NULL, set to character after last used in conversion. base - Numeric base (0 or 2 to 36).
Returns the converted unsigned long integer. On overflow, returns ULONG_MAX and sets errno to ERANGE. Returns 0 if no conversion.
wchar_t *end; unsigned long val = wcstoul(L"0755abc", &end, 0); // val == 493, *end == L'a'
Supports optional whitespace and optional plus sign. Base 0 auto-detects.
igned long long wcstoull( const wchar_t *nptr, wchar_t **endptr, int base)
Converts the initial part of wide string nptr to an unsigned long long integer according to the specified base or auto-detect if base is 0.
nptr - Wide string input. endptr - If not NULL, set to the character after last consumed character. base - Numeric base for conversion (0 or 2 to 36).
Returns converted unsigned long long integer. On overflow, returns ULLONG_MAX and sets errno to ERANGE. Returns 0 if no conversion.
wchar_t *end; unsigned long long val = wcstoull(L"18446744073709551615xyz", &end, 10); // val == 18446744073709551615ULL, *end == L'x'
Supports optional whitespace and plus sign. Base 0 auto-detects.
uintmax_t wcstoumax( const wchar_t *nptr, wchar_t **endptr, int base)
Converts a wide-character string of digits into an unsigned integer according to the given base. This function is similar to wcstoul(), but returns a value of type uintmax_t.
nptr - Pointer to the wide-character string to be converted.
endptr - If non-NULL, the address of the first character after the
number is stored here.
base - The numeric base for the conversion (e.g., 10 for decimal,
16 for hexadecimal).
The converted numeric value as a uintmax_t. If no valid digits are found, 0 is returned, and if endptr is non-NULL, it is set to nptr.
wchar_t *str = L"FF"; wchar_t *end; uintmax_t value = wcstoumax(str, &end, 16);
The function does not set errno on overflow or underflow, contrary to the requirements of the C99 standard.
errno is not set on range errors as required by the C99 standard.
size_t wcsxfrm( wchar_t *dest, const wchar_t *src, size_t n)
Transforms the wide-character string 'src' into a form suitable for comparison using wcscmp(), and stores it in 'dest'.
dest -- destination buffer to store the transformed string src -- source wide-character string n -- maximum number of characters to store in dest
Returns the length of the transformed string (as if no limit was applied), not counting the null terminator.
This naive implementation simply copies 'src' to 'dest' up to 'n' characters (including the null terminator if space permits). This implementation does not perform locale-specific transformations; it is equivalent to wcsncpy() + wcslen()
wctob( wint_t wc) FUNCTION The wctob() function attempts to convert a wide character to a single-byte character, according to the current locale's encoding. The conversion is only successful if the wide character maps to a single byte.
wc - A wide character (wint_t) to convert.
Returns the corresponding single-byte character (as an unsigned char) cast to int, or EOF if the character cannot be represented as a single-byte sequence.
int c = wctob(L'A'); // Might return 'A' if in ASCII-compatible locale.
This function only succeeds for wide characters that map directly to a single byte in the current locale encoding.
Fails for wide characters that require multibyte sequences (e.g., most non-ASCII characters in UTF-8).
int wctomb( char *s, wchar_t wc)
Converts a single wide character to its multibyte equivalent and stores it in the buffer pointed to by 's'.
s - Pointer to the output buffer to store the resulting multibyte character.
If NULL, the function is called to reset the conversion state.
wc - The wide character to convert.
Returns the number of bytes written into 's' if successful. If 'wc' is the null character (L'\0'), a single null byte is written and 1 is returned. If the wide character cannot be represented as a valid multibyte sequence, -1 is returned and errno is set to EILSEQ. If 's' is NULL, the function does not perform a conversion. Instead, it returns 0 if the encoding is stateless (as with UTF-8), or a non-zero value if the encoding is state-dependent. For UTF-8, 0 is always returned in this case.
wchar_t wc = L'O';
char buf[MB_CUR_MAX];
int len = wctomb(buf, wc);
if (len > 0) {
// buf now contains the multibyte representation of 'wc'
}
This function is a wrapper around wcrtomb(), using a static internal mbstate_t object to preserve compatibility with C standard behavior. However, since UTF-8 is a stateless encoding, the static state is effectively unused. The function does not support stateful encodings and behaves according to the "C" or UTF-8 locale model only. Behavior is undefined if multibyte encodings require internal state.
No locale-specific behavior is supported. No stateful encoding support (e.g., Shift-JIS or ISO 2022).
wctrans_t wctrans( const char *prop)
Returns a value representing a wide character mapping function, such as "tolower" or "toupper", to be used with `towctrans()`.
prop - a string specifying the mapping ("tolower", "toupper").
A wctrans_t descriptor for the transformation, or 0 if not recognized.
wctrans_t map = wctrans("toupper");
wchar_t upper = towctrans(L'a', map); // 'A'
wctype_t wctype( const char *prop)
Returns a value identifying a wide character classification property, such as "alpha", "digit", or "upper", which can later be used with `iswctype()` to test characters.
prop - a null-terminated string naming a wide character class.
Common names include: "alnum", "alpha", "blank", "cntrl",
"digit", "graph", "lower", "print", "punct", "space",
"upper", "xdigit".
Returns a value of type wctype_t if the property name is recognized, or 0 if not.
wctype_t type = wctype("alpha");
if (iswctype(L'Z', type))
{
// is an alpha character
}
The returned wctype_t value is opaque and must only be used with `iswctype()`.
Only a fixed set of property names are recognized. No locale-specific names are currently supported.
ar_t *wmemchr( const wchar_t *s, wchar_t c, size_t n)
Scans the initial n wide characters of the memory area pointed to by s for the first occurrence of the wide character c.
s - Memory area to scan. c - Wide character to locate. n - Number of wide characters to scan.
Returns a pointer to the first occurrence of c within the first n wide characters of s, or NULL if c is not found.
wmemcmp( const wchar_t * s1, const wchar_t * s2, size_t n)
Compares the first n wide characters of the object pointed to by s1 to the first n wide characters of the object pointed to by s2.
s1 - Pointer to block of elements of type wchar_t. s2 - Pointer to block of elements of type wchar_t. n - Number of elements of type wchar_t to compare.
Returns an integral value indicating the relationship between the content of the blocks: A zero value indicates that the contents of both memory blocks are equal. A value greater than zero indicates that the first wide character that does not match in both memory blocks has a greater value in ptr1 than in ptr2; And a value less than zero indicates the opposite.
ar_t *wmemcpy( wchar_t * restrict s1, const wchar_t * restrict s2, size_t n)
Copies n wide characters from s2 to s1. The memory areas must not overlap.
s1 - Destination buffer. s2 - Source buffer. n - Number of wide characters to copy.
Returns s1.
ar_t *wmemmove( wchar_t *s1, const wchar_t *s2, size_t n)
Copies n wide characters from s2 to s1. The memory areas may overlap.
s1 - Destination buffer. s2 - Source buffer. n - Number of wide characters to copy.
Returns s1.
ar_t *wmemset( wchar_t *s, wchar_t c, size_t n)
Copies the value of c into each of the first n wide characters of the object pointed to by s.
s - Pointer to the array to fill. c - Value to be set. n - Number of bytes to be set to the value.
Returns the value of s.
int wprintf( const wchar_t * restrict format, ...)
Format a variable list of arguments according to a wide-character format string and print the output to the standard output stream.
format - A wide-character printf() format string. ... - Additional arguments matching the format specifiers.
The number of wide characters written to the standard output, or a negative value if an error occurs.
Equivalent to fwprintf() with stdout as the output stream.
int wscanf( const wchar_t * restrict format, ...)
Reads formatted wide-character input from the standard input stream and stores the results into the provided argument locations.
format - How to convert the input into the arguments ... - Write the result in these arguments
The number of converted arguments.
double y0( double x)
Computes the Bessel function of the second kind of order zero, Y0(x).
x - input value, must be positive.
The value of Y0(x).
double val = y0(1.0);
Domain: x > 0. Returns -inf or NaN for invalid domain inputs.
Undefined for x <= 0.
float y0f( float x)
Evaluate the Bessel function of the second kind, Y_0(x), of order zero.
x - Positive real argument.
An approximation to Y_0(x) as a float. Both signs of zero return negative infinity. Negative values, including negative infinity, return NaN. Positive infinity returns positive zero. NaN returns NaN.
Include <math.h>. This is a BSD extension. The function does not assign errno. Floating-point exceptions may occur; enabled traps may prevent return. Use round-to-nearest. The trigonometric argument reduction used for large arguments assumes this rounding mode. Zero arguments can raise divide-by-zero; negative arguments can raise invalid.
double y1( double x)
Computes the Bessel function of the second kind of order one, Y1(x).
x - input value, must be positive.
The value of Y1(x).
double val = y1(1.0);
Domain: x > 0. Returns -inf or NaN for invalid domain inputs.
Undefined for x <= 0.
float y1f( float x)
Evaluate the Bessel function of the second kind, Y_1(x), of order one.
x - Positive real argument.
An approximation to Y_1(x) as a float. Both signs of zero return negative infinity. Negative values, including negative infinity, return NaN. Positive infinity returns positive zero. NaN returns NaN.
Include <math.h>. This is a BSD extension. The function does not assign errno. Floating-point exceptions may occur; enabled traps may prevent return. Use round-to-nearest. The trigonometric argument reduction used for large arguments assumes this rounding mode. Zero arguments can raise divide-by-zero; negative arguments can raise invalid.
double yn( int n, double x)
Computes the Bessel function of the second kind (Neumann function) of order `n` at `x`.
n - order of the Bessel function (integer). x - the point at which to evaluate. Must be positive.
Returns the value of the Bessel function \( Y_n(x) \). Returns NaN and sets errno to EDOM if `x` < 0. Returns -infinity and sets errno to ERANGE if `x` == 0.
double r = yn(1, 2.0); // Y1(2.0)
Commonly used in physics for problems with cylindrical symmetry involving singularities.
None known.
float ynf( int n, float x)
Evaluate the Bessel function of the second kind, Y_n(x), for integer order n.
n - Integer order; see BUGS for unsupported extreme orders. x - Positive real argument.
An approximation to Y_n(x) as a float. Negative arguments, including negative infinity, return NaN. NaN returns NaN. Both signs of zero return negative infinity for every n, subject to the negative-order defect below. Positive infinity returns negative zero for n = -1 and positive zero for other supported orders.
Include <math.h>. This is a BSD extension. The function does not assign errno. Floating-point exceptions may occur; enabled traps may prevent return. Use round-to-nearest. The trigonometric argument reduction used for large arguments assumes this rounding mode. Evaluation time can grow with the magnitude of n. For positive integer m and finite positive x, Y_-m(x) = (-1)^m Y_m(x). Zero arguments can raise divide-by-zero; negative arguments can raise invalid.
INT_MIN is not supported for positive arguments: negating this order overflows signed int. Recurrence arithmetic is not protected against overflow for very large orders. For negative odd orders at zero, the returned negative infinity disagrees with the positive-side limit, which is positive infinity. The zero check bypasses the negative-order sign correction.