NAME
7 Library — WG14
N1256, clause 7
7
7.1 Introduction
7.1.1 Definitions of terms
A string is a contiguous sequence of characters terminated by and including the first null character. The term multibyte string is sometimes used instead to emphasize special processing given to multibyte characters contained in the string or to avoid confusion with a wide string. A pointer to a string is a pointer to its initial (lowest addressed) character. The length of a string is the number of bytes preceding the null character and the value of a string is the sequence of the values of the contained characters, in order.
The decimal-point character is the character used by functions that convert floating-point numbers to or from character sequences to denote the beginning of the fractional part of such character sequences.157) It is represented in the text and examples by a period, but may be changed by the setlocale function.
A null wide character is a wide character with code value zero.
A wide string is a contiguous sequence of wide characters terminated by and including the first null wide character. A pointer to a wide string is a pointer to its initial (lowest addressed) wide character. The length of a wide string is the number of wide characters preceding the null wide character and the value of a wide string is the sequence of code values of the contained wide characters, in order.
A shift sequence is a contiguous sequence of bytes within a multibyte string that (potentially) causes a change in shift state (see 5.2.1.2 ). A shift sequence shall not have a corresponding wide character; it is instead taken to be an adjunct to an adjacent multibyte character.158) Forward references: character handling ( 7.4 Character handling <ctype.h> ), the setlocale function ( 7.11.1.1 The setlocale function ).
7.1.2 Standard headers
Each library function is declared, with a type that includes a prototype, in a header, [159] whose contents are made available by the #include preprocessing directive. The header declares a set of related functions, plus any necessary types and additional macros needed to facilitate their use. Declarations of types described in this clause shall not include type qualifiers, unless explicitly stated otherwise.
The standard headers are
If a file with the same name as one of the above < and > delimited sequences, not provided as part of the implementation, is placed in any of the standard places that are searched for included source files, the behavior is undefined.
Standard headers may be included in any order; each may be included more than once in a given scope, with no effect different from being included only once, except that the effect of including <assert.h> depends on the definition of NDEBUG (see 7.2 Diagnostics <assert.h> ). If used, a header shall be included outside of any external declaration or definition, and it shall first be included before the first reference to any of the functions or objects it declares, or to any of the types or macros it defines. However, if an identifier is declared or defined in more than one header, the second and subsequent associated headers may be included after the initial reference to the identifier. The program shall not have any macros with names lexically identical to keywords currently defined prior to the inclusion.
Any definition of an object-like macro described in this clause shall expand to code that is fully protected by parentheses where necessary, so that it groups in an arbitrary expression as if it were a single identifier.
Any declaration of a library function shall have external linkage.
A summary of the contents of the standard headers is given in annex B. Forward references: diagnostics ( 7.2 Diagnostics <assert.h> ).
7.1.3 Reserved identifiers
Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.
- All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
- All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
- Each macro name in any of the following subclauses (including the future library directions) is reserved for use as specified if any of its associated headers is included; unless explicitly stated otherwise (see 7.1.4 Use of library functions ).
- All identifiers with external linkage in any of the following subclauses (including the future library directions) are always reserved for use as identifiers with external linkage.160)
- Each identifier with file scope listed in any of the following subclauses (including the future library directions) is reserved for use as a macro name and as an identifier with file scope in the same name space if any of its associated headers is included.
No other identifiers are reserved. If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4 Use of library functions ), or defines a reserved identifier as a macro name, the behavior is undefined.
If the program removes (with #undef) any macro definition of an identifier in the first group listed above, the behavior is undefined.
7.1.4 Use of library functions
Each of the following statements applies unless explicitly stated otherwise in the detailed descriptions that follow: If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, or a pointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined. If a function argument is described as being an array, the pointer actually passed to the function shall have a value such that all address computations and accesses to objects (that would be valid if the pointer did point to the first element of such an array) are in fact valid. Any function declared in a header may be additionally implemented as a function-like macro defined in the header, so if a library function is declared explicitly when its header is included, one of the techniques shown below can be used to ensure the declaration is not affected by such a macro. Any macro definition of a function can be suppressed locally by enclosing the name of the function in parentheses, because the name is then not followed by the left parenthesis that indicates expansion of a macro function name. For the same syntactic reason, it is permitted to take the address of a library function even if it is also defined as a macro.161) The use of #undef to remove any macro definition will also ensure that an actual function is referred to. Any invocation of a library function that is implemented as a macro shall expand to code that evaluates each of its arguments exactly once, fully protected by parentheses where necessary, so it is generally safe to use arbitrary expressions as arguments.162) Likewise, those function-like macros described in the following subclauses may be invoked in an expression anywhere a function with a compatible return type could be called.163) All object-like macros listed as expanding to integer constant expressions shall additionally be suitable for use in #if preprocessing directives.
Provided that a library function can be declared without reference to any type defined in a header, it is also permissible to declare the function and use it without including its associated header.
There is a sequence point immediately before a library function returns.
The functions in the standard library are not guaranteed to be reentrant and may modify objects with static storage duration.164)
The function atoi may be used in any of several ways: — by use of its associated header (possibly generating a macro expansion)
#include <stdlib.h>
const char *str;
/* ... */
i = atoi(str);
— by use of its associated header (assuredly generating a true function reference)
#include <stdlib.h>
#undef atoi
const char *str;
/* ... */
i = atoi(str);
or
#include <stdlib.h>
const char *str;
/* ... */
i = (atoi)(str);
— by explicit declaration
extern int atoi(const char *);
const char *str;
/* ... */
i = atoi(str);
7.2 Diagnostics <assert.h>
The header <assert.h> defines the assert macro and refers to another macro,
NDEBUG
which is not defined by <assert.h>. If NDEBUG is defined as a macro name at the point in the source file where <assert.h> is included, the assert macro is defined simply as
#define assert(ignore) ((void)0)
The assert macro is redefined according to the current state of NDEBUG each time that <assert.h> is included.
The assert macro shall be implemented as a macro, not as an actual function. If the macro definition is suppressed in order to access an actual function, the behavior is undefined.
7.2.1 Program diagnostics
7.2.1.1 The assert macro
Synopsis
#include <assert.h>
void assert(scalar expression);
Description
The assert macro puts diagnostic tests into programs; it expands to a void expression. When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal to 0), the assert macro writes information about the particular call that failed (including the text of the argument, the name of the source file, the source line number, and the name of the enclosing function — the latter are respectively the values of the preprocessing macros _ _FILE_ _ and _ _LINE_ _ and of the identifier _ _func_ _) on the standard error stream in an implementation-defined format.165) It then calls the abort function.
Returns
The assert macro returns no value. Forward references: the abort function ( 7.20.4.1 The abort function ).
7.3 Complex arithmetic <complex.h>
7.3.1 Introduction
The header <complex.h> defines macros and declares functions that support complex arithmetic.166) Each synopsis specifies a family of functions consisting of a principal function with one or more double complex parameters and a double complex or double return value; and other functions with the same name but with f and l suffixes which are corresponding functions with float and long double parameters and return values.
The macro complex expands to _Complex; the macro _Complex_I expands to a constant expression of type const float _Complex, with the value of the imaginary unit.167)
The macros imaginary and _Imaginary_I are defined if and only if the implementation supports imaginary types; [168] if defined, they expand to _Imaginary and a constant expression of type const float _Imaginary with the value of the imaginary unit.
The macro expands to either _Imaginary_I or _Complex_I. If _Imaginary_I is not defined, I shall expand to _Complex_I.
Notwithstanding the provisions of 7.1.3 Reserved identifiers , a program may undefine and perhaps then redefine the macros complex, imaginary, and I. Forward references: IEC 60559-compatible complex arithmetic (annex G).
7.3.2 Conventions
Values are interpreted as radians, not degrees. An implementation may set errno but is not required to.
7.3.3 Branch cuts
Some of the functions below have branch cuts, across which the function is discontinuous. For implementations with a signed zero (including all IEC 60559 implementations) that follow the specifications of annex G, the sign of zero distinguishes one side of a cut from another so the function is continuous (except for format limitations) as the cut is approached from either side. For example, for the square root function, which has a branch cut along the negative real axis, the top of the cut, with imaginary part +0, maps to the positive imaginary axis, and the bottom of the cut, with imaginary part −0, maps to the negative imaginary axis.
Implementations that do not support a signed zero (see annex F) cannot distinguish the sides of branch cuts. These implementations shall map a cut so the function is continuous as the cut is approached coming around the finite endpoint of the cut in a counter clockwise direction. (Branch cuts for the functions specified here have just one finite endpoint.) For example, for the square root function, coming counter clockwise around the finite endpoint of the cut along the negative real axis approaches the cut from above, so the cut maps to the positive imaginary axis.
7.3.4 The CX_LIMITED_RANGE pragma
Synopsis
#include <complex.h>
#pragma STDC CX_LIMITED_RANGE on-off-switch
Description
The usual mathematical formulas for complex multiply, divide, and absolute value are problematic because of their treatment of infinities and because of undue overflow and underflow. The CX_LIMITED_RANGE pragma can be used to inform the implementation that (where the state is ‘‘on’’) the usual mathematical formulas are acceptable.169) The pragma can occur either outside external declarations or preceding all explicit declarations and statements inside a compound statement. When outside external declarations, the pragma takes effect from its occurrence until another CX_LIMITED_RANGE pragma is encountered, or until the end of the translation unit. When inside a compound statement, the pragma takes effect from its occurrence until another CX_LIMITED_RANGE pragma is encountered (including within a nested compound statement), or until the end of the compound statement; at the end of a compound statement the state for the pragma is restored to its condition just before the compound statement. If this pragma is used in any other context, the behavior is undefined. The default state for the pragma is ‘‘off’’.
7.3.5 Trigonometric functions
7.3.5.1 The cacos functions
Synopsis
#include <complex.h>
double complex cacos(double complex z);
float complex cacosf(float complex z);
long double complex cacosl(long double complex z);
Description
The cacos functions compute the complex arc cosine of z, with branch cuts outside the interval [−1, +1] along the real axis.
Returns
The cacos functions return the complex arc cosine value, in the range of a strip mathematically unbounded along the imaginary axis and in the interval [0, π ] along the real axis.
7.3.5.2 The casin functions
Synopsis
#include <complex.h>
double complex casin(double complex z);
float complex casinf(float complex z);
long double complex casinl(long double complex z);
Description
The casin functions compute the complex arc sine of z, with branch cuts outside the interval [−1, +1] along the real axis.
Returns
The casin functions return the complex arc sine value, in the range of a strip mathematically unbounded along the imaginary axis and in the interval [−π /2, +π /2] along the real axis.
7.3.5.3 The catan functions
Synopsis
#include <complex.h>
double complex catan(double complex z);
float complex catanf(float complex z);
long double complex catanl(long double complex z);
Description
The catan functions compute the complex arc tangent of z, with branch cuts outside the interval [−i, +i] along the imaginary axis.
Returns
The catan functions return the complex arc tangent value, in the range of a strip mathematically unbounded along the imaginary axis and in the interval [−π /2, +π /2] along the real axis.
7.3.5.4 The ccos functions
Synopsis
#include <complex.h>
double complex ccos(double complex z);
float complex ccosf(float complex z);
long double complex ccosl(long double complex z);
Description
The ccos functions compute the complex cosine of z.
Returns
The ccos functions return the complex cosine value.
7.3.5.5 The csin functions
Synopsis
#include <complex.h>
double complex csin(double complex z);
float complex csinf(float complex z);
long double complex csinl(long double complex z);
Description
The csin functions compute the complex sine of z.
Returns
The csin functions return the complex sine value.
7.3.5.6 The ctan functions
Synopsis
#include <complex.h>
double complex ctan(double complex z);
float complex ctanf(float complex z);
long double complex ctanl(long double complex z);
Description
The ctan functions compute the complex tangent of z.
Returns
The ctan functions return the complex tangent value.
7.3.6 Hyperbolic functions
7.3.6.1 The cacosh functions
Synopsis
#include <complex.h>
double complex cacosh(double complex z);
float complex cacoshf(float complex z);
long double complex cacoshl(long double complex z);
Description
The cacosh functions compute the complex arc hyperbolic cosine of z, with a branch cut at values less than 1 along the real axis.
Returns
The cacosh functions return the complex arc hyperbolic cosine value, in the range of a half-strip of non-negative values along the real axis and in the interval [−iπ , +iπ ] along the imaginary axis.
7.3.6.2 The casinh functions
Synopsis
#include <complex.h>
double complex casinh(double complex z);
float complex casinhf(float complex z);
long double complex casinhl(long double complex z);
Description
The casinh functions compute the complex arc hyperbolic sine of z, with branch cuts outside the interval [−i, +i] along the imaginary axis.
Returns
The casinh functions return the complex arc hyperbolic sine value, in the range of a strip mathematically unbounded along the real axis and in the interval [−iπ /2, +iπ /2] along the imaginary axis.
7.3.6.3 The catanh functions
Synopsis
#include <complex.h>
double complex catanh(double complex z);
float complex catanhf(float complex z);
long double complex catanhl(long double complex z);
Description
The catanh functions compute the complex arc hyperbolic tangent of z, with branch cuts outside the interval [−1, +1] along the real axis.
Returns
The catanh functions return the complex arc hyperbolic tangent value, in the range of a strip mathematically unbounded along the real axis and in the interval [−iπ /2, +iπ /2] along the imaginary axis.
7.3.6.4 The ccosh functions
Synopsis
#include <complex.h>
double complex ccosh(double complex z);
float complex ccoshf(float complex z);
long double complex ccoshl(long double complex z);
Description
The ccosh functions compute the complex hyperbolic cosine of z.
Returns
The ccosh functions return the complex hyperbolic cosine value.
7.3.6.5 The csinh functions
Synopsis
#include <complex.h>
double complex csinh(double complex z);
float complex csinhf(float complex z);
long double complex csinhl(long double complex z);
Description
The csinh functions compute the complex hyperbolic sine of z.
Returns
The csinh functions return the complex hyperbolic sine value.
7.3.6.6 The ctanh functions
Synopsis
#include <complex.h>
double complex ctanh(double complex z);
float complex ctanhf(float complex z);
long double complex ctanhl(long double complex z);
Description
The ctanh functions compute the complex hyperbolic tangent of z.
Returns
The ctanh functions return the complex hyperbolic tangent value.
7.3.7 Exponential and logarithmic functions
7.3.7.1 The cexp functions
Synopsis
#include <complex.h>
double complex cexp(double complex z);
float complex cexpf(float complex z);
long double complex cexpl(long double complex z);
Description
The cexp functions compute the complex base-e exponential of z.
Returns
The cexp functions return the complex base-e exponential value.
7.3.7.2 The clog functions
Synopsis
#include <complex.h>
double complex clog(double complex z);
float complex clogf(float complex z);
long double complex clogl(long double complex z);
Description
The clog functions compute the complex natural (base-e) logarithm of z, with a branch cut along the negative real axis.
Returns
The clog functions return the complex natural logarithm value, in the range of a strip mathematically unbounded along the real axis and in the interval [−iπ , +iπ ] along the imaginary axis.
7.3.8 Power and absolute-value functions
7.3.8.1 The cabs functions
Synopsis
#include <complex.h>
double cabs(double complex z);
float cabsf(float complex z);
long double cabsl(long double complex z);
Description
The cabs functions compute the complex absolute value (also called norm, modulus, or magnitude) of z.
Returns
The cabs functions return the complex absolute value.
7.3.8.2 The cpow functions
Synopsis
#include <complex.h>
double complex cpow(double complex x, double complex y);
float complex cpowf(float complex x, float complex y);
long double complex cpowl(long double complex x,
long double complex y);
Description
The cpow functions compute the complex power function xy , with a branch cut for the first parameter along the negative real axis.
Returns
The cpow functions return the complex power function value.
7.3.8.3 The csqrt functions
Synopsis
#include <complex.h>
double complex csqrt(double complex z);
float complex csqrtf(float complex z);
long double complex csqrtl(long double complex z);
Description
The csqrt functions compute the complex square root of z, with a branch cut along the negative real axis.
Returns
The csqrt functions return the complex square root value, in the range of the right half-plane (including the imaginary axis).
7.3.9 Manipulation functions
7.3.9.1 The carg functions
Synopsis
#include <complex.h>
double carg(double complex z);
float cargf(float complex z);
long double cargl(long double complex z);
Description
The carg functions compute the argument (also called phase angle) of z, with a branch cut along the negative real axis.
Returns
The carg functions return the value of the argument in the interval [−π , +π ].
7.3.9.2 The cimag functions
Synopsis
#include <complex.h>
double cimag(double complex z);
float cimagf(float complex z);
long double cimagl(long double complex z);
Description
The cimag functions compute the imaginary part of z.170)
Returns
The cimag functions return the imaginary part value (as a real).
7.3.9.3 The conj functions
Synopsis
#include <complex.h>
double complex conj(double complex z);
float complex conjf(float complex z);
long double complex conjl(long double complex z);
Description
The conj functions compute the complex conjugate of z, by reversing the sign of its imaginary part.
Returns
The conj functions return the complex conjugate value.
7.3.9.4 The cproj functions
Synopsis
#include <complex.h>
double complex cproj(double complex z);
float complex cprojf(float complex z);
long double complex cprojl(long double complex z);
Description
The cproj functions compute a projection of z onto the Riemann sphere: z projects to z except that all complex infinities (even those with one infinite part and one NaN part) project to positive infinity on the real axis. If z has an infinite part, then cproj(z) is equivalent to
INFINITY + I * copysign(0.0, cimag(z))
Returns
The cproj functions return the value of the projection onto the Riemann sphere.
7.3.9.5 The creal functions
Synopsis
#include <complex.h>
double creal(double complex z);
float crealf(float complex z);
long double creall(long double complex z);
Description
The creal functions compute the real part of z.171)
Returns
The creal functions return the real part value.
7.4 Character handling <ctype.h>
The header <ctype.h> declares several functions useful for classifying and mapping characters.172) In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined.
The behavior of these functions is affected by the current locale. Those functions that have locale-specific aspects only when not in the "C" locale are noted below.
The term printing character refers to a member of a locale-specific set of characters, each of which occupies one printing position on a display device; the term control character refers to a member of a locale-specific set of characters that are not printing characters.173) All letters and digits are printing characters. Forward references: EOF ( 7.19.1 Introduction ), localization ( 7.11 Localization <locale.h> ).
7.4.1 Character classification functions
The functions in this subclause return nonzero (true) if and only if the value of the argument c conforms to that in the description of the function.
7.4.1.1 The isalnum function
Synopsis
#include <ctype.h>
int isalnum(int c);
Description
The isalnum function tests for any character for which isalpha or isdigit is true.
7.4.1.2 The isalpha function
Synopsis
#include <ctype.h>
int isalpha(int c);
Description
The isalpha function tests for any character for which isupper or islower is true, or any character that is one of a locale-specific set of alphabetic characters for which none of iscntrl, isdigit, ispunct, or isspace is true.174) In the "C" locale, isalpha returns true only for the characters for which isupper or islower is true.
7.4.1.3 The isblank function
Synopsis
#include <ctype.h>
int isblank(int c);
Description
The isblank function tests for any character that is a standard blank character or is one of a locale-specific set of characters for which isspace is true and that is used to separate words within a line of text. The standard blank characters are the following: space (' '), and horizontal tab ('\t'). In the "C" locale, isblank returns true only for the standard blank characters.
7.4.1.4 The iscntrl function
Synopsis
#include <ctype.h>
int iscntrl(int c);
Description
The iscntrl function tests for any control character.
7.4.1.5 The isdigit function
Synopsis
#include <ctype.h>
int isdigit(int c);
Description
The isdigit function tests for any decimal-digit character (as defined in 5.2.1 ).
7.4.1.6 The isgraph function
Synopsis
#include <ctype.h>
int isgraph(int c);
Description
The isgraph function tests for any printing character except space (' ').
7.4.1.7 The islower function
Synopsis
#include <ctype.h>
int islower(int c);
Description
The islower function tests for any character that is a lowercase letter or is one of a locale-specific set of characters for which none of iscntrl, isdigit, ispunct, or isspace is true. In the "C" locale, islower returns true only for the lowercase letters (as defined in 5.2.1 ).
7.4.1.8 The isprint function
Synopsis
#include <ctype.h>
int isprint(int c);
Description
The isprint function tests for any printing character including space (' ').
7.4.1.9 The ispunct function
Synopsis
#include <ctype.h>
int ispunct(int c);
Description
The ispunct function tests for any printing character that is one of a locale-specific set of punctuation characters for which neither isspace nor isalnum is true. In the "C" locale, ispunct returns true for every printing character for which neither isspace nor isalnum is true.
7.4.1.10 The isspace function
Synopsis
#include <ctype.h>
int isspace(int c);
Description
The isspace function tests for any character that is a standard white-space character or is one of a locale-specific set of characters for which isalnum is false. The standard white-space characters are the following: space (' '), form feed ('\f'), new-line ('\n'), carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v'). In the "C" locale, isspace returns true only for the standard white-space characters.
7.4.1.11 The isupper function
Synopsis
#include <ctype.h>
int isupper(int c);
Description
The isupper function tests for any character that is an uppercase letter or is one of a locale-specific set of characters for which none of iscntrl, isdigit, ispunct, or isspace is true. In the "C" locale, isupper returns true only for the uppercase letters (as defined in 5.2.1 ).
7.4.1.12 The isxdigit function
Synopsis
#include <ctype.h>
int isxdigit(int c);
Description
The isxdigit function tests for any hexadecimal-digit character (as defined in 6.4.4.1 ).
7.4.2 Character case mapping functions
7.4.2.1 The tolower function
Synopsis
#include <ctype.h>
int tolower(int c);
Description
The tolower function converts an uppercase letter to a corresponding lowercase letter.
Returns
If the argument is a character for which isupper is true and there are one or more corresponding characters, as specified by the current locale, for which islower is true, the tolower function returns one of the corresponding characters (always the same one for any given locale); otherwise, the argument is returned unchanged.
7.4.2.2 The toupper function
Synopsis
#include <ctype.h>
int toupper(int c);
Description
The toupper function converts a lowercase letter to a corresponding uppercase letter.
Returns
If the argument is a character for which islower is true and there are one or more corresponding characters, as specified by the current locale, for which isupper is true, the toupper function returns one of the corresponding characters (always the same one for any given locale); otherwise, the argument is returned unchanged.
7.5 Errors <errno.h>
The header <errno.h> defines several macros, all relating to the reporting of error conditions.
The macros are
EDOM
EILSEQ
ERANGE
which expand to integer constant expressions with type int, distinct positive values, and which are suitable for use in #if preprocessing directives; and errno which expands to a modifiable lvalue [175] that has type int, the value of which is set to a positive error number by several library functions. It is unspecified whether errno is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual object, or a program defines an identifier with the name errno, the behavior is undefined.
The value of errno is zero at program startup, but is never set to zero by any library function.176) The value of errno may be set to nonzero by a library function call whether or not there is an error, provided the use of errno is not documented in the description of the function in this International Standard.
Additional macro definitions, beginning with E and a digit or E and an uppercase letter, [177] may also be specified by the implementation.
7.6 Floating-point environment <fenv.h>
The header <fenv.h> declares two types and several macros and functions to provide access to the floating-point environment. The floating-point environment refers collectively to any floating-point status flags and control modes supported by the implementation.178) A floating-point status flag is a system variable whose value is set (but never cleared) when a floating-point exception is raised, which occurs as a side effect of exceptional floating-point arithmetic to provide auxiliary information.179) A floating-point control mode is a system variable whose value may be set by the user to affect the subsequent behavior of floating-point arithmetic.
Certain programming conventions support the intended model of use for the floating-point environment: [180]
- a function call does not alter its caller’s floating-point control modes, clear its caller’s floating-point status flags, nor depend on the state of its caller’s floating-point status flags unless the function is so documented;
- a function call is assumed to require default floating-point control modes, unless its documentation promises otherwise;
- a function call is assumed to have the potential for raising floating-point exceptions, unless its documentation promises otherwise.
The type fenv_t represents the entire floating-point environment.
The type fexcept_t represents the floating-point status flags collectively, including any status the implementation associates with the flags.
Each of the macros
FE_DIVBYZERO
FE_INEXACT
FE_INVALID
FE_OVERFLOW
FE_UNDERFLOW
is defined if and only if the implementation supports the floating-point exception by means of the functions in 7.6.2.181 ) Additional implementation-defined floating-point exceptions, with macro definitions beginning with FE_ and an uppercase letter, may also be specified by the implementation. The defined macros expand to integer constant expressions with values such that bitwise ORs of all combinations of the macros result in distinct values, and furthermore, bitwise ANDs of all combinations of the macros result in zero.182)
The macro
FE_ALL_EXCEPT
is simply the bitwise OR of all floating-point exception macros defined by the implementation. If no such macros are defined, FE_ALL_EXCEPT shall be defined as 0.
Each of the macros
FE_DOWNWARD
FE_TONEAREST
FE_TOWARDZERO
FE_UPWARD
is defined if and only if the implementation supports getting and setting the represented rounding direction by means of the fegetround and fesetround functions. Additional implementation-defined rounding directions, with macro definitions beginning with FE_ and an uppercase letter, may also be specified by the implementation. The defined macros expand to integer constant expressions whose values are distinct nonnegative values.183)
The macro FE_DFL_ENV represents the default floating-point environment — the one installed at program startup
- and has type ‘‘pointer to const-qualified fenv_t’’. It can be used as an argument to <fenv.h> functions that manage the floating-point environment.
Additional implementation-defined environments, with macro definitions beginning with FE_ and an uppercase letter, and having type ‘‘pointer to const-qualified fenv_t’’, may also be specified by the implementation.
7.6.1 The FENV_ACCESS pragma
Synopsis
#include <fenv.h>
#pragma STDC FENV_ACCESS on-off-switch
Description
The FENV_ACCESS pragma provides a means to inform the implementation when a program might access the floating-point environment to test floating-point status flags or run under non-default floating-point control modes.184) The pragma shall occur either outside external declarations or preceding all explicit declarations and statements inside a compound statement. When outside external declarations, the pragma takes effect from its occurrence until another FENV_ACCESS pragma is encountered, or until the end of the translation unit. When inside a compound statement, the pragma takes effect from its occurrence until another FENV_ACCESS pragma is encountered (including within a nested compound statement), or until the end of the compound statement; at the end of a compound statement the state for the pragma is restored to its condition just before the compound statement. If this pragma is used in any other context, the behavior is undefined. If part of a program tests floating-point status flags, sets floating-point control modes, or runs under non-default mode settings, but was translated with the state for the FENV_ACCESS pragma ‘‘off’’, the behavior is undefined. The default state (‘‘on’’ or ‘‘off’’) for the pragma is implementation-defined. (When execution passes from a part of the program translated with FENV_ACCESS ‘‘off’’ to a part translated with FENV_ACCESS ‘‘on’’, the state of the floating-point status flags is unspecified and the floating-point control modes have their default settings.)
#include <fenv.h>
void f(double x)
{
#pragma STDC FENV_ACCESS ON
void g(double);
void h(double);
/* ... */
g(x + 1);
h(x + 1);
/* ... */
}
If the function g might depend on status flags set as a side effect of the first x + 1, or if the second x + 1 might depend on control modes set as a side effect of the call to function g, then the program shall contain an appropriately placed invocation of #pragma STDC FENV_ACCESS ON.185)
7.6.2 Floating-point exceptions
The following functions provide access to the floating-point status flags.186) The int input argument for the functions represents a subset of floating-point exceptions, and can be zero or the bitwise OR of one or more floating-point exception macros, for example FE_OVERFLOW | FE_INEXACT. For other argument values the behavior of these functions is undefined.
7.6.2.1 The feclearexcept function
Synopsis
#include <fenv.h>
int feclearexcept(int excepts);
Description
The feclearexcept function attempts to clear the supported floating-point exceptions represented by its argument.
Returns
The feclearexcept function returns zero if the excepts argument is zero or if all the specified exceptions were successfully cleared. Otherwise, it returns a nonzero value.
7.6.2.2 The fegetexceptflag function
Synopsis
#include <fenv.h>
int fegetexceptflag(fexcept_t *flagp,
int excepts);
Description
The fegetexceptflag function attempts to store an implementation-defined representation of the states of the floating-point status flags indicated by the argument excepts in the object pointed to by the argument flagp.
Returns
The fegetexceptflag function returns zero if the representation was successfully stored. Otherwise, it returns a nonzero value.
7.6.2.3 The feraiseexcept function
Synopsis
#include <fenv.h>
int feraiseexcept(int excepts);
Description
The feraiseexcept function attempts to raise the supported floating-point exceptions represented by its argument.187) The order in which these floating-point exceptions are raised is unspecified, except as stated in F.7.6. Whether the feraiseexcept function additionally raises the ‘‘inexact’’ floating-point exception whenever it raises the ‘‘overflow’’ or ‘‘underflow’’ floating-point exception is implementation-defined.
Returns
The feraiseexcept function returns zero if the excepts argument is zero or if all the specified exceptions were successfully raised. Otherwise, it returns a nonzero value.
7.6.2.4 The fesetexceptflag function
Synopsis
#include <fenv.h>
int fesetexceptflag(const fexcept_t *flagp,
int excepts);
Description
The fesetexceptflag function attempts to set the floating-point status flags indicated by the argument excepts to the states stored in the object pointed to by flagp. The value of *flagp shall have been set by a previous call to fegetexceptflag whose second argument represented at least those floating-point exceptions represented by the argument excepts. This function does not raise floating-point exceptions, but only sets the state of the flags.
Returns
The fesetexceptflag function returns zero if the excepts argument is zero or if all the specified flags were successfully set to the appropriate state. Otherwise, it returns a nonzero value.
7.6.2.5 The fetestexcept function
Synopsis
#include <fenv.h>
int fetestexcept(int excepts);
Description
The fetestexcept function determines which of a specified subset of the floating-point exception flags are currently set. The excepts argument specifies the floating-point status flags to be queried.188)
Returns
The fetestexcept function returns the value of the bitwise OR of the floating-point exception macros corresponding to the currently set floating-point exceptions included in excepts.
Call f if ‘‘invalid’’ is set, then g if ‘‘overflow’’ is set:
#include <fenv.h>
/* ... */
{
#pragma STDC FENV_ACCESS ON
int set_excepts;
feclearexcept(FE_INVALID | FE_OVERFLOW);
// maybe raise exceptions
set_excepts = fetestexcept(FE_INVALID | FE_OVERFLOW);
if (set_excepts & FE_INVALID) f();
if (set_excepts & FE_OVERFLOW) g();
/* ... */
}
7.6.3 Rounding
The fegetround and fesetround functions provide control of rounding direction modes.
7.6.3.1 The fegetround function
Synopsis
#include <fenv.h>
int fegetround(void);
Description
The fegetround function gets the current rounding direction.
Returns
The fegetround function returns the value of the rounding direction macro representing the current rounding direction or a negative value if there is no such rounding direction macro or the current rounding direction is not determinable.
7.6.3.2 The fesetround function
Synopsis
#include <fenv.h>
int fesetround(int round);
Description
The fesetround function establishes the rounding direction represented by its argument round. If the argument is not equal to the value of a rounding direction macro, the rounding direction is not changed.
Returns
The fesetround function returns zero if and only if the requested rounding direction was established.
Save, set, and restore the rounding direction. Report an error and abort if setting the rounding direction fails.
#include <fenv.h>
#include <assert.h>
void f(int round_dir)
{
#pragma STDC FENV_ACCESS ON
int save_round;
int setround_ok;
save_round = fegetround();
setround_ok = fesetround(round_dir);
assert(setround_ok == 0);
/* ... */
fesetround(save_round);
/* ... */
}
7.6.4 Environment
The functions in this section manage the floating-point environment — status flags and control modes — as one entity.
7.6.4.1 The fegetenv function
Synopsis
#include <fenv.h>
int fegetenv(fenv_t *envp);
Description
The fegetenv function attempts to store the current floating-point environment in the object pointed to by envp.
Returns
The fegetenv function returns zero if the environment was successfully stored. Otherwise, it returns a nonzero value.
7.6.4.2 The feholdexcept function
Synopsis
#include <fenv.h>
int feholdexcept(fenv_t *envp);
Description
The feholdexcept function saves the current floating-point environment in the object pointed to by envp, clears the floating-point status flags, and then installs a non-stop (continue on floating-point exceptions) mode, if available, for all floating-point exceptions.189)
Returns
The feholdexcept function returns zero if and only if non-stop floating-point exception handling was successfully installed.
7.6.4.3 The fesetenv function
Synopsis
#include <fenv.h>
int fesetenv(const fenv_t *envp);
Description
The fesetenv function attempts to establish the floating-point environment represented by the object pointed to by envp. The argument envp shall point to an object set by a call to fegetenv or feholdexcept, or equal a floating-point environment macro. Note that fesetenv merely installs the state of the floating-point status flags represented through its argument, and does not raise these floating-point exceptions.
Returns
The fesetenv function returns zero if the environment was successfully established. Otherwise, it returns a nonzero value.
7.6.4.4 The feupdateenv function
Synopsis
#include <fenv.h>
int feupdateenv(const fenv_t *envp);
Description
The feupdateenv function attempts to save the currently raised floating-point exceptions in its automatic storage, install the floating-point environment represented by the object pointed to by envp, and then raise the saved floating-point exceptions. The argument envp shall point to an object set by a call to feholdexcept or fegetenv, or equal a floating-point environment macro.
Returns
The feupdateenv function returns zero if all the actions were successfully carried out. Otherwise, it returns a nonzero value.
Hide spurious underflow floating-point exceptions:
#include <fenv.h>
double f(double x)
{
#pragma STDC FENV_ACCESS ON
double result;
fenv_t save_env;
if (feholdexcept(&save_env))
return /* indication of an environmental problem */;
// compute result
if (/* test spurious underflow */)
if (feclearexcept(FE_UNDERFLOW))
return /* indication of an environmental problem */;
if (feupdateenv(&save_env))
return /* indication of an environmental problem */;
return result;
}
7.7 Characteristics of floating types <float.h>
The header <float.h> defines several macros that expand to various limits and parameters of the standard floating-point types.
The macros, their meanings, and the constraints (or restrictions) on their values are listed in 5.2.4.2.2.
7.8 Format conversion of integer types <inttypes.h>
The header <inttypes.h> includes the header <stdint.h> and extends it with additional facilities provided by hosted implementations.
It declares functions for manipulating greatest-width integers and converting numeric character strings to greatest-width integers, and it declares the type imaxdiv_t which is a structure type that is the type of the value returned by the imaxdiv function. For each type declared in <stdint.h>, it defines corresponding macros for conversion specifiers for use with the formatted input/output functions.190) Forward references: integer types <stdint.h> ( 7.18 Integer types <stdint.h> ), formatted input/output functions ( 7.19.6 Formatted input/output functions ), formatted wide character input/output functions ( 7.24.2 Formatted wide character input/output functions ).
7.8.1 Macros for format specifiers
Each of the following object-like macros [191] expands to a character string literal containing a conversion specifier, possibly modified by a length modifier, suitable for use within the format argument of a formatted input/output function when converting the corresponding integer type. These macro names have the general form of PRI (character string literals for the fprintf and fwprintf family) or SCN (character string literals for the fscanf and fwscanf family), [192] followed by the conversion specifier, followed by a name corresponding to a similar type name in 7.18.1. In these names, N represents the width of the type as described in 7.18.1. For example, PRIdFAST32 can be used in a format string to print the value of an integer of type int_fast32_t.
The fprintf macros for signed integers are:
PRIdN PRIdLEASTN PRIdFASTN PRIdMAX PRIdPTR
PRIiN PRIiLEASTN PRIiFASTN PRIiMAX PRIiPTR
The fprintf macros for unsigned integers are:
PRIoN PRIoLEASTN PRIoFASTN PRIoMAX PRIoPTR
PRIuN PRIuLEASTN PRIuFASTN PRIuMAX PRIuPTR
PRIxN PRIxLEASTN PRIxFASTN PRIxMAX PRIxPTR
PRIXN PRIXLEASTN PRIXFASTN PRIXMAX PRIXPTR
The fscanf macros for signed integers are:
SCNdN SCNdLEASTN SCNdFASTN SCNdMAX SCNdPTR
SCNiN SCNiLEASTN SCNiFASTN SCNiMAX SCNiPTR
The fscanf macros for unsigned integers are:
SCNoN SCNoLEASTN SCNoFASTN SCNoMAX SCNoPTR
SCNuN SCNuLEASTN SCNuFASTN SCNuMAX SCNuPTR
SCNxN SCNxLEASTN SCNxFASTN SCNxMAX SCNxPTR
For each type that the implementation provides in <stdint.h>, the corresponding fprintf macros shall be defined and the corresponding fscanf macros shall be defined unless the implementation does not have a suitable fscanf length modifier for the type.
#include <inttypes.h>
#include <wchar.h>
int main(void)
{
uintmax_t i = UINTMAX_MAX; // this type always exists
wprintf(L"The largest integer value is %020"
PRIxMAX "\n", i);
return 0;
}
7.8.2 Functions for greatest-width integer types
7.8.2.1 The imaxabs function
Synopsis
#include <inttypes.h>
intmax_t imaxabs(intmax_t j);
Description
The imaxabs function computes the absolute value of an integer j. If the result cannot be represented, the behavior is undefined.193)
Returns
The imaxabs function returns the absolute value.
7.8.2.2 The imaxdiv function
Synopsis
#include <inttypes.h>
imaxdiv_t imaxdiv(intmax_t numer, intmax_t denom);
Description
The imaxdiv function computes numer / denom and numer % denom in a single operation.
Returns
The imaxdiv function returns a structure of type imaxdiv_t comprising both the quotient and the remainder. The structure shall contain (in either order) the members quot (the quotient) and rem (the remainder), each of which has type intmax_t. If either part of the result cannot be represented, the behavior is undefined.
7.8.2.3 The strtoimax and strtoumax functions
Synopsis
#include <inttypes.h>
intmax_t strtoimax(const char * restrict nptr,
char ** restrict endptr, int base);
uintmax_t strtoumax(const char * restrict nptr,
char ** restrict endptr, int base);
Description
The strtoimax and strtoumax functions are equivalent to the strtol, strtoll, strtoul, and strtoull functions, except that the initial portion of the string is converted to intmax_t and uintmax_t representation, respectively.
Returns
The strtoimax and strtoumax functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value is outside the range of representable values, INTMAX_MAX, INTMAX_MIN, or UINTMAX_MAX is returned (according to the return type and sign of the value, if any), and the value of the macro ERANGE is stored in errno. Forward references: the strtol, strtoll, strtoul, and strtoull functions ( 7.20.1.4 The strtol, strtoll, strtoul, and strtoull functions ).
7.8.2.4 The wcstoimax and wcstoumax functions
Synopsis
#include <stddef.h> // for wchar_t
#include <inttypes.h>
intmax_t wcstoimax(const wchar_t * restrict nptr,
wchar_t ** restrict endptr, int base);
uintmax_t wcstoumax(const wchar_t * restrict nptr,
wchar_t ** restrict endptr, int base);
Description
The wcstoimax and wcstoumax functions are equivalent to the wcstol, wcstoll, wcstoul, and wcstoull functions except that the initial portion of the wide string is converted to intmax_t and uintmax_t representation, respectively.
Returns
The wcstoimax function returns the converted value, if any. If no conversion could be performed, zero is returned. If the correct value is outside the range of representable values, INTMAX_MAX, INTMAX_MIN, or UINTMAX_MAX is returned (according to the return type and sign of the value, if any), and the value of the macro ERANGE is stored in errno. Forward references: the wcstol, wcstoll, wcstoul, and wcstoull functions ( 7.24.4.1.2 The wcstol, wcstoll, wcstoul, and wcstoull functions ).
7.9 Alternative spellings <iso646.h>
The header <iso646.h> defines the following eleven macros (on the left) that expand to the corresponding tokens (on the right):
and &&
and_eq &=
bitand &
bitor |
compl ~
not !
not_eq !=
or ||
or_eq |=
xor ^
xor_eq ^=
7.10 Sizes of integer types <limits.h>
The header <limits.h> defines several macros that expand to various limits and parameters of the standard integer types.
The macros, their meanings, and the constraints (or restrictions) on their values are listed in 5.2.4.2.1.
7.11 Localization <locale.h>
The header <locale.h> declares two functions, one type, and defines several macros.
The type is struct lconv which contains members related to the formatting of numeric values. The structure shall contain at least the following members, in any order. The semantics of the members and their normal ranges are explained in 7.11.2.1. In the "C" locale, the members shall have the values specified in the comments.
char *decimal_point; // "."
char *thousands_sep; // ""
char *grouping; // ""
char *mon_decimal_point; // ""
char *mon_thousands_sep; // ""
char *mon_grouping; // ""
char *positive_sign; // ""
char *negative_sign; // ""
char *currency_symbol; // ""
char frac_digits; // CHAR_MAX
char p_cs_precedes; // CHAR_MAX
char n_cs_precedes; // CHAR_MAX
char p_sep_by_space; // CHAR_MAX
char n_sep_by_space; // CHAR_MAX
char p_sign_posn; // CHAR_MAX
char n_sign_posn; // CHAR_MAX
char *int_curr_symbol; // ""
char int_frac_digits; // CHAR_MAX
char int_p_cs_precedes; // CHAR_MAX
char int_n_cs_precedes; // CHAR_MAX
char int_p_sep_by_space; // CHAR_MAX
char int_n_sep_by_space; // CHAR_MAX
char int_p_sign_posn; // CHAR_MAX
char int_n_sign_posn; // CHAR_MAX
The macros defined are NULL (described in 7.17 Common definitions <stddef.h> ); and
LC_ALL
LC_COLLATE
LC_CTYPE
LC_MONETARY
LC_NUMERIC
LC_TIME
which expand to integer constant expressions with distinct values, suitable for use as the first argument to the setlocale function.194) Additional macro definitions, beginning with the characters LC_ and an uppercase letter, [195] may also be specified by the implementation.
7.11.1 Locale control
7.11.1.1 The setlocale function
Synopsis
#include <locale.h>
char *setlocale(int category, const char *locale);
Description
The setlocale function selects the appropriate portion of the program’s locale as specified by the category and locale arguments. The setlocale function may be used to change or query the program’s entire current locale or portions thereof. The value LC_ALL for category names the program’s entire locale; the other values for category name only a portion of the program’s locale. LC_COLLATE affects the behavior of the strcoll and strxfrm functions. LC_CTYPE affects the behavior of the character handling functions [196] and the multibyte and wide character functions. LC_MONETARY affects the monetary formatting information returned by the localeconv function. LC_NUMERIC affects the decimal-point character for the formatted input/output functions and the string conversion functions, as well as the nonmonetary formatting information returned by the localeconv function. LC_TIME affects the behavior of the strftime and wcsftime functions.
A value of "C" for locale specifies the minimal environment for C translation; a value of "" for locale specifies the locale-specific native environment. Other implementation-defined strings may be passed as the second argument to setlocale.
At program startup, the equivalent of
setlocale(LC_ALL, "C");
is executed.
The implementation shall behave as if no library function calls the setlocale function.
Returns
If a pointer to a string is given for locale and the selection can be honored, the setlocale function returns a pointer to the string associated with the specified category for the new locale. If the selection cannot be honored, the setlocale function returns a null pointer and the program’s locale is not changed.
A null pointer for locale causes the setlocale function to return a pointer to the string associated with the category for the program’s current locale; the program’s locale is not changed.197)
The pointer to string returned by the setlocale function is such that a subsequent call with that string value and its associated category will restore that part of the program’s locale. The string pointed to shall not be modified by the program, but may be overwritten by a subsequent call to the setlocale function. Forward references: formatted input/output functions ( 7.19.6 Formatted input/output functions ), multibyte/wide character conversion functions ( 7.20.7 Multibyte/wide character conversion functions ), multibyte/wide string conversion functions ( 7.20.8 Multibyte/wide string conversion functions ), numeric conversion functions ( 7.20.1 Numeric conversion functions ), the strcoll function ( 7.21.4.3 The strcoll function ), the strftime function ( 7.23.3.5 The strftime function ), the strxfrm function ( 7.21.4.5 The strxfrm function ).
7.11.2 Numeric formatting convention inquiry
7.11.2.1 The localeconv function
Synopsis
#include <locale.h>
struct lconv *localeconv(void);
Description
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 members of the structure with type char * are pointers to strings, any of which (except decimal_point) can point to "", to indicate that the value is not available in the current locale or is of zero length. Apart from grouping and mon_grouping, the strings shall start and end in the initial shift state. The members with type char are nonnegative numbers, any of which can be CHAR_MAX to indicate that the value is not available in the current locale. The members include the following:
- char *decimal_point
- The decimal-point character used to format nonmonetary quantities.
- char *thousands_sep
- The character used to separate groups of digits before the decimal-point character in formatted nonmonetary quantities.
- char *grouping
- A string whose elements indicate the size of each group of digits in formatted nonmonetary quantities.
- char *mon_decimal_point
- The decimal-point used to format monetary quantities.
- char *mon_thousands_sep
- The separator for groups of digits before the decimal-point in formatted monetary quantities.
- char *mon_grouping
- A string whose elements indicate the size of each group of digits in formatted monetary quantities.
- char *positive_sign
- The string used to indicate a nonnegative-valued formatted monetary quantity.
- char *negative_sign
- The string used to indicate a negative-valued formatted monetary quantity.
- char *currency_symbol
- The local currency symbol applicable to the current locale.
- char frac_digits
- The number of fractional digits (those after the decimal-point) to be displayed in a locally formatted monetary quantity.
- char p_cs_precedes
- Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the value for a nonnegative locally formatted monetary quantity.
- char n_cs_precedes
- Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the value for a negative locally formatted monetary quantity.
- char p_sep_by_space
- Set to a value indicating the separation of the currency_symbol, the sign string, and the value for a nonnegative locally formatted monetary quantity.
- char n_sep_by_space
- Set to a value indicating the separation of the currency_symbol, the sign string, and the value for a negative locally formatted monetary quantity.
- char p_sign_posn
- Set to a value indicating the positioning of the positive_sign for a nonnegative locally formatted monetary quantity.
- char n_sign_posn
- Set to a value indicating the positioning of the negative_sign for a negative locally formatted monetary quantity.
- char *int_curr_symbol
- The international currency symbol applicable to the current locale. The first three characters contain the alphabetic international currency symbol in accordance with those specified in ISO 4217. The fourth character (immediately preceding the null character) is the character used to separate the international currency symbol from the monetary quantity.
- char int_frac_digits
- The number of fractional digits (those after the decimal-point) to be displayed in an internationally formatted monetary quantity.
- char int_p_cs_precedes
- Set to 1 or 0 if the int_curr_symbol respectively precedes or succeeds the value for a nonnegative internationally formatted monetary quantity.
- char int_n_cs_precedes
- Set to 1 or 0 if the int_curr_symbol respectively precedes or succeeds the value for a negative internationally formatted monetary quantity.
- char int_p_sep_by_space
- Set to a value indicating the separation of the int_curr_symbol, the sign string, and the value for a nonnegative internationally formatted monetary quantity.
- char int_n_sep_by_space
- Set to a value indicating the separation of the int_curr_symbol, the sign string, and the value for a negative internationally formatted monetary quantity.
- char int_p_sign_posn
- Set to a value indicating the positioning of the positive_sign for a nonnegative internationally formatted monetary quantity.
- char int_n_sign_posn
- Set to a value indicating the positioning of the negative_sign for a negative internationally formatted monetary quantity.
The elements of grouping and mon_grouping are interpreted according to the following:
- CHAR_MAX
- No further grouping is to be performed.
- 0
- The previous element is to be repeatedly used for the remainder of the digits.
- other
- The integer value is the number of digits that compose the current group. The next element is examined to determine the size of the next group of digits before the current group.
The values of p_sep_by_space, n_sep_by_space, int_p_sep_by_space, and int_n_sep_by_space are interpreted according to the following:
- 0
- No space separates the currency symbol and value.
- 1
- If the currency symbol and sign string are adjacent, a space separates them from the value; otherwise, a space separates the currency symbol from the value.
- 2
- If the currency symbol and sign string are adjacent, a space separates them; otherwise, a space separates the sign string from the value. For int_p_sep_by_space and int_n_sep_by_space, the fourth character of int_curr_symbol is used instead of a space.
The values of p_sign_posn, n_sign_posn, int_p_sign_posn, and int_n_sign_posn are interpreted according to the following:
- 0
- Parentheses surround the quantity and currency symbol.
- 1
- The sign string precedes the quantity and currency symbol.
- 2
- The sign string succeeds the quantity and currency symbol.
- 3
- The sign string immediately precedes the currency symbol.
- 4
- The sign string immediately succeeds the currency symbol.
The implementation shall behave as if no library function calls the localeconv function.
Returns
The localeconv function returns a pointer to the filled-in object. The structure pointed to by the return value shall not be modified by the program, but may be overwritten by a subsequent call to the localeconv function. In addition, calls to the setlocale function with categories LC_ALL, LC_MONETARY, or LC_NUMERIC may overwrite the contents of the structure.
EXAMPLE 1 The following table illustrates rules which may well be used by four countries to format monetary quantities.
Local format International format
Country Positive Negative Positive Negative
Country1 1.234,56 mk -1.234,56 mk FIM 1.234,56 FIM -1.234,56
Country2 L.1.234 -L.1.234 ITL 1.234 -ITL 1.234
Country3 ƒ 1.234,56 ƒ -1.234,56 NLG 1.234,56 NLG -1.234,56
Country4 SFrs.1,234.56 SFrs.1,234.56C CHF 1,234.56 CHF 1,234.56C
For these four countries, the respective values for the monetary members of the structure returned by localeconv could be:
Country1 Country2 Country3 Country4
mon_decimal_point "," "" "," "."
mon_thousands_sep "." "." "." ","
mon_grouping "\3" "\3" "\3" "\3"
positive_sign "" "" "" ""
negative_sign "-" "-" "-" "C"
currency_symbol "mk" "L." "\u0192" "SFrs."
frac_digits 2 0 2 2
p_cs_precedes 0 1 1 1
n_cs_precedes 0 1 1 1
p_sep_by_space 1 0 1 0
n_sep_by_space 1 0 2 0
p_sign_posn 1 1 1 1
n_sign_posn 1 1 4 2
int_curr_symbol "FIM " "ITL " "NLG " "CHF "
int_frac_digits 2 0 2 2
int_p_cs_precedes 1 1 1 1
int_n_cs_precedes 1 1 1 1
int_p_sep_by_space 1 1 1 1
int_n_sep_by_space 2 1 2 1
int_p_sign_posn 1 1 1 1
int_n_sign_posn 4 1 4 2
EXAMPLE 2 The following table illustrates how the cs_precedes, sep_by_space, and sign_posn members affect the formatted value. p_sep_by_space
p_cs_precedes p_sign_posn 0 1 2
0 0 (1.25$) (1.25 $) (1.25$)
1 +1.25$ +1.25 $ + 1.25$
2 1.25$+ 1.25 $+ 1.25$ +
3 1.25+$ 1.25 +$ 1.25+ $
4 1.25$+ 1.25 $+ 1.25$ +
1 0 ($1.25) ($ 1.25) ($1.25)
1 +$1.25 +$ 1.25 + $1.25
2 $1.25+ $ 1.25+ $1.25 +
3 +$1.25 +$ 1.25 + $1.25
4 $+1.25 $+ 1.25 $ +1.25
7.12 Mathematics <math.h>
The header <math.h> declares two types and many mathematical functions and defines several macros. Most synopses specify a family of functions consisting of a principal function with one or more double parameters, a double return value, or both; and other functions with the same name but with f and l suffixes, which are corresponding functions with float and long double parameters, return values, or both.198) Integer arithmetic functions and conversion functions are discussed later.
The types float_t double_t are floating types at least as wide as float and double, respectively, and such that double_t is at least as wide as float_t. If FLT_EVAL_METHOD equals 0, float_t and double_t are float and double, respectively; if FLT_EVAL_METHOD equals 1, they are both double; if FLT_EVAL_METHOD equals 2, they are both long double; and for other values of FLT_EVAL_METHOD, they are otherwise implementation-defined.199)
The macro
HUGE_VAL
expands to a positive double constant expression, not necessarily representable as a float. The macros
HUGE_VALF
HUGE_VALL
are respectively float and long double analogs of HUGE_VAL.200)
The macro
INFINITY
expands to a constant expression of type float representing positive or unsigned infinity, if available; else to a positive constant of type float that overflows at translation time.201)
The macro
NAN
is defined if and only if the implementation supports quiet NaNs for the float type. It expands to a constant expression of type float representing a quiet NaN.
The number classification macros
FP_INFINITE
FP_NAN
FP_NORMAL
FP_SUBNORMAL
FP_ZERO
represent the mutually exclusive kinds of floating-point values. They expand to integer constant expressions with distinct values. Additional implementation-defined floating-point classifications, with macro definitions beginning with FP_ and an uppercase letter, may also be specified by the implementation.
The macro
FP_FAST_FMA
is optionally defined. If defined, it indicates that the fma function generally executes about as fast as, or faster than, a multiply and an add of double operands.202) The macros
FP_FAST_FMAF
FP_FAST_FMAL
are, respectively, float and long double analogs of FP_FAST_FMA. If defined, these macros expand to the integer constant 1.
The macros
FP_ILOGB0
FP_ILOGBNAN
expand to integer constant expressions whose values are returned by ilogb(x) if x is zero or NaN, respectively. The value of FP_ILOGB0 shall be either INT_MIN or -INT_MAX. The value of FP_ILOGBNAN shall be either INT_MAX or INT_MIN.
The macros MATH_ERRNO MATH_ERREXCEPT expand to the integer constants 1 and 2, respectively; the macro math_errhandling expands to an expression that has type int and the value MATH_ERRNO, MATH_ERREXCEPT, or the bitwise OR of both. The value of math_errhandling is constant for the duration of the program. It is unspecified whether math_errhandling is a macro or an identifier with external linkage. If a macro definition is suppressed or a program defines an identifier with the name
math_errhandling, the behavior is undefined. If the expression
math_errhandling & MATH_ERREXCEPT can be nonzero, the implementation shall define the macros FE_DIVBYZERO, FE_INVALID, and FE_OVERFLOW in <fenv.h>.
7.12.1 Treatment of error conditions
The behavior of each of the functions in <math.h> is specified for all representable values of its input arguments, except where stated otherwise. Each function shall execute as if it were a single operation without generating any externally visible exceptional conditions.
For all functions, a domain error occurs if an input argument is outside the domain over which the mathematical function is defined. The description of each function lists any required domain errors; an implementation may define additional domain errors, provided that such errors are consistent with the mathematical definition of the function.203) On a domain error, the function returns an implementation-defined value; if the integer expression math_errhandling & MATH_ERRNO is nonzero, the integer expression errno acquires the value EDOM; if the integer expression math_errhandling & MATH_ERREXCEPT is nonzero, the ‘‘invalid’’ floating-point exception is raised.
Similarly, a range error occurs if the mathematical result of the function cannot be represented in an object of the specified type, due to extreme magnitude.
A floating result overflows if the magnitude of the mathematical result is finite but so large that the mathematical result cannot be represented without extraordinary roundoff error in an object of the specified type. If a floating result overflows and default rounding is in effect, or if the mathematical result is an exact infinity from finite arguments (for example log( 0.0 )), then the function returns the value of the macro HUGE_VAL, HUGE_VALF, or HUGE_VALL according to the return type, with the same sign as the correct value of the function; if the integer expression math_errhandling & MATH_ERRNO is nonzero, the integer expression errno acquires the value ERANGE; if the integer expression math_errhandling & MATH_ERREXCEPT is nonzero, the ‘‘divide-by-zero’’ floating-point exception is raised if the mathematical result is an exact infinity and the ‘‘overflow’’ floating-point exception is raised otherwise.
The result underflows if the magnitude of the mathematical result is so small that the mathematical result cannot be represented, without extraordinary roundoff error, in an object of the specified type.204) If the result underflows, the function returns an implementation-defined value whose magnitude is no greater than the smallest normalized positive number in the specified type; if the integer expression math_errhandling & MATH_ERRNO is nonzero, whether errno acquires the
value ERANGE is implementation-defined; if the integer expression
math_errhandling & MATH_ERREXCEPT is nonzero, whether the ‘‘underflow’’ floating-point exception is raised is implementation-defined.
7.12.2 The FP_CONTRACT pragma
Synopsis
#include <math.h>
#pragma STDC FP_CONTRACT on-off-switch
Description
The FP_CONTRACT pragma can be used to allow (if the state is ‘‘on’’) or disallow (if the state is ‘‘off’’) the implementation to contract expressions ( 6.5 ). Each pragma can occur either outside external declarations or preceding all explicit declarations and statements inside a compound statement. When outside external declarations, the pragma takes effect from its occurrence until another FP_CONTRACT pragma is encountered, or until the end of the translation unit. When inside a compound statement, the pragma takes effect from its occurrence until another FP_CONTRACT pragma is encountered (including within a nested compound statement), or until the end of the compound statement; at the end of a compound statement the state for the pragma is restored to its condition just before the compound statement. If this pragma is used in any other context, the behavior is undefined. The default state (‘‘on’’ or ‘‘off’’) for the pragma is implementation-defined.
7.12.3 Classification macros
In the synopses in this subclause, real-floating indicates that the argument shall be an expression of real floating type.
7.12.3.1 The fpclassify macro
Synopsis
#include <math.h>
int fpclassify(real-floating x);
Description
The fpclassify macro classifies its argument value as NaN, infinite, normal, subnormal, zero, or into another implementation-defined category. First, an argument represented in a format wider than its semantic type is converted to its semantic type. Then classification is based on the type of the argument.205)
Returns
The fpclassify macro returns the value of the number classification macro appropriate to the value of its argument.
The fpclassify macro might be implemented in terms of ordinary functions as
#define fpclassify(x) \
((sizeof (x) == sizeof (float)) ? _ _fpclassifyf(x) : \
(sizeof (x) == sizeof (double)) ? _ _fpclassifyd(x) : \
_ _fpclassifyl(x))
7.12.3.2 The isfinite macro
Synopsis
#include <math.h>
int isfinite(real-floating x);
Description
The isfinite macro determines whether its argument has a finite value (zero, subnormal, or normal, and not infinite or NaN). First, an argument represented in a format wider than its semantic type is converted to its semantic type. Then determination is based on the type of the argument.
Returns
The isfinite macro returns a nonzero value if and only if its argument has a finite value.
7.12.3.3 The isinf macro
Synopsis
#include <math.h>
int isinf(real-floating x);
Description
The isinf macro determines whether its argument value is an infinity (positive or negative). First, an argument represented in a format wider than its semantic type is converted to its semantic type. Then determination is based on the type of the argument.
Returns
The isinf macro returns a nonzero value if and only if its argument has an infinite value.
7.12.3.4 The isnan macro
Synopsis
#include <math.h>
int isnan(real-floating x);
Description
The isnan macro determines whether its argument value is a NaN. First, an argument represented in a format wider than its semantic type is converted to its semantic type. Then determination is based on the type of the argument.206)
Returns
The isnan macro returns a nonzero value if and only if its argument has a NaN value.
7.12.3.5 The isnormal macro
Synopsis
#include <math.h>
int isnormal(real-floating x);
Description
The isnormal macro determines whether its argument value is normal (neither zero, subnormal, infinite, nor NaN). First, an argument represented in a format wider than its semantic type is converted to its semantic type. Then determination is based on the type of the argument.
Returns
The isnormal macro returns a nonzero value if and only if its argument has a normal value.
7.12.3.6 The signbit macro
Synopsis
#include <math.h>
int signbit(real-floating x);
Description
The signbit macro determines whether the sign of its argument value is negative.207)
Returns
The signbit macro returns a nonzero value if and only if the sign of its argument value is negative.
7.12.4 Trigonometric functions
7.12.4.1 The acos functions
Synopsis
#include <math.h>
double acos(double x);
float acosf(float x);
long double acosl(long double x);
Description
The acos functions compute the principal value of the arc cosine of x. A domain error occurs for arguments not in the interval [−1, +1].
Returns
The acos functions return arccos x in the interval [0, π ] radians.
7.12.4.2 The asin functions
Synopsis
#include <math.h>
double asin(double x);
float asinf(float x);
long double asinl(long double x);
Description
The asin functions compute the principal value of the arc sine of x. A domain error occurs for arguments not in the interval [−1, +1].
Returns
The asin functions return arcsin x in the interval [−π /2, +π /2] radians.
7.12.4.3 The atan functions
Synopsis
#include <math.h>
double atan(double x);
float atanf(float x);
long double atanl(long double x);
Description
The atan functions compute the principal value of the arc tangent of x.
Returns
The atan functions return arctan x in the interval [−π /2, +π /2] radians.
7.12.4.4 The atan2 functions
Synopsis
#include <math.h>
double atan2(double y, double x);
float atan2f(float y, float x);
long double atan2l(long double y, long double x);
Description
The atan2 functions compute the value of the arc tangent of y/x, using the signs of both arguments to determine the quadrant of the return value. A domain error may occur if both arguments are zero.
Returns
The atan2 functions return arctan y/x in the interval [−π , +π ] radians.
7.12.4.5 The cos functions
Synopsis
#include <math.h>
double cos(double x);
float cosf(float x);
long double cosl(long double x);
Description
The cos functions compute the cosine of x (measured in radians).
Returns
The cos functions return cos x.
7.12.4.6 The sin functions
Synopsis
#include <math.h>
double sin(double x);
float sinf(float x);
long double sinl(long double x);
Description
The sin functions compute the sine of x (measured in radians).
Returns
The sin functions return sin x.
7.12.4.7 The tan functions
Synopsis
#include <math.h>
double tan(double x);
float tanf(float x);
long double tanl(long double x);
Description
The tan functions return the tangent of x (measured in radians).
Returns
The tan functions return tan x.
7.12.5 Hyperbolic functions
7.12.5.1 The acosh functions
Synopsis
#include <math.h>
double acosh(double x);
float acoshf(float x);
long double acoshl(long double x);
Description
The acosh functions compute the (nonnegative) arc hyperbolic cosine of x. A domain error occurs for arguments less than 1.
Returns
The acosh functions return arcosh x in the interval [0, +∞].
7.12.5.2 The asinh functions
Synopsis
#include <math.h>
double asinh(double x);
float asinhf(float x);
long double asinhl(long double x);
Description
The asinh functions compute the arc hyperbolic sine of x.
Returns
The asinh functions return arsinh x.
7.12.5.3 The atanh functions
Synopsis
#include <math.h>
double atanh(double x);
float atanhf(float x);
long double atanhl(long double x);
Description
The atanh functions compute the arc hyperbolic tangent of x. A domain error occurs for arguments not in the interval [−1, +1]. A range error may occur if the argument equals −1 or +1.
Returns
The atanh functions return artanh x.
7.12.5.4 The cosh functions
Synopsis
#include <math.h>
double cosh(double x);
float coshf(float x);
long double coshl(long double x);
Description
The cosh functions compute the hyperbolic cosine of x. A range error occurs if the magnitude of x is too large.
Returns
The cosh functions return cosh x.
7.12.5.5 The sinh functions
Synopsis
#include <math.h>
double sinh(double x);
float sinhf(float x);
long double sinhl(long double x);
Description
The sinh functions compute the hyperbolic sine of x. A range error occurs if the magnitude of x is too large.
Returns
The sinh functions return sinh x.
7.12.5.6 The tanh functions
Synopsis
#include <math.h>
double tanh(double x);
float tanhf(float x);
long double tanhl(long double x);
Description
The tanh functions compute the hyperbolic tangent of x.
Returns
The tanh functions return tanh x.
7.12.6 Exponential and logarithmic functions
7.12.6.1 The exp functions
Synopsis
#include <math.h>
double exp(double x);
float expf(float x);
long double expl(long double x);
Description
The exp functions compute the base-e exponential of x. A range error occurs if the magnitude of x is too large.
Returns
The exp functions return
7.12.6.2 The exp2 functions
Synopsis
#include <math.h>
double exp2(double x);
float exp2f(float x);
long double exp2l(long double x);
Description
The exp2 functions compute the base-2 exponential of x. A range error occurs if the magnitude of x is too large.
Returns
The exp2 functions return
7.12.6.3 The expm1 functions
Synopsis
#include <math.h>
double expm1(double x);
float expm1f(float x);
long double expm1l(long double x);
Description
The expm1 functions compute the base-e exponential of the argument, minus 1. A range error occurs if x is too large.208)
Returns
The expm1 functions return
7.12.6.4 The frexp functions
Synopsis
#include <math.h>
double frexp(double value, int *exp);
float frexpf(float value, int *exp);
long double frexpl(long double value, int *exp);
Description
The frexp functions break a floating-point number into a normalized fraction and an integral power of 2. They store the integer in the int object pointed to by exp.
Returns
If value is not a floating-point number, the results are unspecified. Otherwise, the frexp functions return the value x, such that x has a magnitude in the interval [1/2, 1) or zero, and value equals x × 2*exp . If value is zero, both parts of the result are zero.
7.12.6.5 The ilogb functions
Synopsis
#include <math.h>
int ilogb(double x);
int ilogbf(float x);
int ilogbl(long double x);
Description
The ilogb functions extract the exponent of x as a signed int value. If x is zero they compute the value FP_ILOGB0; if x is infinite they compute the value INT_MAX; if x is a NaN they compute the value FP_ILOGBNAN; otherwise, they are equivalent to calling the corresponding logb function and casting the returned value to type int. A domain error or range error may occur if x is zero, infinite, or NaN. If the correct value is outside the range of the return type, the numeric result is unspecified.
Returns
The ilogb functions return the exponent of x as a signed int value. Forward references: the logb functions ( 7.12.6.11 The logb functions ).
7.12.6.6 The ldexp functions
Synopsis
#include <math.h>
double ldexp(double x, int exp);
float ldexpf(float x, int exp);
long double ldexpl(long double x, int exp);
Description
The ldexp functions multiply a floating-point number by an integral power of 2. A range error may occur.
Returns
The ldexp functions return
7.12.6.7 The log functions
Synopsis
#include <math.h>
double log(double x);
float logf(float x);
long double logl(long double x);
Description
The log functions compute the base-e (natural) logarithm of x. A domain error occurs if the argument is negative. A range error may occur if the argument is zero.
Returns
The log functions return
7.12.6.8 The log10 functions
Synopsis
#include <math.h>
double log10(double x);
float log10f(float x);
long double log10l(long double x);
Description
The log10 functions compute the base-10 (common) logarithm of x. A domain error occurs if the argument is negative. A range error may occur if the argument is zero.
Returns
The log10 functions return
7.12.6.9 The log1p functions
Synopsis
#include <math.h>
double log1p(double x);
float log1pf(float x);
long double log1pl(long double x);
Description
The log1p functions compute the base-e (natural) logarithm of 1 plus the argument.209) A domain error occurs if the argument is less than −1. A range error may occur if the argument equals −1.
Returns
The log1p functions return
7.12.6.10 The log2 functions
Synopsis
#include <math.h>
double log2(double x);
float log2f(float x);
long double log2l(long double x);
Description
The log2 functions compute the base-2 logarithm of x. A domain error occurs if the argument is less than zero. A range error may occur if the argument is zero.
Returns
The log2 functions return
7.12.6.11 The logb functions
Synopsis
#include <math.h>
double logb(double x);
float logbf(float x);
long double logbl(long double x);
Description
The logb functions extract the exponent of x, as a signed integer value in floating-point format. If x is subnormal it is treated as though it were normalized; thus, for positive finite x, 1 ≤ x × FLT_RADIX−logb(x) < FLT_RADIX A domain error or range error may occur if the argument is zero.
Returns
The logb functions return the signed exponent of x.
7.12.6.12 The modf functions
Synopsis
#include <math.h>
double modf(double value, double *iptr);
float modff(float value, float *iptr);
long double modfl(long double value, long double *iptr);
Description
The modf functions break the argument value into integral and fractional parts, each of which has the same type and sign as the argument. They store the integral part (in floating-point format) in the object pointed to by iptr.
Returns
The modf functions return the signed fractional part of value.
7.12.6.13 The scalbn and scalbln functions
Synopsis
#include <math.h>
double scalbn(double x, int n);
float scalbnf(float x, int n);
long double scalbnl(long double x, int n);
double scalbln(double x, long int n);
float scalblnf(float x, long int n);
long double scalblnl(long double x, long int n);
Description
The scalbn and scalbln functions compute x × FLT_RADIXn efficiently, not normally by computing FLT_RADIXn explicitly. A range error may occur.
Returns
The scalbn and scalbln functions return
7.12.7 Power and absolute-value functions
7.12.7.1 The cbrt functions
Synopsis
#include <math.h>
double cbrt(double x);
float cbrtf(float x);
long double cbrtl(long double x);
Description
The cbrt functions compute the real cube root of x.
Returns
The cbrt functions return
7.12.7.2 The fabs functions
Synopsis
#include <math.h>
double fabs(double x);
float fabsf(float x);
long double fabsl(long double x);
Description
The fabs functions compute the absolute value of a floating-point number x.
Returns
The fabs functions return
7.12.7.3 The hypot functions
Synopsis
#include <math.h>
double hypot(double x, double y);
float hypotf(float x, float y);
long double hypotl(long double x, long double y);
Description
The hypot functions compute the square root of the sum of the squares of x and y, without undue overflow or underflow. A range error may occur.
Returns
The hypot functions return
7.12.7.4 The pow functions
Synopsis
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
Description
The pow functions compute x raised to the power y. A domain error occurs if x is finite and negative and y is finite and not an integer value. A range error may occur. A domain error may occur if x is zero and y is zero. A domain error or range error may occur if x is zero and y is less than zero.
Returns
The pow functions return
7.12.7.5 The sqrt functions
Synopsis
#include <math.h>
double sqrt(double x);
float sqrtf(float x);
long double sqrtl(long double x);
Description
The sqrt functions compute the nonnegative square root of x. A domain error occurs if the argument is less than zero.
Returns
The sqrt functions return
7.12.8 Error and gamma functions
7.12.8.1 The erf functions
Synopsis
#include <math.h>
double erf(double x);
float erff(float x);
long double erfl(long double x);
Description
The erf functions compute the error function of x.
Returns
2 x
√π ∫
The erf functions return
7.12.8.2 The erfc functions
Synopsis
#include <math.h>
double erfc(double x);
float erfcf(float x);
long double erfcl(long double x);
Description
The erfc functions compute the complementary error function of x. A range error occurs if x is too large.
Returns
2 ∞
√π ∫
The erfc functions return
7.12.8.3 The lgamma functions
Synopsis
#include <math.h>
double lgamma(double x);
float lgammaf(float x);
long double lgammal(long double x);
Description
The lgamma functions compute the natural logarithm of the absolute value of gamma of x. A range error occurs if x is too large. A range error may occur if x is a negative integer or zero.
Returns
The lgamma functions return
7.12.8.4 The tgamma functions
Synopsis
#include <math.h>
double tgamma(double x);
float tgammaf(float x);
long double tgammal(long double x);
Description
The tgamma functions compute the gamma function of x. A domain error or range error may occur if x is a negative integer or zero. A range error may occur if the magnitude of x is too large or too small.
Returns
The tgamma functions return
7.12.9 Nearest integer functions
7.12.9.1 The ceil functions
Synopsis
#include <math.h>
double ceil(double x);
float ceilf(float x);
long double ceill(long double x);
Description
The ceil functions compute the smallest integer value not less than x.
Returns
The ceil functions return x, expressed as a floating-point number.
7.12.9.2 The floor functions
Synopsis
#include <math.h>
double floor(double x);
float floorf(float x);
long double floorl(long double x);
Description
The floor functions compute the largest integer value not greater than x.
Returns
The floor functions return x, expressed as a floating-point number.
7.12.9.3 The nearbyint functions
Synopsis
#include <math.h>
double nearbyint(double x);
float nearbyintf(float x);
long double nearbyintl(long double x);
Description
The nearbyint functions round their argument to an integer value in floating-point format, using the current rounding direction and without raising the ‘‘inexact’’ floating-point exception.
Returns
The nearbyint functions return the rounded integer value.
7.12.9.4 The rint functions
Synopsis
#include <math.h>
double rint(double x);
float rintf(float x);
long double rintl(long double x);
Description
The rint functions differ from the nearbyint functions ( 7.12.9.3 The nearbyint functions ) only in that the rint functions may raise the ‘‘inexact’’ floating-point exception if the result differs in value from the argument.
Returns
The rint functions return the rounded integer value.
7.12.9.5 The lrint and llrint functions
Synopsis
#include <math.h>
long int lrint(double x);
long int lrintf(float x);
long int lrintl(long double x);
long long int llrint(double x);
long long int llrintf(float x);
long long int llrintl(long double x);
Description
The lrint and llrint functions round their argument to the nearest integer value, rounding according to the current rounding direction. If the rounded value is outside the range of the return type, the numeric result is unspecified and a domain error or range
error may occur. ∗
Returns
The lrint and llrint functions return the rounded integer value.
7.12.9.6 The round functions
Synopsis
#include <math.h>
double round(double x);
float roundf(float x);
long double roundl(long double x);
Description
The round functions round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction.
Returns
The round functions return the rounded integer value.
7.12.9.7 The lround and llround functions
Synopsis
#include <math.h>
long int lround(double x);
long int lroundf(float x);
long int lroundl(long double x);
long long int llround(double x);
long long int llroundf(float x);
long long int llroundl(long double x);
Description
The lround and llround functions round their argument to the nearest integer value, rounding halfway cases away from zero, regardless of the current rounding direction. If the rounded value is outside the range of the return type, the numeric result is unspecified and a domain error or range error may occur.
Returns
The lround and llround functions return the rounded integer value.
7.12.9.8 The trunc functions
Synopsis
#include <math.h>
double trunc(double x);
float truncf(float x);
long double truncl(long double x);
Description
The trunc functions round their argument to the integer value, in floating format, nearest to but no larger in magnitude than the argument.
Returns
The trunc functions return the truncated integer value.
7.12.10 Remainder functions
7.12.10.1 The fmod functions
Synopsis
#include <math.h>
double fmod(double x, double y);
float fmodf(float x, float y);
long double fmodl(long double x, long double y);
Description
The fmod functions compute the floating-point remainder of x/y.
Returns
The fmod functions return the value x − ny, for some integer n such that, if y is nonzero, the result has the same sign as x and magnitude less than the magnitude of y. If y is zero, whether a domain error occurs or the fmod functions return zero is implementation-defined.
7.12.10.2 The remainder functions
Synopsis
#include <math.h>
double remainder(double x, double y);
float remainderf(float x, float y);
long double remainderl(long double x, long double y);
Description
The remainder functions compute the remainder x REM y required by IEC 60559.210 )
Returns
The remainder functions return x REM y. If y is zero, whether a domain error occurs or the functions return zero is implementation defined.
7.12.10.3 The remquo functions
Synopsis
#include <math.h>
double remquo(double x, double y, int *quo);
float remquof(float x, float y, int *quo);
long double remquol(long double x, long double y,
int *quo);
Description
The remquo functions compute the same remainder as the remainder functions. In the object pointed to by quo they store a value whose sign is the sign of x/y and whose magnitude is congruent modulo 2n to the magnitude of the integral quotient of x/y, where n is an implementation-defined integer greater than or equal to 3.
Returns
The remquo functions return x REM y. If y is zero, the value stored in the object pointed to by quo is unspecified and whether a domain error occurs or the functions return zero is implementation defined.
7.12.11 Manipulation functions
7.12.11.1 The copysign functions
Synopsis
#include <math.h>
double copysign(double x, double y);
float copysignf(float x, float y);
long double copysignl(long double x, long double y);
Description
The copysign functions produce a value with the magnitude of x and the sign of y. They produce a NaN (with the sign of y) if x is a NaN. On implementations that represent a signed zero but do not treat negative zero consistently in arithmetic operations, the copysign functions regard the sign of zero as positive.
Returns
The copysign functions return a value with the magnitude of x and the sign of y.
7.12.11.2 The nan functions
Synopsis
#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);
Description
The call nan("n-char-sequence") is equivalent to strtod("NAN(n-char-sequence)", (char**) NULL); the call nan("") is equivalent to strtod("NAN()", (char**) NULL). If tagp does not point to an n-char sequence or an empty string, the call is equivalent to strtod("NAN", (char**) NULL). Calls to nanf and nanl are equivalent to the corresponding calls to strtof and strtold.
Returns
The nan functions return a quiet NaN, if available, with content indicated through tagp. If the implementation does not support quiet NaNs, the functions return zero. Forward references: the strtod, strtof, and strtold functions ( 7.20.1.3 The strtod, strtof, and strtold functions ).
7.12.11.3 The nextafter functions
Synopsis
#include <math.h>
double nextafter(double x, double y);
float nextafterf(float x, float y);
long double nextafterl(long double x, long double y);
Description
The nextafter functions determine the next representable value, in the type of the function, after x in the direction of y, where x and y are first converted to the type of the function.211) The nextafter functions return y if x equals y. A range error may occur if the magnitude of x is the largest finite value representable in the type and the result is infinite or not representable in the type.
Returns
The nextafter functions return the next representable value in the specified format after x in the direction of y.
7.12.11.4 The nexttoward functions
Synopsis
#include <math.h>
double nexttoward(double x, long double y);
float nexttowardf(float x, long double y);
long double nexttowardl(long double x, long double y);
Description
The nexttoward functions are equivalent to the nextafter functions except that the second parameter has type long double and the functions return y converted to the type of the function if x equals y.212)
7.12.12 Maximum, minimum, and positive difference functions
7.12.12.1 The fdim functions
Synopsis
#include <math.h>
double fdim(double x, double y);
float fdimf(float x, float y);
long double fdiml(long double x, long double y);
Description
The fdim functions determine the positive difference between their arguments: x − y if x > y
+0 if x ≤ y
A range error may occur.
Returns
The fdim functions return the positive difference value.
7.12.12.2 The fmax functions
Synopsis
#include <math.h>
double fmax(double x, double y);
float fmaxf(float x, float y);
long double fmaxl(long double x, long double y);
Description
The fmax functions determine the maximum numeric value of their arguments.213)
Returns
The fmax functions return the maximum numeric value of their arguments.
7.12.12.3 The fmin functions
Synopsis
#include <math.h>
double fmin(double x, double y);
float fminf(float x, float y);
long double fminl(long double x, long double y);
Description
The fmin functions determine the minimum numeric value of their arguments.214)
Returns
The fmin functions return the minimum numeric value of their arguments.
7.12.13 Floating multiply-add
7.12.13.1 The fma functions
Synopsis
#include <math.h>
double fma(double x, double y, double z);
float fmaf(float x, float y, float z);
long double fmal(long double x, long double y,
long double z);
Description
The fma functions compute (x × y) + z, rounded as one ternary operation: they compute the value (as if) to infinite precision and round once to the result format, according to the current rounding mode. A range error may occur.
Returns
The fma functions return (x × y) + z, rounded as one ternary operation.
7.12.14 Comparison macros
The relational and equality operators support the usual mathematical relationships between numeric values. For any ordered pair of numeric values exactly one of the relationships — less, greater, and equal — is true. Relational operators may raise the ‘‘invalid’’ floating-point exception when argument values are NaNs. For a NaN and a numeric value, or for two NaNs, just the unordered relationship is true.215) The following subclauses provide macros that are quiet (non floating-point exception raising) versions of the relational operators, and other comparison macros that facilitate writing efficient code that accounts for NaNs without suffering the ‘‘invalid’’ floating-point exception. In the synopses in this subclause, real-floating indicates that the argument shall be an expression of real floating type.
7.12.14.1 The isgreater macro
Synopsis
#include <math.h>
int isgreater(real-floating x, real-floating y);
Description
The isgreater macro determines whether its first argument is greater than its second argument. The value of isgreater(x, y) is always equal to (x) > (y); however, unlike (x) > (y), isgreater(x, y) does not raise the ‘‘invalid’’ floating-point exception when x and y are unordered.
Returns
The isgreater macro returns the value of (x) > (y).
7.12.14.2 The isgreaterequal macro
Synopsis
#include <math.h>
int isgreaterequal(real-floating x, real-floating y);
Description
The isgreaterequal macro determines whether its first argument is greater than or
equal to its second argument. The value of isgreaterequal(x, y) is always equal
to (x) >= (y); however, unlike (x) >= (y), isgreaterequal(x, y) does
not raise the ‘‘invalid’’ floating-point exception when x and y are unordered.
Returns
The isgreaterequal macro returns the value of (x) >= (y).
7.12.14.3 The isless macro
Synopsis
#include <math.h>
int isless(real-floating x, real-floating y);
Description
The isless macro determines whether its first argument is less than its second argument. The value of isless(x, y) is always equal to (x) < (y); however, unlike (x) < (y), isless(x, y) does not raise the ‘‘invalid’’ floating-point exception when x and y are unordered.
Returns
The isless macro returns the value of (x) < (y).
7.12.14.4 The islessequal macro
Synopsis
#include <math.h>
int islessequal(real-floating x, real-floating y);
Description
The islessequal macro determines whether its first argument is less than or equal to its second argument. The value of islessequal(x, y) is always equal to (x) <= (y); however, unlike (x) <= (y), islessequal(x, y) does not raise the ‘‘invalid’’ floating-point exception when x and y are unordered.
Returns
The islessequal macro returns the value of (x) <= (y).
7.12.14.5 The islessgreater macro
Synopsis
#include <math.h>
int islessgreater(real-floating x, real-floating y);
Description
The islessgreater macro determines whether its first argument is less than or greater than its second argument. The islessgreater(x, y) macro is similar to (x) < (y) || (x) > (y); however, islessgreater(x, y) does not raise the ‘‘invalid’’ floating-point exception when x and y are unordered (nor does it evaluate x and y twice).
Returns
The islessgreater macro returns the value of (x) < (y) || (x) > (y).
7.12.14.6 The isunordered macro
Synopsis
#include <math.h>
int isunordered(real-floating x, real-floating y);
Description
The isunordered macro determines whether its arguments are unordered.
Returns
The isunordered macro returns 1 if its arguments are unordered and 0 otherwise.
7.13 Nonlocal jumps <setjmp.h>
The header <setjmp.h> defines the macro setjmp, and declares one function and one type, for bypassing the normal function call and return discipline.216)
The type declared is jmp_buf which is an array type suitable for holding the information needed to restore a calling environment. The environment of a call to the setjmp macro consists of information sufficient for a call to the longjmp function to return execution to the correct block and invocation of that block, were it called recursively. It does not include the state of the floating-point status flags, of open files, or of any other component of the abstract machine.
It is unspecified whether setjmp is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual function, or a program defines an external identifier with the name setjmp, the behavior is undefined.
7.13.1 Save calling environment
7.13.1.1 The setjmp macro
Synopsis
#include <setjmp.h>
int setjmp(jmp_buf env);
Description
The setjmp macro saves its calling environment in its jmp_buf argument for later use by the longjmp function.
Returns
If the return is from a direct invocation, the setjmp macro returns the value zero. If the return is from a call to the longjmp function, the setjmp macro returns a nonzero value. Environmental limits
An invocation of the setjmp macro shall appear only in one of the following contexts:
- the entire controlling expression of a selection or iteration statement;
- one operand of a relational or equality operator with the other operand an integer constant expression, with the resulting expression being the entire controlling expression of a selection or iteration statement;
- the operand of a unary ! operator with the resulting expression being the entire controlling expression of a selection or iteration statement; or
- the entire expression of an expression statement (possibly cast to void).
If the invocation appears in any other context, the behavior is undefined.
7.13.2 Restore calling environment
7.13.2.1 The longjmp function
Synopsis
#include <setjmp.h>
void longjmp(jmp_buf env, int val);
Description
The longjmp function restores the environment saved by the most recent invocation of the setjmp macro in the same invocation of the program with the corresponding jmp_buf argument. If there has been no such invocation, or if the function containing the invocation of the setjmp macro has terminated execution [217] in the interim, or if the invocation of the setjmp macro was within the scope of an identifier with variably modified type and execution has left that scope in the interim, the behavior is undefined.
All accessible objects have values, and all other components of the abstract machine [218] have state, as of the time the longjmp function was called, except that the values of objects of automatic storage duration that are local to the function containing the invocation of the corresponding setjmp macro that do not have volatile-qualified type and have been changed between the setjmp invocation and longjmp call are indeterminate.
Returns
After longjmp is completed, program execution continues as if the corresponding invocation of the setjmp macro had just returned the value specified by val. The longjmp function cannot cause the setjmp macro to return the value 0; if val is 0, the setjmp macro returns the value 1.
The longjmp function that returns control back to the point of the setjmp invocation might cause memory associated with a variable length array object to be squandered.
#include <setjmp.h>
jmp_buf buf;
void g(int n);
void h(int n);
int n = 6;
void f(void)
{
int x[n]; // valid: f is not terminated
setjmp(buf);
g(n);
}
void g(int n)
{
int a[n]; // a may remain allocated
h(n);
}
void h(int n)
{
int b[n]; // b may remain allocated
longjmp(buf, 2); // might cause memory loss
}
7.14 Signal handling <signal.h>
The header <signal.h> declares a type and two functions and defines several macros, for handling various signals (conditions that may be reported during program execution).
The type defined is sig_atomic_t which is the (possibly volatile-qualified) integer type of an object that can be accessed as an atomic entity, even in the presence of asynchronous interrupts.
The macros defined are SIG_DFL SIG_ERR SIG_IGN which expand to constant expressions with distinct values that have type compatible with the second argument to, and the return value of, the signal function, and whose values compare unequal to the address of any declarable function; and the following, which expand to positive integer constant expressions with type int and distinct values that are the signal numbers, each corresponding to the specified condition: SIGABRT abnormal termination, such as is initiated by the abort function
SIGFPE an erroneous arithmetic operation, such as zero divide or an operation
resulting in overflow
SIGILL detection of an invalid function image, such as an invalid instruction
SIGINT receipt of an interactive attention signal
SIGSEGV an invalid access to storage
SIGTERM a termination request sent to the program
An implementation need not generate any of these signals, except as a result of explicit calls to the raise function. Additional signals and pointers to undeclarable functions, with macro definitions beginning, respectively, with the letters SIG and an uppercase letter or with SIG_ and an uppercase letter, [219] may also be specified by the implementation. The complete set of signals, their semantics, and their default handling is implementation-defined; all signal numbers shall be positive.
7.14.1 Specify signal handling
7.14.1.1 The signal function
Synopsis
#include <signal.h>
void (*signal(int sig, void (*func)(int)))(int);
Description
The signal function chooses one of three ways in which receipt of the signal number sig is to be subsequently handled. If the value of func is SIG_DFL, default handling for that signal will occur. If the value of func is SIG_IGN, the signal will be ignored. Otherwise, func shall point to a function to be called when that signal occurs. An invocation of such a function because of a signal, or (recursively) of any further functions called by that invocation (other than functions in the standard library), is called a signal handler.
When a signal occurs and func points to a function, it is implementation-defined whether the equivalent of signal(sig, SIG_DFL); is executed or the implementation prevents some implementation-defined set of signals (at least including sig) from occurring until the current signal handling has completed; in the case of SIGILL, the implementation may alternatively define that no action is taken. Then the equivalent of (*func)(sig); is executed. If and when the function returns, if the value of sig is SIGFPE, SIGILL, SIGSEGV, or any other implementation-defined value corresponding to a computational exception, the behavior is undefined; otherwise the program will resume execution at the point it was interrupted.
If the signal occurs as the result of calling the abort or raise function, the signal handler shall not call the raise function.
If the signal occurs other than as the result of calling the abort or raise function, the behavior is undefined if the signal handler refers to any object with static storage duration other than by assigning a value to an object declared as volatile sig_atomic_t, or the signal handler calls any function in the standard library other than the abort function, the _Exit function, or the signal function with the first argument equal to the signal number corresponding to the signal that caused the invocation of the handler. Furthermore, if such a call to the signal function results in a SIG_ERR return, the value of errno is indeterminate.220)
At program startup, the equivalent of
signal(sig, SIG_IGN);
may be executed for some signals selected in an implementation-defined manner; the equivalent of
signal(sig, SIG_DFL);
is executed for all other signals defined by the implementation.
The implementation shall behave as if no library function calls the signal function.
Returns
If the request can be honored, the signal function returns the value of func for the most recent successful call to signal for the specified signal sig. Otherwise, a value of SIG_ERR is returned and a positive value is stored in errno. Forward references: the abort function ( 7.20.4.1 The abort function ), the exit function ( 7.20.4.3 The exit function ), the _Exit function ( 7.20.4.4 The _Exit function ).
7.14.2 Send signal
7.14.2.1 The raise function
Synopsis
#include <signal.h>
int raise(int sig);
Description
The raise function carries out the actions described in 7.14.1.1 The signal function for the signal sig. If a signal handler is called, the raise function shall not return until after the signal handler does.
Returns
The raise function returns zero if successful, nonzero if unsuccessful.
7.15 Variable arguments <stdarg.h>
The header <stdarg.h> declares a type and defines four macros, for advancing through a list of arguments whose number and types are not known to the called function when it is translated.
A function may be called with a variable number of arguments of varying types. As described in 6.9.1 , its parameter list contains one or more parameters. The rightmost parameter plays a special role in the access mechanism, and will be designated parmN in this description.
The type declared is va_list which is an object type suitable for holding information needed by the macros va_start, va_arg, va_end, and va_copy. If access to the varying arguments is desired, the called function shall declare an object (generally referred to as ap in this subclause) having type va_list. The object ap may be passed as an argument to another function; if that function invokes the va_arg macro with parameter ap, the value of ap in the calling function is indeterminate and shall be passed to the va_end macro prior to any further reference to ap.221)
7.15.1 Variable argument list access macros
The va_start and va_arg macros described in this subclause shall be implemented as macros, not functions. It is unspecified whether va_copy and va_end are macros or identifiers declared with external linkage. If a macro definition is suppressed in order to access an actual function, or a program defines an external identifier with the same name, the behavior is undefined. Each invocation of the va_start and va_copy macros shall be matched by a corresponding invocation of the va_end macro in the same function.
7.15.1.1 The va_arg macro
Synopsis
#include <stdarg.h>
type va_arg(va_list ap, type);
Description
The va_arg macro expands to an expression that has the specified type and the value of the next argument in the call. The parameter ap shall have been initialized by the va_start or va_copy macro (without an intervening invocation of the va_end macro for the same ap). Each invocation of the va_arg macro modifies ap so that the values of successive arguments are returned in turn. The parameter type shall be a type name specified such that the type of a pointer to an object that has the specified type can be obtained simply by postfixing a * to type. If there is no actual next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined, except for the following cases:
- one type is a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types;
- one type is pointer to void and the other is a pointer to a character type.
Returns
The first invocation of the va_arg macro after that of the va_start macro returns the value of the argument after that specified by parmN . Successive invocations return the values of the remaining arguments in succession.
7.15.1.2 The va_copy macro
Synopsis
#include <stdarg.h>
void va_copy(va_list dest, va_list src);
Description
The va_copy macro initializes dest as a copy of src, as if the va_start macro had been applied to dest followed by the same sequence of uses of the va_arg macro as had previously been used to reach the present state of src. Neither the va_copy nor va_start macro shall be invoked to reinitialize dest without an intervening invocation of the va_end macro for the same dest.
Returns
The va_copy macro returns no value.
7.15.1.3 The va_end macro
Synopsis
#include <stdarg.h>
void va_end(va_list ap);
Description
The va_end macro facilitates a normal return from the function whose variable argument list was referred to by the expansion of the va_start macro, or the function containing the expansion of the va_copy macro, that initialized the va_list ap. The va_end macro may modify ap so that it is no longer usable (without being reinitialized by the va_start or va_copy macro). If there is no corresponding invocation of the va_start or va_copy macro, or if the va_end macro is not invoked before the return, the behavior is undefined.
Returns
The va_end macro returns no value.
7.15.1.4 The va_start macro
Synopsis
#include <stdarg.h>
void va_start(va_list ap, parmN);
Description
The va_start macro shall be invoked before any access to the unnamed arguments.
The va_start macro initializes ap for subsequent use by the va_arg and va_end macros. Neither the va_start nor va_copy macro shall be invoked to reinitialize ap without an intervening invocation of the va_end macro for the same ap.
The parameter parmN is the identifier of the rightmost parameter in the variable parameter list in the function definition (the one just before the , ...). If the parameter parmN is declared with the register storage class, with a function or array type, or with a type that is not compatible with the type that results after application of the default argument promotions, the behavior is undefined.
Returns
The va_start macro returns no value.
The function f1 gathers into an array a list of arguments that are pointers to strings (but not more than MAXARGS arguments), then passes the array as a single argument to function f2. The number of pointers is specified by the first argument to f1.
#include <stdarg.h>
#define MAXARGS 31
void f1(int n_ptrs, ...)
{
va_list ap;
char *array[MAXARGS];
int ptr_no = 0;
if (n_ptrs > MAXARGS)
n_ptrs = MAXARGS;
va_start(ap, n_ptrs);
while (ptr_no < n_ptrs)
array[ptr_no++] = va_arg(ap, char *);
va_end(ap);
f2(n_ptrs, array);
}
Each call to f1 is required to have visible the definition of the function or a declaration such as
void f1(int, ...);
The function f3 is similar, but saves the status of the variable argument list after the indicated number of arguments; after f2 has been called once with the whole list, the trailing part of the list is gathered again and passed to function f4.
#include <stdarg.h>
#define MAXARGS 31
void f3(int n_ptrs, int f4_after, ...)
{
va_list ap, ap_save;
char *array[MAXARGS];
int ptr_no = 0;
if (n_ptrs > MAXARGS)
n_ptrs = MAXARGS;
va_start(ap, f4_after);
while (ptr_no < n_ptrs) {
array[ptr_no++] = va_arg(ap, char *);
if (ptr_no == f4_after)
va_copy(ap_save, ap);
}
va_end(ap);
f2(n_ptrs, array);
// Now process the saved copy.
n_ptrs -= f4_after;
ptr_no = 0;
while (ptr_no < n_ptrs)
array[ptr_no++] = va_arg(ap_save, char *);
va_end(ap_save);
f4(n_ptrs, array);
}
7.16 Boolean type and values <stdbool.h>
The header <stdbool.h> defines four macros.
The macro bool expands to _Bool.
The remaining three macros are suitable for use in #if preprocessing directives. They are true which expands to the integer constant 1, false which expands to the integer constant 0, and _ _bool_true_false_are_defined which expands to the integer constant 1.
Notwithstanding the provisions of 7.1.3 Reserved identifiers , a program may undefine and perhaps then redefine the macros bool, true, and false.222)
7.17 Common definitions <stddef.h>
The following types and macros are defined in the standard header <stddef.h>. Some are also defined in other headers, as noted in their respective subclauses.
The types are ptrdiff_t which is the signed integer type of the result of subtracting two pointers; size_t which is the unsigned integer type of the result of the sizeof operator; and wchar_t which is an integer type whose range of values can represent distinct codes for all members of the largest extended character set specified among the supported locales; the null character shall have the code value zero. Each member of the basic character set shall have a code value equal to its value when used as the lone character in an integer
character constant if an implementation does not define
_ _STDC_MB_MIGHT_NEQ_WC_ _.
The macros are
NULL
which expands to an implementation-defined null pointer constant; and
offsetof(type, member-designator)
which expands to an integer constant expression that has type size_t, the value of which is the offset in bytes, to the structure member (designated by member-designator), from the beginning of its structure (designated by type). The type and member designator shall be such that given static type t; then the expression &(t.member-designator) evaluates to an address constant. (If the specified member is a bit-field, the behavior is undefined.)
Recommended practice
The types used for size_t and ptrdiff_t should not have an integer conversion rank greater than that of signed long int unless the implementation supports objects large enough to make this necessary. Forward references: localization ( 7.11 Localization <locale.h> ).
7.18 Integer types <stdint.h>
The header <stdint.h> declares sets of integer types having specified widths, and defines corresponding sets of macros.223) It also defines macros that specify limits of integer types corresponding to types defined in other standard headers.
Types are defined in the following categories:
- integer types having certain exact widths;
- integer types having at least certain specified widths;
- fastest integer types having at least certain specified widths;
- integer types wide enough to hold pointers to objects;
- integer types having greatest width. (Some of these types may denote the same type.)
Corresponding macros specify limits of the declared types and construct suitable constants.
For each type described herein that the implementation provides, [224] <stdint.h> shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, <stdint.h> shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘‘optional’’).
7.18.1 Integer types
When typedef names differing only in the absence or presence of the initial u are defined, they shall denote corresponding signed and unsigned types as described in 6.2.5 ; an implementation providing one of these corresponding types shall also provide the other.
In the following descriptions, the symbol N represents an unsigned decimal integer with no leading zeros (e.g., 8 or 24, but not 04 or 048).
7.18.1.1 Exact-width integer types
The typedef name intN_t designates a signed integer type with width N , no padding bits, and a two’s complement representation. Thus, int8_t denotes a signed integer type with a width of exactly 8 bits.
The typedef name uintN_t designates an unsigned integer type with width N . Thus, uint24_t denotes an unsigned integer type with a width of exactly 24 bits.
These types are optional. However, if an implementation provides integer types with widths of 8, 16, 32, or 64 bits, no padding bits, and (for the signed types) that have a two’s complement representation, it shall define the corresponding typedef names.
7.18.1.2 Minimum-width integer types
The typedef name int_leastN_t designates a signed integer type with a width of at least N , such that no signed integer type with lesser size has at least the specified width. Thus, int_least32_t denotes a signed integer type with a width of at least 32 bits.
The typedef name uint_leastN_t designates an unsigned integer type with a width of at least N , such that no unsigned integer type with lesser size has at least the specified width. Thus, uint_least16_t denotes an unsigned integer type with a width of at least 16 bits.
The following types are required:
int_least8_t uint_least8_t
int_least16_t uint_least16_t
int_least32_t uint_least32_t
int_least64_t uint_least64_t
All other types of this form are optional.
7.18.1.3 Fastest minimum-width integer types
Each of the following types designates an integer type that is usually fastest [225] to operate with among all integer types that have at least the specified width.
The typedef name int_fastN_t designates the fastest signed integer type with a width of at least N . The typedef name uint_fastN_t designates the fastest unsigned integer type with a width of at least N .
The following types are required:
int_fast8_t uint_fast8_t
int_fast16_t uint_fast16_t
int_fast32_t uint_fast32_t
int_fast64_t uint_fast64_t
All other types of this form are optional.
7.18.1.4 Integer types capable of holding object pointers
The following type designates a signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer: intptr_t The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer: uintptr_t These types are optional.
7.18.1.5 Greatest-width integer types
The following type designates a signed integer type capable of representing any value of any signed integer type: intmax_t The following type designates an unsigned integer type capable of representing any value of any unsigned integer type: uintmax_t These types are required.
7.18.2 Limits of specified-width integer types
The following object-like macros [226] specify the minimum and maximum limits of the types declared in <stdint.h>. Each macro name corresponds to a similar type name in 7.18.1.
Each instance of any defined macro shall be replaced by a constant expression suitable for use in #if preprocessing directives, and this expression shall have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Its implementation-defined value shall be equal to or greater in magnitude (absolute value) than the corresponding value given below, with the same sign, except where stated to be exactly the given value.
7.18.2.1 Limits of exact-width integer types
- minimum values of exact-width signed integer types INTN_MIN exactly −(2 N −1 )
- maximum values of exact-width signed integer types INTN_MAX exactly 2 N −1 − 1
- maximum values of exact-width unsigned integer types UINTN_MAX exactly 2 N − 1
7.18.2.2 Limits of minimum-width integer types
- minimum values of minimum-width signed integer types INT_LEASTN_MIN −(2 N −1 − 1)
- maximum values of minimum-width signed integer types INT_LEASTN_MAX 2 N −1 − 1
- maximum values of minimum-width unsigned integer types UINT_LEASTN_MAX 2N − 1
7.18.2.3 Limits of fastest minimum-width integer types
- minimum values of fastest minimum-width signed integer types INT_FASTN_MIN −(2 N −1 − 1)
- maximum values of fastest minimum-width signed integer types INT_FASTN_MAX 2 N −1 − 1
- maximum values of fastest minimum-width unsigned integer types UINT_FASTN_MAX 2N − 1
7.18.2.4 Limits of integer types capable of holding object pointers
- minimum value of pointer-holding signed integer type INTPTR_MIN −(215 − 1)
- maximum value of pointer-holding signed integer type INTPTR_MAX 215 − 1
- maximum value of pointer-holding unsigned integer type UINTPTR_MAX 216 − 1
7.18.2.5 Limits of greatest-width integer types
- minimum value of greatest-width signed integer type INTMAX_MIN −(263 − 1)
- maximum value of greatest-width signed integer type INTMAX_MAX 263 − 1
- maximum value of greatest-width unsigned integer type UINTMAX_MAX 264 − 1
7.18.3 Limits of other integer types
The following object-like macros [227] specify the minimum and maximum limits of integer types corresponding to types defined in other standard headers.
Each instance of these macros shall be replaced by a constant expression suitable for use in #if preprocessing directives, and this expression shall have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Its implementation-defined value shall be equal to or greater in magnitude (absolute value) than the corresponding value given below, with the same sign. An implementation shall define only the macros corresponding to those typedef names it actually provides.228)
- limits of ptrdiff_t PTRDIFF_MIN −65535 PTRDIFF_MAX +65535
- limits of sig_atomic_t SIG_ATOMIC_MIN see below SIG_ATOMIC_MAX see below
- limit of size_t SIZE_MAX 65535
- limits of wchar_t WCHAR_MIN see below WCHAR_MAX see below
- limits of wint_t WINT_MIN see below WINT_MAX see below
If sig_atomic_t (see 7.14 Signal handling <signal.h> ) is defined as a signed integer type, the value of SIG_ATOMIC_MIN shall be no greater than −127 and the value of SIG_ATOMIC_MAX shall be no less than 127; otherwise, sig_atomic_t is defined as an unsigned integer type, and the value of SIG_ATOMIC_MIN shall be 0 and the value of SIG_ATOMIC_MAX shall be no less than 255.
If wchar_t (see 7.17 Common definitions <stddef.h> ) is defined as a signed integer type, the value of WCHAR_MIN shall be no greater than −127 and the value of WCHAR_MAX shall be no less than 127; otherwise, wchar_t is defined as an unsigned integer type, and the value of WCHAR_MIN shall be 0 and the value of WCHAR_MAX shall be no less than 255.229 )
If wint_t (see 7.24 Extended multibyte and wide character utilities <wchar.h> ) is defined as a signed integer type, the value of WINT_MIN shall be no greater than −32767 and the value of WINT_MAX shall be no less than 32767; otherwise, wint_t is defined as an unsigned integer type, and the value of WINT_MIN shall be 0 and the value of WINT_MAX shall be no less than 65535.
7.18.4 Macros for integer constants
The following function-like macros [230] expand to integer constants suitable for initializing objects that have integer types corresponding to types defined in <stdint.h>. Each macro name corresponds to a similar type name in 7.18.1.2 Minimum-width integer types or 7.18.1.5.
The argument in any instance of these macros shall be an unsuffixed integer constant (as defined in 6.4.4.1 ) with a value that does not exceed the limits for the corresponding type.
Each invocation of one of these macros shall expand to an integer constant expression suitable for use in #if preprocessing directives. The type of the expression shall have the same type as would an expression of the corresponding type converted according to the integer promotions. The value of the expression shall be that of the argument.
7.18.4.1 Macros for minimum-width integer constants
The macro INTN_C(value) shall expand to an integer constant expression corresponding to the type int_leastN_t. The macro UINTN_C(value) shall expand to an integer constant expression corresponding to the type uint_leastN_t. For example, if uint_least64_t is a name for the type unsigned long long int, then UINT64_C(0x123) might expand to the integer constant 0x123ULL.
7.18.4.2 Macros for greatest-width integer constants
The following macro expands to an integer constant expression having the value specified by its argument and the type intmax_t:
INTMAX_C(value)
The following macro expands to an integer constant expression having the value specified by its argument and the type uintmax_t:
UINTMAX_C(value)
7.19 Input/output <stdio.h>
7.19.1 Introduction
The header <stdio.h> declares three types, several macros, and many functions for performing input and output.
The types declared are size_t (described in 7.17 Common definitions <stddef.h> );
FILE
which is an object type capable of recording all the information needed to control a stream, including its file position indicator, a pointer to its associated buffer (if any), an error indicator that records whether a read/write error has occurred, and an end-of-file indicator that records whether the end of the file has been reached; and fpos_t which is an object type other than an array type capable of recording all the information needed to specify uniquely every position within a file.
The macros are NULL (described in 7.17 Common definitions <stddef.h> ); _IOFBF _IOLBF _IONBF which expand to integer constant expressions with distinct values, suitable for use as the third argument to the setvbuf function;
BUFSIZ
which expands to an integer constant expression that is the size of the buffer used by the setbuf function;
EOF
which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;
FOPEN_MAX
which expands to an integer constant expression that is the minimum number of files that the implementation guarantees can be open simultaneously;
FILENAME_MAX
which expands to an integer constant expression that is the size needed for an array of char large enough to hold the longest file name string that the implementation guarantees can be opened; [231] L_tmpnam which expands to an integer constant expression that is the size needed for an array of char large enough to hold a temporary file name string generated by the tmpnam function;
SEEK_CUR
SEEK_END
SEEK_SET
which expand to integer constant expressions with distinct values, suitable for use as the third argument to the fseek function;
TMP_MAX
which expands to an integer constant expression that is the maximum number of unique file names that can be generated by the tmpnam function; stderr stdin stdout which are expressions of type ‘‘pointer to FILE’’ that point to the FILE objects associated, respectively, with the standard error, input, and output streams.
The header <wchar.h> declares a number of functions useful for wide character input and output. The wide character input/output functions described in that subclause provide operations analogous to most of those described here, except that the fundamental units internal to the program are wide characters. The external representation (in the file) is a sequence of ‘‘generalized’’ multibyte characters, as described further in 7.19.3.
The input/output functions are given the following collective terms:
- The wide character input functions — those functions described in 7.24 Extended multibyte and wide character utilities <wchar.h> that perform input into wide characters and wide strings: fgetwc, fgetws, getwc, getwchar, fwscanf, wscanf, vfwscanf, and vwscanf.
- The wide character output functions — those functions described in 7.24 Extended multibyte and wide character utilities <wchar.h> that perform output from wide characters and wide strings: fputwc, fputws, putwc, putwchar, fwprintf, wprintf, vfwprintf, and vwprintf.
- The wide character input/output functions — the union of the ungetwc function, the wide character input functions, and the wide character output functions.
- The byte input/output functions — those functions described in this subclause that perform input/output: fgetc, fgets, fprintf, fputc, fputs, fread, fscanf, fwrite, getc, getchar, gets, printf, putc, putchar, puts, scanf, ungetc, vfprintf, vfscanf, vprintf, and vscanf. Forward references: files ( 7.19.3 Files ), the fseek function ( 7.19.9.2 The fseek function ), streams ( 7.19.2 Streams ), the tmpnam function ( 7.19.4.4 The tmpnam function ), <wchar.h> ( 7.24 Extended multibyte and wide character utilities <wchar.h> ).
7.19.2 Streams
Input and output, whether to or from physical devices such as terminals and tape drives, or whether to or from files supported on structured storage devices, are mapped into logical data streams, whose properties are more uniform than their various inputs and outputs. Two forms of mapping are supported, for text streams and for binary streams.232)
A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one-to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.
A binary stream is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream shall compare equal to the data that were earlier written out to that stream, under the same implementation. Such a stream may, however, have an implementation-defined number of null characters appended to the end of the stream.
Each stream has an orientation. After a stream is associated with an external file, but before any operations are performed on it, the stream is without orientation. Once a wide character input/output function has been applied to a stream without orientation, the stream becomes a wide-oriented stream. Similarly, once a byte input/output function has been applied to a stream without orientation, the stream becomes a byte-oriented stream. Only a call to the freopen function or the fwide function can otherwise alter the orientation of a stream. (A successful call to freopen removes any orientation.)233)
Byte input/output functions shall not be applied to a wide-oriented stream and wide character input/output functions shall not be applied to a byte-oriented stream. The remaining stream operations do not affect, and are not affected by, a stream’s orientation, except for the following additional restrictions:
- Binary wide-oriented streams have the file-positioning restrictions ascribed to both text and binary streams.
- For wide-oriented streams, after a successful call to a file-positioning function that leaves the file position indicator prior to the end-of-file, a wide character output function can overwrite a partial multibyte character; any file contents beyond the byte(s) written are henceforth indeterminate.
Each wide-oriented stream has an associated mbstate_t object that stores the current parse state of the stream. A successful call to fgetpos stores a representation of the value of this mbstate_t object as part of the value of the fpos_t object. A later successful call to fsetpos using the same stored fpos_t value restores the value of the associated mbstate_t object as well as the position within the controlled stream. Environmental limits
An implementation shall support text files with lines containing at least 254 characters, including the terminating new-line character. The value of the macro BUFSIZ shall be at least 256. Forward references: the freopen function ( 7.19.5.4 The freopen function ), the fwide function ( 7.24.3.5 The fwide function ), mbstate_t ( 7.25.1 Introduction ), the fgetpos function ( 7.19.9.1 The fgetpos function ), the fsetpos function ( 7.19.9.3 The fsetpos function ).
7.19.3 Files
A stream is associated with an external file (which may be a physical device) by opening a file, which may involve creating a new file. Creating an existing file causes its former contents to be discarded, if necessary. If a file can support positioning requests (such as a disk file, as opposed to a terminal), then a file position indicator associated with the stream is positioned at the start (character number zero) of the file, unless the file is opened with append mode in which case it is implementation-defined whether the file position indicator is initially positioned at the beginning or the end of the file. The file position indicator is maintained by subsequent reads, writes, and positioning requests, to facilitate an orderly progression through the file.
Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation-defined.
When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment. Support for these characteristics is implementation-defined, and may be affected via the setbuf and setvbuf functions.
A file may be disassociated from a controlling stream by closing the file. Output streams are flushed (any unwritten buffer contents are transmitted to the host environment) before the stream is disassociated from the file. The value of a pointer to a FILE object is indeterminate after the associated file is closed (including the standard text streams). Whether a file of zero length (on which no characters have been written by an output stream) actually exists is implementation-defined.
The file may be subsequently reopened, by the same or another program execution, and its contents reclaimed or modified (if it can be repositioned at its start). If the main function returns to its original caller, or if the exit function is called, all open files are closed (hence all output streams are flushed) before program termination. Other paths to program termination, such as calling the abort function, need not close all files properly.
The address of the FILE object used to control a stream may be significant; a copy of a FILE object need not serve in place of the original.
At program startup, three text streams are predefined and need not be opened explicitly
- standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.
Functions that open additional (nontemporary) files require a file name, which is a string. The rules for composing valid file names are implementation-defined. Whether the same file can be simultaneously open multiple times is also implementation-defined.
Although both text and binary wide-oriented streams are conceptually sequences of wide characters, the external file associated with a wide-oriented stream is a sequence of multibyte characters, generalized as follows:
- Multibyte encodings within files may contain embedded null bytes (unlike multibyte encodings valid for use internal to the program).
- A file need not begin nor end in the initial shift state.234)
Moreover, the encodings used for multibyte characters may differ among files. Both the nature and choice of such encodings are implementation-defined.
The wide character input functions read multibyte characters from the stream and convert them to wide characters as if they were read by successive calls to the fgetwc function. Each conversion occurs as if by a call to the mbrtowc function, with the conversion state described by the stream’s own mbstate_t object. The byte input functions read characters from the stream as if by successive calls to the fgetc function.
The wide character output functions convert wide characters to multibyte characters and write them to the stream as if they were written by successive calls to the fputwc function. Each conversion occurs as if by a call to the wcrtomb function, with the conversion state described by the stream’s own mbstate_t object. The byte output functions write characters to the stream as if by successive calls to the fputc function.
In some cases, some of the byte input/output functions also perform conversions between multibyte characters and wide characters. These conversions also occur as if by calls to the mbrtowc and wcrtomb functions.
An encoding error occurs if the character sequence presented to the underlying mbrtowc function does not form a valid (generalized) multibyte character, or if the code value passed to the underlying wcrtomb does not correspond to a valid (generalized) multibyte character. The wide character input/output functions and the byte input/output functions store the value of the macro EILSEQ in errno if and only if an encoding error occurs. Environmental limits
The value of FOPEN_MAX shall be at least eight, including the three standard text streams. Forward references: the exit function ( 7.20.4.3 The exit function ), the fgetc function ( 7.19.7.1 The fgetc function ), the fopen function ( 7.19.5.3 The fopen function ), the fputc function ( 7.19.7.3 The fputc function ), the setbuf function ( 7.19.5.5 The setbuf function ), the setvbuf function ( 7.19.5.6 The setvbuf function ), the fgetwc function ( 7.24.3.1 The fgetwc function ), the fputwc function ( 7.24.3.3 The fputwc function ), conversion state ( 7.24.6 Extended multibyte/wide character conversion utilities ), the mbrtowc function ( 7.24.6.3.2 The mbrtowc function ), the wcrtomb function ( 7.24.6.3.3 The wcrtomb function ).
7.19.4 Operations on files
7.19.4.1 The remove function
Synopsis
#include <stdio.h>
int remove(const char *filename);
Description
The remove function causes the file whose name is the string pointed to by filename to be no longer accessible by that name. A subsequent attempt to open that file using that name will fail, unless it is created anew. If the file is open, the behavior of the remove function is implementation-defined.
Returns
The remove function returns zero if the operation succeeds, nonzero if it fails.
7.19.4.2 The rename function
Synopsis
#include <stdio.h>
int rename(const char *old, const char *new);
Description
The rename function causes the file whose name is the string pointed to by old to be henceforth known by the name given by the string pointed to by new. The file named old is no longer accessible by that name. If a file named by the string pointed to by new exists prior to the call to the rename function, the behavior is implementation-defined.
Returns
The rename function returns zero if the operation succeeds, nonzero if it fails, [235] in which case if the file existed previously it is still known by its original name.
7.19.4.3 The tmpfile function
Synopsis
#include <stdio.h>
FILE *tmpfile(void);
Description
The tmpfile function creates a temporary binary file that is different from any other existing file and that will automatically be removed when it is closed or at program termination. If the program terminates abnormally, whether an open temporary file is removed is implementation-defined. The file is opened for update with "wb+" mode.
Recommended practice
It should be possible to open at least TMP_MAX temporary files during the lifetime of the program (this limit may be shared with tmpnam) and there should be no limit on the number simultaneously open other than this limit and any limit on the number of open files (FOPEN_MAX).
Returns
The tmpfile function returns a pointer to the stream of the file that it created. If the file cannot be created, the tmpfile function returns a null pointer. Forward references: the fopen function ( 7.19.5.3 The fopen function ).
7.19.4.4 The tmpnam function
Synopsis
#include <stdio.h>
char *tmpnam(char *s);
Description
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.236) 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.
The tmpnam function generates a different string each time it is called.
The implementation shall behave as if no library function calls the tmpnam function.
Returns
If no suitable string can be generated, the tmpnam function returns a null pointer. Otherwise, if the argument is a null pointer, the tmpnam function leaves its result in an internal static object and returns a pointer to that object (subsequent calls to the tmpnam function may modify the same object). If the argument is not a null pointer, it is assumed to point to an array of at least L_tmpnam chars; the tmpnam function writes its result in that array and returns the argument as its value. Environmental limits
The value of the macro TMP_MAX shall be at least 25.
7.19.5 File access functions
7.19.5.1 The fclose function
Synopsis
#include <stdio.h>
int fclose(FILE *stream);
Description
A successful call to the fclose function causes the stream pointed to by stream to be flushed and the associated file to be closed. Any unwritten buffered data for the stream are delivered to the host environment to be written to the file; any unread buffered data are discarded. Whether or not the call succeeds, the stream is disassociated from the file and any buffer set by the setbuf or setvbuf function is disassociated from the stream (and deallocated if it was automatically allocated).
Returns
The fclose function returns zero if the stream was successfully closed, or EOF if any errors were detected.
7.19.5.2 The fflush function
Synopsis
#include <stdio.h>
int fflush(FILE *stream);
Description
If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
If stream is a null pointer, the fflush function performs this flushing action on all streams for which the behavior is defined above.
Returns
The fflush function sets the error indicator for the stream and returns EOF if a write error occurs, otherwise it returns zero. Forward references: the fopen function ( 7.19.5.3 The fopen function ).
7.19.5.3 The fopen function
Synopsis
#include <stdio.h>
FILE *fopen(const char * restrict filename,
const char * restrict mode);
Description
The fopen function opens the file whose name is the string pointed to by filename, and associates a stream with it.
The argument mode points to a string. If the string is one of the following, the file is open in the indicated mode. Otherwise, the behavior is undefined.237)
r open text file for reading
w truncate to zero length or create text file for writing
a append; open or create text file for writing at end-of-file
rb open binary file for reading
wb truncate to zero length or create binary file for writing
ab append; open or create binary file for writing at end-of-file
r+ open text file for update (reading and writing)
w+ truncate to zero length or create text file for update
a+ append; open or create text file for update, writing at end-of-file
r+b or rb+ open binary file for update (reading and writing) w+b or wb+ truncate to zero length or create binary file for update a+b or ab+ append; open or create binary file for update, writing at end-of-file
Opening a file with read mode ('r' as the first character in the mode argument) fails if the file does not exist or cannot be read.
Opening a file with append mode ('a' as the first character in the mode argument) causes all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to the fseek function. In some implementations, opening a binary file with append mode ('b' as the second or third character in the above list of mode argument values) may initially position the file position indicator for the stream beyond the last data written, because of null character padding.
When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file. Opening (or creating) a text file with update mode may instead open (or create) a binary stream in some implementations.
When opened, a stream is fully buffered if and only if it can be determined not to refer to an interactive device. The error and end-of-file indicators for the stream are cleared.
Returns
The fopen function returns a pointer to the object controlling the stream. If the open operation fails, fopen returns a null pointer. Forward references: file positioning functions ( 7.19.9 File positioning functions ).
7.19.5.4 The freopen function
Synopsis
#include <stdio.h>
FILE *freopen(const char * restrict filename,
const char * restrict mode,
FILE * restrict stream);
Description
The freopen function opens the file whose name is the string pointed to by filename and associates the stream pointed to by stream with it. The mode argument is used just as in the fopen function.238)
If filename is a null pointer, the freopen function attempts to change the mode of the stream to that specified by mode, as if the name of the file currently associated with the stream had been used. It is implementation-defined which changes of mode are permitted (if any), and under what circumstances.
The freopen function first attempts to close any file that is associated with the specified stream. Failure to close the file is ignored. The error and end-of-file indicators for the stream are cleared.
Returns
The freopen function returns a null pointer if the open operation fails. Otherwise, freopen returns the value of stream.
7.19.5.5 The setbuf function
Synopsis
#include <stdio.h>
void setbuf(FILE * restrict stream,
char * restrict buf);
Description
Except that it returns no value, the setbuf function is equivalent to the setvbuf function invoked with the values _IOFBF for mode and BUFSIZ for size, or (if buf is a null pointer), with the value _IONBF for mode.
Returns
The setbuf function returns no value. Forward references: the setvbuf function ( 7.19.5.6 The setvbuf function ).
7.19.5.6 The setvbuf function
Synopsis
#include <stdio.h>
int setvbuf(FILE * restrict stream,
char * restrict buf,
int mode, size_t size);
Description
The setvbuf function may be used only after the stream pointed to by stream has been associated with an open file and before any other operation (other than an unsuccessful call to setvbuf) is performed on the stream. The argument mode determines how stream will be buffered, as follows: _IOFBF causes input/output to be fully buffered; _IOLBF causes input/output to be line buffered; _IONBF causes input/output to be unbuffered. If buf is not a null pointer, the array it points to may be used instead of a buffer allocated by the setvbuf function [239] and the argument size specifies the size of the array; otherwise, size may determine the size of a buffer allocated by the setvbuf function. The contents of the array at any time are indeterminate.
Returns
The setvbuf function returns zero on success, or nonzero if an invalid value is given for mode or if the request cannot be honored.
7.19.6 Formatted input/output functions
The formatted input/output functions shall behave as if there is a sequence point after the actions associated with each specifier.240)
7.19.6.1 The fprintf function
Synopsis
#include <stdio.h>
int fprintf(FILE * restrict stream,
const char * restrict format, ...);
Description
The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. The fprintf function returns when the end of the format string is encountered.
The format shall be a multibyte character sequence, beginning and ending in its initial shift state. The format is composed of zero or more directives: ordinary multibyte characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent arguments, converting them, if applicable, according to the corresponding conversion specifier, and then writing the result to the output stream.
Each conversion specification is introduced by the character %. After the %, the following appear in sequence:
- Zero or more flags (in any order) that modify the meaning of the conversion specification.
- An optional minimum field width. If the converted value has fewer characters than the field width, it is padded with spaces (by default) on the left (or right, if the left adjustment flag, described later, has been given) to the field width. The field width takes the form of an asterisk * (described later) or a nonnegative decimal integer.241)
- An optional precision that gives the minimum number of digits to appear for the d, i, o, u, x, and X conversions, the number of digits to appear after the decimal-point character for a, A, e, E, f, and F conversions, the maximum number of significant digits for the g and G conversions, or the maximum number of bytes to be written for s conversions. The precision takes the form of a period (.) followed either by an asterisk * (described later) or by an optional decimal integer; if only the period is specified, the precision is taken as zero. If a precision appears with any other conversion specifier, the behavior is undefined.
- An optional length modifier that specifies the size of the argument.
- A conversion specifier character that specifies the type of conversion to be applied.
As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an int argument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted. A negative field width argument is taken as a - flag followed by a positive field width. A negative precision argument is taken as if the precision were omitted.
The flag characters and their meanings are:
- -
- The result of the conversion is left-justified within the field. (It is right-justified if this flag is not specified.)
- +
- The result of a signed conversion always begins with a plus or minus sign. (It begins with a sign only when a negative value is converted if this flag is not specified.)242)
- space
- If the first character of a signed conversion is not a sign, or if a signed conversion results in no characters, a space is prefixed to the result. If the space and + flags both appear, the space flag is ignored.
- #
- The result is converted to an ‘‘alternative form’’. For o conversion, it increases the precision, if and only if necessary, to force the first digit of the result to be a zero (if the value and precision are both 0, a single 0 is printed). For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it. For a, A, e, E, f, F, g, and G conversions, the result of converting a floating-point number always contains a decimal-point character, even if no digits follow it. (Normally, a decimal-point character appears in the result of these conversions only if a digit follows it.) For g and G conversions, trailing zeros are not removed from the result. For other conversions, the behavior is undefined.
0 For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, leading zeros (following any indication of sign or base) are used to pad to the field width rather than performing space padding, except when converting an infinity or NaN. If the 0 and - flags both appear, the 0 flag is ignored. For d, i, o, u, x, and X conversions, if a precision is specified, the 0 flag is ignored. For other conversions, the behavior is undefined.
The length modifiers and their meanings are:
- hh
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following n conversion specifier applies to a pointer to a signed char argument.
- h
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to a short int or unsigned short int argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to short int or unsigned short int before printing); or that a following n conversion specifier applies to a pointer to a short int argument.
- l (ell)
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.
- ll (ell-ell)
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long long int or unsigned long long int argument; or that a following n conversion specifier applies to a pointer to a long long int argument.
- j
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to an intmax_t or uintmax_t argument; or that a following n conversion specifier applies to a pointer to an intmax_t argument.
- z
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to a size_t or the corresponding signed integer type argument; or that a following n conversion specifier applies to a pointer to a signed integer type corresponding to size_t argument.
- t
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned integer type argument; or that a following n conversion specifier applies to a pointer to a ptrdiff_t argument.
- L
- Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument.
If a length modifier appears with any conversion specifier other than as specified above, the behavior is undefined.
The conversion specifiers and their meanings are: d,i The int argument is converted to signed decimal in the style [−]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no characters. o,u,x,X The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal notation (x or X) in the style dddd; the letters abcdef are used for x conversion and the letters ABCDEF for X conversion. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no characters. f,F A double argument representing a floating-point number is 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 zero and the # flag is not specified, no decimal-point character appears. If a decimal-point character appears, at least one digit appears before it. The value is rounded to the appropriate number of digits. A double argument representing an infinity is converted in one of the styles [-]inf or [-]infinity — which style is implementation-defined. A double argument representing a NaN is converted in one of the styles [-]nan or [-]nan(n-char-sequence) — which style, and the meaning of any n-char-sequence, is implementation-defined. The F conversion specifier produces INF, INFINITY, or NAN instead of inf, infinity, or nan, respectively.243) e,E A double argument representing a floating-point number is converted in the style [−]d.ddd e±dd, where there is one digit (which is nonzero if the argument is nonzero) 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 and the # flag is not specified, no decimal-point character appears. The value is rounded to the appropriate number of digits. The E conversion specifier produces a number with E instead of e introducing the exponent. The exponent always contains at least two digits, and only as many more digits as necessary to represent the exponent. If the value is zero, the exponent is zero. A double argument representing an infinity or NaN is converted in the style of an f or F conversion specifier. g,G A double argument representing a floating-point number is converted in style f or e (or in style F or E in the case of a G conversion specifier), depending on the value converted and the precision. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X :
- if P > X ≥ −4, the conversion is with style f (or F) and precision P − (X + 1).
- otherwise, the conversion is with style e (or E) and precision P − 1. Finally, unless the # flag is used, any trailing zeros are removed from the fractional portion of the result and the decimal-point character is removed if there is no fractional portion remaining. A double argument representing an infinity or NaN is converted in the style of an f or F conversion specifier. a,A A double argument representing a floating-point number is converted in the style [−]0xh.hhhh p±d, where there is one hexadecimal digit (which is nonzero if the argument is a normalized floating-point number and is otherwise unspecified) before the decimal-point character [244] and the number of hexadecimal digits after it is equal to the precision; if the precision is missing and FLT_RADIX is a power of 2, then the precision is sufficient for an exact representation of the value; if the precision is missing and FLT_RADIX is not a power of 2, then the precision is sufficient to distinguish [245] values of type double, except that trailing zeros may be omitted; if the precision is zero and the # flag is not specified, no decimal-point character appears. The letters abcdef are used for a conversion and the letters ABCDEF for A conversion. The A conversion specifier produces a number with X and P instead of x and p. The exponent always contains at least one digit, and only as many more digits as necessary to represent the decimal exponent of 2. If the value is zero, the exponent is zero. A double argument representing an infinity or NaN is converted in the style of an f or F conversion specifier. c If no l length modifier is present, the int argument is converted to an unsigned char, and the resulting character is written. If an l length modifier is present, the wint_t argument is converted as if by an ls conversion specification with no precision and an argument that points to the initial element of a two-element array of wchar_t, the first element containing the wint_t argument to the lc conversion specification and the second a null wide character. s If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type.246) Characters from the array are written up to (but not including) the terminating null character. If the precision is specified, no more than that many bytes are written. If the precision is not specified or is greater than the size of the array, the array shall contain a null character. If an l length modifier is present, the argument shall be a pointer to the initial element of an array of wchar_t type. Wide characters from the array are converted to multibyte characters (each as if by a call to the wcrtomb function, with the conversion state described by an mbstate_t object initialized to zero before the first wide character is converted) up to and including a terminating null wide character. The resulting multibyte characters are written up to (but not including) the terminating null character (byte). If no precision is specified, the array shall contain a null wide character. If a precision is specified, no more than that many bytes are written (including shift sequences, if any), and the array shall contain a null wide character if, to equal the multibyte character sequence length given by the precision, the function would need to access a wide character one past the end of the array. In no case is a partial multibyte character written.247) p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner. n The argument shall be a pointer to signed integer into which is written the number of characters written to the output stream so far by this call to fprintf. No argument is converted, but one is consumed. If the conversion specification includes any flags, a field width, or a precision, the behavior is undefined. % A % character is written. No argument is converted. The complete conversion specification shall be %%.
If a conversion specification is invalid, the behavior is undefined.248) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
In no case does a nonexistent 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.
For a and A conversions, if FLT_RADIX is a power of 2, the value is correctly rounded to a hexadecimal floating number with the given precision.
Recommended practice
For a and A conversions, if FLT_RADIX is not a power of 2 and the result is not exactly representable in the given precision, the result should be one of the two adjacent numbers in hexadecimal floating style with the given precision, with the extra stipulation that the error should have a correct sign for the current rounding direction.
For e, E, f, F, g, and G conversions, if the number of significant decimal digits is at most DECIMAL_DIG, then the result should be correctly rounded.249) If the number of significant decimal digits is more than DECIMAL_DIG but the source value is exactly representable with DECIMAL_DIG digits, then the result should be an exact representation with trailing zeros. Otherwise, the source value is bounded by two adjacent decimal strings L < U, both having DECIMAL_DIG significant digits; the value of the resultant decimal string D should satisfy L ≤ D ≤ U, with the extra stipulation that the error should have a correct sign for the current rounding direction.
Returns
The fprintf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred. Environmental limits
The number of characters that can be produced by any single conversion shall be at least 4095.
To print a date and time in the form ‘‘Sunday, July 3, 10:02’’ followed by π to five decimal places:
#include <math.h>
#include <stdio.h>
/* ... */
char *weekday, *month; // pointers to strings
int day, hour, min;
fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",
weekday, month, day, hour, min);
fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));
EXAMPLE 2 In this example, multibyte characters do not have a state-dependent encoding, and the members of the extended character set that consist of more than one byte each consist of exactly two bytes, the first of which is denoted here by a and the second by an uppercase letter.
Given the following wide string with length seven, static wchar_t wstr[] = L" X Yabc Z W"; the seven calls fprintf(stdout, "|1234567890123|\n"); fprintf(stdout, "|%13ls|\n", wstr); fprintf(stdout, "|%- 13.9 ls|\n", wstr); fprintf(stdout, "|% 13.10 ls|\n", wstr); fprintf(stdout, "|% 13.11 ls|\n", wstr); fprintf(stdout, "|% 13.15 ls|\n", &wstr[2]); fprintf(stdout, "|%13lc|\n", (wint_t) wstr[5]); will print the following seven lines: |1234567890123|
| X Yabc Z W|
| X Yabc Z |
| X Yabc Z|
| X Yabc Z W|
| abc Z W|
| Z|
Forward references: conversion state ( 7.24.6 Extended multibyte/wide character conversion utilities ), the wcrtomb function ( 7.24.6.3.3 The wcrtomb function ).
7.19.6.2 The fscanf function
Synopsis
#include <stdio.h>
int fscanf(FILE * restrict stream,
const char * restrict format, ...);
Description
The fscanf function reads input from the stream pointed to by stream, under control of the string pointed to by format that specifies the admissible input sequences and how they are to be converted for assignment, using subsequent arguments as pointers to the objects to receive the converted input. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored.
The format shall be a multibyte character sequence, beginning and ending in its initial shift state. The format is composed of zero or more directives: one or more white-space characters, an ordinary multibyte character (neither % nor a white-space character), or a conversion specification. Each conversion specification is introduced by the character %. After the %, the following appear in sequence:
- An optional assignment-suppressing character *.
- An optional decimal integer greater than zero that specifies the maximum field width (in characters).
- An optional length modifier that specifies the size of the receiving object.
- A conversion specifier character that specifies the type of conversion to be applied.
The fscanf function executes each directive of the format in turn. If a directive fails, as detailed below, the function returns. Failures are described as input failures (due to the occurrence of an encoding error or the unavailability of input characters), or matching failures (due to inappropriate input).
A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read.
A directive that is an ordinary multibyte character is executed by reading the next characters of the stream. If any of those characters differ from the ones composing the directive, the directive fails and the differing and subsequent characters remain unread. Similarly, if end-of-file, an encoding error, or a read error prevents a character from being read, the directive fails.
A directive that is a conversion specification defines a set of matching input sequences, as described below for each specifier. A conversion specification is executed in the following steps:
Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier.250)
An input item is read from the stream, unless the specification includes an n specifier. An input item is defined as the longest sequence of input characters which does not exceed any specified field width and which is, or is a prefix of, a matching input sequence.251) The first character, if any, after the input item remains unread. If the length of the input item is zero, the execution of the directive fails; this condition is a matching failure unless end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure.
Except in the case of a % specifier, the input item (or, in the case of a %n directive, the count of input characters) is converted to a type appropriate to the conversion specifier. If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure. Unless assignment suppression was indicated by a *, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.
The length modifiers and their meanings are:
- hh
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to signed char or unsigned char.
- h
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to short int or unsigned short int.
- l (ell)
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to long int or unsigned long int; that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double; or that a following c, s, or [ conversion specifier applies to an argument with type pointer to wchar_t.
- ll (ell-ell)
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to long long int or unsigned long long int.
- j
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to intmax_t or uintmax_t.
- z
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to size_t or the corresponding signed integer type.
- t
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to ptrdiff_t or the corresponding unsigned integer type.
- L
- Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to long double.
If a length modifier appears with any conversion specifier other than as specified above, the behavior is undefined.
The conversion specifiers and their meanings are:
- d
- Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer.
- i
- Matches an optionally signed integer, whose format is the same as expected for the subject sequence of the strtol function with the value 0 for the base argument. The corresponding argument shall be a pointer to signed integer.
- o
- Matches an optionally signed octal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 8 for the base argument. The corresponding argument shall be a pointer to unsigned integer.
- u
- Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 10 for the base argument. The corresponding argument shall be a pointer to unsigned integer.
- x
- Matches an optionally signed hexadecimal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 16 for the base argument. The corresponding argument shall be a pointer to unsigned integer.
- a,e,f,g
- Matches an optionally signed floating-point number, infinity, or NaN, whose format is the same as expected for the subject sequence of the strtod function. The corresponding argument shall be a pointer to floating.
- c
- Matches a sequence of characters of exactly the number specified by the field width (1 if no field width is present in the directive).252) If no l length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence. No null character is added. If an l length modifier is present, the input shall be a sequence of multibyte characters that begins in the initial shift state. Each multibyte character in the sequence is converted to a wide character as if by a call to the mbrtowc function, with the conversion state described by an mbstate_t object initialized to zero before the first multibyte character is converted. The corresponding argument shall be a pointer to the initial element of an array of wchar_t large enough to accept the resulting sequence of wide characters. No null wide character is added.
- s
- Matches a sequence of non-white-space characters.252) If no l length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically. If an l length modifier is present, the input shall be a sequence of multibyte characters that begins in the initial shift state. Each multibyte character is converted to a wide character as if by a call to the mbrtowc function, with the conversion state described by an mbstate_t object initialized to zero before the first multibyte character is converted. The corresponding argument shall be a pointer to the initial element of an array of wchar_t large enough to accept the sequence and the terminating null wide character, which will be added automatically.
- [
- Matches a nonempty sequence of characters from a set of expected characters (the scanset).252) If no l length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically. If an l length modifier is present, the input shall be a sequence of multibyte characters that begins in the initial shift state. Each multibyte character is converted to a wide character as if by a call to the mbrtowc function, with the conversion state described by an mbstate_t object initialized to zero before the first multibyte character is converted. The corresponding argument shall be a pointer to the initial element of an array of wchar_t large enough to accept the sequence and the terminating null wide character, which will be added automatically. The conversion specifier includes all subsequent characters in the format string, up to and including the matching right bracket (]). The characters between the brackets (the scanlist) compose the scanset, unless the character after the left bracket is a circumflex (^), in which case the scanset contains all characters that do not appear in the scanlist between the circumflex and the right bracket. If the conversion specifier begins with [] or [^], the right bracket character is in the scanlist and the next following right bracket character is the matching right bracket that ends the specification; otherwise the first following right bracket character is the one that ends the specification. If a - character is in the scanlist and is not the first, nor the second where the first character is a ^, nor the last character, the behavior is implementation-defined.
- p
- Matches an implementation-defined set of sequences, which should be the same as the set of sequences that may be produced by the %p conversion of the fprintf function. The corresponding argument shall be a pointer to a pointer to void. The input item is converted to a pointer value in an implementation-defined manner. If the input item is a value converted earlier during the same program execution, the pointer that results shall compare equal to that value; otherwise the behavior of the %p conversion is undefined.
- n
- No input is consumed. The corresponding argument shall be a pointer to signed integer into which is to be written the number of characters read from the input stream so far by this call to the fscanf function. Execution of a %n directive does not increment the assignment count returned at the completion of execution of the fscanf function. No argument is converted, but one is consumed. If the conversion specification includes an assignment-suppressing character or a field width, the behavior is undefined.
- %
- Matches a single % character; no conversion or assignment occurs. The complete conversion specification shall be %%.
If a conversion specification is invalid, the behavior is undefined.253)
The conversion specifiers A, E, F, G, and X are also valid and behave the same as, respectively, a, e, f, g, and x.
Trailing white space (including new-line characters) is left unread unless matched by a directive. The success of literal matches and suppressed assignments is not directly determinable other than via the %n directive.
Returns
The fscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
The call:
#include <stdio.h>
/* ... */
int n, i; float x; char name[50];
n = fscanf(stdin, "%d%f%s", &i, &x, name);
with the input line: 25 54.32 E-1 thompson will assign to n the value 3, to i the value 25, to x the value 5.432 , and to name the sequence thompson\0.
The call:
#include <stdio.h>
/* ... */
int i; float x; char name[50];
fscanf(stdin, "%2d%f%*d %[0123456789]", &i, &x, name);
with input: 56789 0123 56a72 will assign to i the value 56 and to x the value 789.0 , will skip 0123, and will assign to name the sequence 56\0. The next character read from the input stream will be a.
To accept repeatedly from stdin a quantity, a unit of measure, and an item name:
#include <stdio.h>
/* ... */
int count; float quant; char units[21], item[21];
do {
count = fscanf(stdin, "%f%20s of %20s", &quant, units, item);
fscanf(stdin,"%*[^\n]");
} while (!feof(stdin) && !ferror(stdin));
If the stdin stream contains the following lines: 2 quarts of oil - 12.8 degrees Celsius lots of luck
10.0LBS of
dirt
100ergs of energy
the execution of the above example will be analogous to the following assignments: quant = 2; strcpy(units, "quarts"); strcpy(item, "oil"); count = 3; quant = - 12.8 ; strcpy(units, "degrees"); count = 2; // "C" fails to match "o" count = 0; // "l" fails to match "%f" quant = 10.0 ; strcpy(units, "LBS"); strcpy(item, "dirt"); count = 3; count = 0; // "100e" fails to match "%f" count = EOF;
In:
#include <stdio.h>
/* ... */
int d1, d2, n1, n2, i;
i = sscanf("123", "%d%n%n%d", &d1, &n1, &n2, &d2);
the value 123 is assigned to d1 and the value 3 to n1. Because %n can never get an input failure the value of 3 is also assigned to n2. The value of d2 is not affected. The value 1 is assigned to i.
EXAMPLE 5 In these examples, multibyte characters do have a state-dependent encoding, and the members of the extended character set that consist of more than one byte each consist of exactly two bytes, the first of which is denoted here by a and the second by an uppercase letter, but are only recognized as such when in the alternate shift state. The shift sequences are denoted by ↑ and ↓, in which the first causes entry into the alternate shift state.
After the call:
#include <stdio.h>
/* ... */
char str[50];
fscanf(stdin, "a%s", str);
with the input line: a↑ X Y↓ bc str will contain ↑ X Y↓\0 assuming that none of the bytes of the shift sequences (or of the multibyte characters, in the more general case) appears to be a single-byte white-space character.
In contrast, after the call:
#include <stdio.h>
#include <stddef.h>
/* ... */
wchar_t wstr[50];
fscanf(stdin, "a%ls", wstr);
with the same input line, wstr will contain the two wide characters that correspond to X and Y and a terminating null wide character.
However, the call:
#include <stdio.h>
#include <stddef.h>
/* ... */
wchar_t wstr[50];
fscanf(stdin, "a↑ X↓%ls", wstr);
with the same input line will return zero due to a matching failure against the ↓ sequence in the format string.
Assuming that the first byte of the multibyte character X is the same as the first byte of the multibyte character Y, after the call:
#include <stdio.h>
#include <stddef.h>
/* ... */
wchar_t wstr[50];
fscanf(stdin, "a↑ Y↓%ls", wstr);
with the same input line, zero will again be returned, but stdin will be left with a partially consumed multibyte character.
Forward references: the strtod, strtof, and strtold functions ( 7.20.1.3 The strtod, strtof, and strtold functions ), the strtol, strtoll, strtoul, and strtoull functions ( 7.20.1.4 The strtol, strtoll, strtoul, and strtoull functions ), conversion state ( 7.24.6 Extended multibyte/wide character conversion utilities ), the wcrtomb function ( 7.24.6.3.3 The wcrtomb function ).
7.19.6.3 The printf function
Synopsis
#include <stdio.h>
int printf(const char * restrict format, ...);
Description
The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf.
Returns
The printf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.
7.19.6.4 The scanf function
Synopsis
#include <stdio.h>
int scanf(const char * restrict format, ...);
Description
The scanf function is equivalent to fscanf with the argument stdin interposed before the arguments to scanf.
Returns
The scanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
7.19.6.5 The snprintf function
Synopsis
#include <stdio.h>
int snprintf(char * restrict s, size_t n,
const char * restrict format, ...);
Description
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.
Returns
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.
7.19.6.6 The sprintf function
Synopsis
#include <stdio.h>
int sprintf(char * restrict s,
const char * restrict format, ...);
Description
The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument s) rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.
Returns
The sprintf function returns the number of characters written in the array, not counting the terminating null character, or a negative value if an encoding error occurred.
7.19.6.7 The sscanf function
Synopsis
#include <stdio.h>
int sscanf(const char * restrict s,
const char * restrict format, ...);
Description
The sscanf function is equivalent to fscanf, except that input is obtained from a string (specified by the argument s) rather than from a stream. Reaching the end of the string is equivalent to encountering end-of-file for the fscanf function. If copying takes place between objects that overlap, the behavior is undefined.
Returns
The sscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the sscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
7.19.6.8 The vfprintf function
Synopsis
#include <stdarg.h>
#include <stdio.h>
int vfprintf(FILE * restrict stream,
const char * restrict format,
va_list arg);
Description
The vfprintf function is equivalent to fprintf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vfprintf function does not invoke the va_end macro.254)
Returns
The vfprintf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.
The following shows the use of the vfprintf function in a general error-reporting routine.
#include <stdarg.h>
#include <stdio.h>
void error(char *function_name, char *format, ...)
{
va_list args;
va_start(args, format);
// print out name of function causing error
fprintf(stderr, "ERROR in %s: ", function_name);
// print out remainder of message
vfprintf(stderr, format, args);
va_end(args);
}
7.19.6.9 The vfscanf function
Synopsis
#include <stdarg.h>
#include <stdio.h>
int vfscanf(FILE * restrict stream,
const char * restrict format,
va_list arg);
Description
The vfscanf function is equivalent to fscanf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vfscanf function does not invoke the va_end macro.254)
Returns
The vfscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the vfscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
7.19.6.10 The vprintf function
Synopsis
#include <stdarg.h>
#include <stdio.h>
int vprintf(const char * restrict format,
va_list arg);
Description
The vprintf function is equivalent to printf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vprintf function does not invoke the va_end macro.254)
Returns
The vprintf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.
7.19.6.11 The vscanf function
Synopsis
#include <stdarg.h>
#include <stdio.h>
int vscanf(const char * restrict format,
va_list arg);
Description
The vscanf function is equivalent to scanf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vscanf function does not invoke the va_end macro.254)
Returns
The vscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the vscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
7.19.6.12 The vsnprintf function
Synopsis
#include <stdarg.h>
#include <stdio.h>
int vsnprintf(char * restrict s, size_t n,
const char * restrict format,
va_list arg);
Description
The vsnprintf function is equivalent to snprintf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vsnprintf function does not invoke the va_end macro.254) If copying takes place between objects that overlap, the behavior is undefined.
Returns
The vsnprintf 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.
7.19.6.13 The vsprintf function
Synopsis
#include <stdarg.h>
#include <stdio.h>
int vsprintf(char * restrict s,
const char * restrict format,
va_list arg);
Description
The vsprintf function is equivalent to sprintf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vsprintf function does not invoke the va_end macro.254) If copying takes place between objects that overlap, the behavior is undefined.
Returns
The vsprintf function returns the number of characters written in the array, not counting the terminating null character, or a negative value if an encoding error occurred.
7.19.6.14 The vsscanf function
Synopsis
#include <stdarg.h>
#include <stdio.h>
int vsscanf(const char * restrict s,
const char * restrict format,
va_list arg);
Description
The vsscanf function is equivalent to sscanf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vsscanf function does not invoke the va_end macro.254)
Returns
The vsscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the vsscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
7.19.7 Character input/output functions
7.19.7.1 The fgetc function
Synopsis
#include <stdio.h>
int fgetc(FILE *stream);
Description
If the end-of-file indicator for the input stream pointed to by stream is not set and a next character is present, the fgetc function obtains that character as an unsigned char converted to an int and advances the associated file position indicator for the stream (if defined).
Returns
If the end-of-file indicator for the stream is set, or if the stream is at end-of-file, the end-of-file indicator for the stream is set and the fgetc function returns EOF. Otherwise, the fgetc function returns the next character from the input stream pointed to by stream. If a read error occurs, the error indicator for the stream is set and the fgetc function returns EOF.255)
7.19.7.2 The fgets function
Synopsis
#include <stdio.h>
char *fgets(char * restrict s, int n,
FILE * restrict stream);
Description
The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.
Returns
The fgets function returns s if successful. If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned. If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned.
7.19.7.3 The fputc function
Synopsis
#include <stdio.h>
int fputc(int c, FILE *stream);
Description
The fputc function writes the character specified by c (converted to an unsigned char) to the output stream pointed to by stream, at the position indicated by the associated file position indicator for the stream (if defined), and advances the indicator appropriately. If the file cannot support positioning requests, or if the stream was opened with append mode, the character is appended to the output stream.
Returns
The fputc function returns the character written. If a write error occurs, the error indicator for the stream is set and fputc returns EOF.
7.19.7.4 The fputs function
Synopsis
#include <stdio.h>
int fputs(const char * restrict s,
FILE * restrict stream);
Description
The fputs function writes the string pointed to by s to the stream pointed to by stream. The terminating null character is not written.
Returns
The fputs function returns EOF if a write error occurs; otherwise it returns a nonnegative value.
7.19.7.5 The getc function
Synopsis
#include <stdio.h>
int getc(FILE *stream);
Description
The getc function is equivalent to fgetc, except that if it is implemented as a macro, it may evaluate stream more than once, so the argument should never be an expression with side effects.
Returns
The getc function returns the next character from the input stream pointed to by stream. If the stream is at end-of-file, the end-of-file indicator for the stream is set and getc returns EOF. If a read error occurs, the error indicator for the stream is set and getc returns EOF.
7.19.7.6 The getchar function
Synopsis
#include <stdio.h>
int getchar(void);
Description
The getchar function is equivalent to getc with the argument stdin.
Returns
The getchar function returns the next character from the input stream pointed to by stdin. If the stream is at end-of-file, the end-of-file indicator for the stream is set and getchar returns EOF. If a read error occurs, the error indicator for the stream is set and getchar returns EOF.
7.19.7.7 The gets function
Synopsis
#include <stdio.h>
char *gets(char *s);
Description
The gets function reads characters from the input stream pointed to by stdin, into the array pointed to by s, until end-of-file is encountered or a new-line character is read. Any new-line character is discarded, and a null character is written immediately after the last character read into the array.
Returns
The gets function returns s if successful. If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned. If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned. Forward references: future library directions ( 7.26.9 Input/output <stdio.h> ).
7.19.7.8 The putc function
Synopsis
#include <stdio.h>
int putc(int c, FILE *stream);
Description
The putc function is equivalent to fputc, except that if it is implemented as a macro, it may evaluate stream more than once, so that argument should never be an expression with side effects.
Returns
The putc function returns the character written. If a write error occurs, the error indicator for the stream is set and putc returns EOF.
7.19.7.9 The putchar function
Synopsis
#include <stdio.h>
int putchar(int c);
Description
The putchar function is equivalent to putc with the second argument stdout.
Returns
The putchar function returns the character written. If a write error occurs, the error indicator for the stream is set and putchar returns EOF.
7.19.7.10 The puts function
Synopsis
#include <stdio.h>
int puts(const char *s);
Description
The puts function writes the string pointed to by s to the stream pointed to by stdout, and appends a new-line character to the output. The terminating null character is not written.
Returns
The puts function returns EOF if a write error occurs; otherwise it returns a nonnegative value.
7.19.7.11 The ungetc function
Synopsis
#include <stdio.h>
int ungetc(int c, FILE *stream);
Description
The ungetc function pushes the character specified by c (converted to an unsigned char) back onto the input stream pointed to by stream. Pushed-back characters will be returned by subsequent reads on that stream in the reverse order of their pushing. A successful intervening call (with the stream pointed to by stream) to a file positioning function (fseek, fsetpos, or rewind) discards any pushed-back characters for the stream. The external storage corresponding to the stream is unchanged.
One character of pushback is guaranteed. If the ungetc function is called too many times on the same stream without an intervening read or file positioning operation on that stream, the operation may fail.
If the value of c equals that of the macro EOF, the operation fails and the input stream is unchanged.
A successful call to the ungetc function clears the end-of-file indicator for the stream. The value of the file position indicator for the stream after reading or discarding all pushed-back characters shall be the same as it was before the characters were pushed back. For a text stream, the value of its file position indicator after a successful call to the ungetc function is unspecified until all pushed-back characters are read or discarded. For a binary stream, its file position indicator is decremented by each successful call to the ungetc function; if its value was zero before a call, it is indeterminate after the call.256)
Returns
The ungetc function returns the character pushed back after conversion, or EOF if the operation fails. Forward references: file positioning functions ( 7.19.9 File positioning functions ).
7.19.8 Direct input/output functions
7.19.8.1 The fread function
Synopsis
#include <stdio.h>
size_t fread(void * restrict ptr,
size_t size, size_t nmemb,
FILE * restrict stream);
Description
The fread function reads, into the array pointed to by ptr, up to nmemb elements whose size is specified by size, from the stream pointed to by stream. For each object, size calls are made to the fgetc function and the results stored, in the order read, in an array of unsigned char exactly overlaying the object. The file position indicator for the stream (if defined) is advanced by the number of characters successfully read. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate. If a partial element is read, its value is indeterminate.
Returns
The fread function returns the number of elements successfully read, which may be less than nmemb if a read error or end-of-file is encountered. If size or nmemb is zero, fread returns zero and the contents of the array and the state of the stream remain unchanged.
7.19.8.2 The fwrite function
Synopsis
#include <stdio.h>
size_t fwrite(const void * restrict ptr,
size_t size, size_t nmemb,
FILE * restrict stream);
Description
The fwrite function writes, from the array pointed to by ptr, up to nmemb elements whose size is specified by size, to the stream pointed to by stream. For each object, size calls are made to the fputc function, taking the values (in order) from an array of unsigned char exactly overlaying the object. The file position indicator for the stream (if defined) is advanced by the number of characters successfully written. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate.
Returns
The fwrite function returns the number of elements successfully written, which will be less than nmemb only if a write error is encountered. If size or nmemb is zero, fwrite returns zero and the state of the stream remains unchanged.
7.19.9 File positioning functions
7.19.9.1 The fgetpos function
Synopsis
#include <stdio.h>
int fgetpos(FILE * restrict stream,
fpos_t * restrict pos);
Description
The fgetpos function stores the current values of the parse state (if any) and file position indicator for the stream pointed to by stream in the object pointed to by pos. The values stored contain unspecified information usable by the fsetpos function for repositioning the stream to its position at the time of the call to the fgetpos function.
Returns
If successful, the fgetpos function returns zero; on failure, the fgetpos function returns nonzero and stores an implementation-defined positive value in errno. Forward references: the fsetpos function ( 7.19.9.3 The fsetpos function ).
7.19.9.2 The fseek function
Synopsis
#include <stdio.h>
int fseek(FILE *stream, long int offset, int whence);
Description
The fseek function sets the file position indicator for the stream pointed to by stream. If a read or write error occurs, the error indicator for the stream is set and fseek fails.
For a binary stream, the new position, measured in characters from the beginning of the file, is obtained by adding offset to the position specified by whence. The specified position is the beginning of the file if whence is SEEK_SET, the current value of the file position indicator if SEEK_CUR, or end-of-file if SEEK_END. A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.
For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.
After determining the new position, a successful call to the fseek function undoes any effects of the ungetc function on the stream, clears the end-of-file indicator for the stream, and then establishes the new position. After a successful fseek call, the next operation on an update stream may be either input or output.
Returns
The fseek function returns nonzero only for a request that cannot be satisfied. Forward references: the ftell function ( 7.19.9.4 The ftell function ).
7.19.9.3 The fsetpos function
Synopsis
#include <stdio.h>
int fsetpos(FILE *stream, const fpos_t *pos);
Description
The fsetpos function sets the mbstate_t object (if any) and file position indicator for the stream pointed to by stream according to the value of the object pointed to by pos, which shall be a value obtained from an earlier successful call to the fgetpos function on a stream associated with the same file. If a read or write error occurs, the error indicator for the stream is set and fsetpos fails.
A successful call to the fsetpos function undoes any effects of the ungetc function on the stream, clears the end-of-file indicator for the stream, and then establishes the new parse state and position. After a successful fsetpos call, the next operation on an update stream may be either input or output.
Returns
If successful, the fsetpos function returns zero; on failure, the fsetpos function returns nonzero and stores an implementation-defined positive value in errno.
7.19.9.4 The ftell function
Synopsis
#include <stdio.h>
long int ftell(FILE *stream);
Description
The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.
Returns
If successful, the ftell function returns the current value of the file position indicator for the stream. On failure, the ftell function returns −1L and stores an implementation-defined positive value in errno.
7.19.9.5 The rewind function
Synopsis
#include <stdio.h>
void rewind(FILE *stream);
Description
The rewind function sets the file position indicator for the stream pointed to by stream to the beginning of the file. It is equivalent to
(void)fseek(stream, 0L, SEEK_SET)
except that the error indicator for the stream is also cleared.
Returns
The rewind function returns no value.
7.19.10 Error-handling functions
7.19.10.1 The clearerr function
Synopsis
#include <stdio.h>
void clearerr(FILE *stream);
Description
The clearerr function clears the end-of-file and error indicators for the stream pointed to by stream.
Returns
The clearerr function returns no value.
7.19.10.2 The feof function
Synopsis
#include <stdio.h>
int feof(FILE *stream);
Description
The feof function tests the end-of-file indicator for the stream pointed to by stream.
Returns
The feof function returns nonzero if and only if the end-of-file indicator is set for stream.
7.19.10.3 The ferror function
Synopsis
#include <stdio.h>
int ferror(FILE *stream);
Description
The ferror function tests the error indicator for the stream pointed to by stream.
Returns
The ferror function returns nonzero if and only if the error indicator is set for stream.
7.19.10.4 The perror function
Synopsis
#include <stdio.h>
void perror(const char *s);
Description
The perror function maps the error number in the integer expression errno to an error message. It writes a sequence of characters to the standard error stream thus: first (if s is not a null pointer and the character pointed to by s is not the null character), the string pointed to by s followed by a colon (:) and a space; then an appropriate error message string followed by a new-line character. The contents of the error message strings are the same as those returned by the strerror function with argument errno.
Returns
The perror function returns no value. Forward references: the strerror function ( 7.21.6.2 The strerror function ).
7.20 General utilities <stdlib.h>
The header <stdlib.h> declares five types and several functions of general utility, and defines several macros.257)
The types declared are size_t and wchar_t (both described in 7.17 Common definitions <stddef.h> ), div_t which is a structure type that is the type of the value returned by the div function, ldiv_t which is a structure type that is the type of the value returned by the ldiv function, and lldiv_t which is a structure type that is the type of the value returned by the lldiv function.
The macros defined are NULL (described in 7.17 Common definitions <stddef.h> );
EXIT_FAILURE
and
EXIT_SUCCESS
which expand to integer constant expressions that can be used as the argument to the exit function to return unsuccessful or successful termination status, respectively, to the host environment;
RAND_MAX
which expands to an integer constant expression that is the maximum value returned by the rand function; and
MB_CUR_MAX
which expands to a positive integer expression with type size_t that is the maximum number of bytes in a multibyte character for the extended character set specified by the current locale (category LC_CTYPE), which is never greater than MB_LEN_MAX.
7.20.1 Numeric conversion functions
The functions atof, atoi, atol, and atoll need not affect the value of the integer expression errno on an error. If the value of the result cannot be represented, the behavior is undefined.
7.20.1.1 The atof function
Synopsis
#include <stdlib.h>
double atof(const char *nptr);
Description
The atof function converts the initial portion of the string pointed to by nptr to double representation. Except for the behavior on error, it is equivalent to
strtod(nptr, (char **)NULL)
Returns
The atof function returns the converted value. Forward references: the strtod, strtof, and strtold functions ( 7.20.1.3 The strtod, strtof, and strtold functions ).
7.20.1.2 The atoi, atol, and atoll functions
Synopsis
#include <stdlib.h>
int atoi(const char *nptr);
long int atol(const char *nptr);
long long int atoll(const char *nptr);
Description
The atoi, atol, and atoll functions convert the initial portion of the string pointed to by nptr to int, long int, and long long int representation, respectively. Except for the behavior on error, they are equivalent to atoi: (int)strtol(nptr, (char **)NULL, 10) atol: strtol(nptr, (char **)NULL, 10) atoll: strtoll(nptr, (char **)NULL, 10)
Returns
The atoi, atol, and atoll functions return the converted value. Forward references: the strtol, strtoll, strtoul, and strtoull functions ( 7.20.1.4 The strtol, strtoll, strtoul, and strtoull functions ).
7.20.1.3 The strtod, strtof, and strtold functions
Synopsis
#include <stdlib.h>
double strtod(const char * restrict nptr,
char ** restrict endptr);
float strtof(const char * restrict nptr,
char ** restrict endptr);
long double strtold(const char * restrict nptr,
char ** restrict endptr);
Description
The strtod, strtof, and strtold functions convert the initial portion of the string pointed to by nptr to double, float, and long double representation, respectively. First, they decompose the input string into three parts: an initial, possibly empty, sequence of white-space characters (as specified by the isspace function), a subject sequence resembling a floating-point constant or representing an infinity or NaN; and a final string of one or more unrecognized characters, including the terminating null character of the input string. Then, they attempt to convert the subject sequence to a floating-point number, and return the result.
The expected form of the subject sequence is an optional plus or minus sign, then one of the following:
- a nonempty sequence of decimal digits optionally containing a decimal-point character, then an optional exponent part as defined in 6.4.4.2 ;
- a 0x or 0X, then a nonempty sequence of hexadecimal digits optionally containing a decimal-point character, then an optional binary exponent part as defined in 6.4.4.2 ;
- INF or INFINITY, ignoring case
- NAN or NAN(n-char-sequenceopt), ignoring case in the NAN part, where: n-char-sequence: digit nondigit n-char-sequence digit n-char-sequence nondigit The subject sequence is defined as the longest initial subsequence of the input string, starting with the first non-white-space character, that is of the expected form. The subject sequence contains no characters if the input string is not of the expected form.
If the subject sequence has the expected form for a floating-point number, the sequence of characters starting with the first digit or the decimal-point character (whichever occurs first) is interpreted as a floating constant according to the rules of 6.4.4.2 , except that the decimal-point character is used in place of a period, and that if neither an exponent part nor a decimal-point character appears in a decimal floating point number, or if a binary exponent part does not appear in a hexadecimal floating point number, an exponent part of the appropriate type with value zero is assumed to follow the last digit in the string. If the subject sequence begins with a minus sign, the sequence is interpreted as negated.258) A character sequence INF or INFINITY is interpreted as an infinity, if representable in the return type, else like a floating constant that is too large for the range of the return type. A character sequence NAN or NAN(n-char-sequenceopt), is interpreted as a quiet NaN, if supported in the return type, else like a subject sequence part that does not have the expected form; the meaning of the n-char sequences is implementation-defined.259) A pointer to the final string is stored in the object pointed to by endptr, provided that endptr is not a null pointer.
If the subject sequence has the hexadecimal form and FLT_RADIX is a power of 2, the value resulting from the conversion is correctly rounded.
In other than the "C" locale, additional locale-specific subject sequence forms may be accepted.
If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.
Recommended practice
If the subject sequence has the hexadecimal form, FLT_RADIX is not a power of 2, and the result is not exactly representable, the result should be one of the two numbers in the appropriate internal format that are adjacent to the hexadecimal floating source value, with the extra stipulation that the error should have a correct sign for the current rounding direction.
If the subject sequence has the decimal form and at most DECIMAL_DIG (defined in <float.h>) significant digits, the result should be correctly rounded. If the subject sequence D has the decimal form and more than DECIMAL_DIG significant digits, consider the two bounding, adjacent decimal strings L and U, both having DECIMAL_DIG significant digits, such that the values of L, D, and U satisfy L ≤ D ≤ U. The result should be one of the (equal or adjacent) values that would be obtained by correctly rounding L and U according to the current rounding direction, with the extra stipulation that the error with respect to D should have a correct sign for the current rounding direction.260)
Returns
The functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value is outside the range of representable values, plus or minus HUGE_VAL, HUGE_VALF, or HUGE_VALL is returned (according to the return type and sign of the value), and the value of the macro ERANGE is stored in errno. If the result underflows ( 7.12.1 Treatment of error conditions ), the functions return a value whose magnitude is no greater than the smallest normalized positive number in the return type; whether errno acquires the value ERANGE is implementation-defined.
7.20.1.4 The strtol, strtoll, strtoul, and strtoull functions
Synopsis
#include <stdlib.h>
long int strtol(
const char * restrict nptr,
char ** restrict endptr,
int base);
long long int strtoll(
const char * restrict nptr,
char ** restrict endptr,
int base);
unsigned long int strtoul(
const char * restrict nptr,
char ** restrict endptr,
int base);
unsigned long long int strtoull(
const char * restrict nptr,
char ** restrict endptr,
int base);
Description
The strtol, strtoll, strtoul, and strtoull functions convert the initial portion of the string pointed to by nptr to long int, long long int, unsigned long int, and unsigned long long int representation, respectively. First, they decompose the input string into three parts: an initial, possibly empty, sequence of white-space characters (as specified by the isspace function), a subject sequence resembling an integer represented in some radix determined by the value of base, and a final string of one or more unrecognized characters, including the terminating null character of the input string. Then, they attempt to convert the subject sequence to an integer, and return the result.
If the value of base is zero, the expected form of the subject sequence is that of an integer constant as described in 6.4.4.1 , optionally preceded by a plus or minus sign, but not including an integer suffix. If the value of base is between 2 and 36 (inclusive), the expected form of the subject sequence is a sequence of letters and digits representing an integer with the radix specified by base, optionally preceded by a plus or minus sign, but not including an integer suffix. The letters from a (or A) through z (or Z) are ascribed the values 10 through 35; only letters and digits whose ascribed values are less than that of base are permitted. If the value of base is 16, the characters 0x or 0X may optionally precede the sequence of letters and digits, following the sign if present.
The subject sequence is defined as the longest initial subsequence of the input string, starting with the first non-white-space character, that is of the expected form. The subject sequence contains no characters if the input string is empty or consists entirely of white space, or if the first non-white-space character is other than a sign or a permissible letter or digit.
If the subject sequence has the expected form and the value of base is zero, the sequence of characters starting with the first digit is interpreted as an integer constant according to the rules of 6.4.4.1. If the subject sequence has the expected form and the value of base is between 2 and 36, it is used as the base for conversion, ascribing to each letter its value as given above. If the subject sequence begins with a minus sign, the value resulting from the conversion is negated (in the return type). A pointer to the final string is stored in the object pointed to by endptr, provided that endptr is not a null pointer.
In other than the "C" locale, additional locale-specific subject sequence forms may be accepted.
If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.
Returns
The strtol, strtoll, strtoul, and strtoull functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value is outside the range of representable values, LONG_MIN, LONG_MAX, LLONG_MIN, LLONG_MAX, ULONG_MAX, or ULLONG_MAX is returned (according to the return type and sign of the value, if any), and the value of the macro ERANGE is stored in errno.
7.20.2 Pseudo-random sequence generation functions
7.20.2.1 The rand function
Synopsis
#include <stdlib.h>
int rand(void);
Description
The rand function computes a sequence of pseudo-random integers in the range 0 to RAND_MAX.
The implementation shall behave as if no library function calls the rand function.
Returns
The rand function returns a pseudo-random integer. Environmental limits
The value of the RAND_MAX macro shall be at least 32767.
7.20.2.2 The srand function
Synopsis
#include <stdlib.h>
void srand(unsigned int seed);
Description
The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.
The implementation shall behave as if no library function calls the srand function.
Returns
The srand function returns no value.
EXAMPLE The following functions define a portable implementation of rand and srand. static unsigned long int next = 1;
int rand(void) // RAND_MAX assumed to be 32767
{
next = next * 1103515245 + 12345;
return (unsigned int)(next/65536) % 32768;
}
void srand(unsigned int seed)
{
next = seed;
}
7.20.3 Memory management functions
The order and contiguity of storage allocated by successive calls to the calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated). The lifetime of an allocated object extends from the allocation until the deallocation. Each such allocation shall yield a pointer to an object disjoint from any other object. The pointer returned points to the start (lowest byte address) of the allocated space. If the space cannot be allocated, a null pointer is returned. If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
7.20.3.1 The calloc function
Synopsis
#include <stdlib.h>
void *calloc(size_t nmemb, size_t size);
Description
The calloc function allocates space for an array of nmemb objects, each of whose size is size. The space is initialized to all bits zero.261)
Returns
The calloc function returns either a null pointer or a pointer to the allocated space.
7.20.3.2 The free function
Synopsis
#include <stdlib.h>
void free(void *ptr);
Description
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
Returns
The free function returns no value.
7.20.3.3 The malloc function
Synopsis
#include <stdlib.h>
void *malloc(size_t size);
Description
The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.
Returns
The malloc function returns either a null pointer or a pointer to the allocated space.
7.20.3.4 The realloc function
Synopsis
#include <stdlib.h>
void *realloc(void *ptr, size_t size);
Description
The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.
If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.
Returns
The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object), or a null pointer if the new object could not be allocated.
7.20.4 Communication with the environment
7.20.4.1 The abort function
Synopsis
#include <stdlib.h>
void abort(void);
Description
The abort function causes abnormal program termination to occur, unless the signal SIGABRT is being caught and the signal handler does not return. Whether open streams with unwritten buffered data are flushed, open streams are closed, or temporary files are removed is implementation-defined. An implementation-defined form of the status unsuccessful termination is returned to the host environment by means of the function call raise(SIGABRT).
Returns
The abort function does not return to its caller.
7.20.4.2 The atexit function
Synopsis
#include <stdlib.h>
int atexit(void (*func)(void));
Description
The atexit function registers the function pointed to by func, to be called without arguments at normal program termination. Environmental limits
The implementation shall support the registration of at least 32 functions.
Returns
The atexit function returns zero if the registration succeeds, nonzero if it fails. Forward references: the exit function ( 7.20.4.3 The exit function ).
7.20.4.3 The exit function
Synopsis
#include <stdlib.h>
void exit(int status);
Description
The exit function causes normal program termination to occur. If more than one call to the exit function is executed by a program, the behavior is undefined.
First, all functions registered by the atexit function are called, in the reverse order of their registration, [262] except that a function is called after any previously registered functions that had already been called at the time it was registered. If, during the call to any such function, a call to the longjmp function is made that would terminate the call to the registered function, the behavior is undefined.
Next, all open streams with unwritten buffered data are flushed, all open streams are closed, and all files created by the tmpfile function are removed.
Finally, control is returned to the host environment. If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.
Returns
The exit function cannot return to its caller.
7.20.4.4 The _Exit function
Synopsis
#include <stdlib.h>
void _Exit(int status);
Description
The _Exit function causes normal program termination to occur and control to be returned to the host environment. No functions registered by the atexit function or signal handlers registered by the signal function are called. The status returned to the host environment is determined in the same way as for the exit function ( 7.20.4.3 The exit function ). Whether open streams with unwritten buffered data are flushed, open streams are closed, or temporary files are removed is implementation-defined.
Returns
The _Exit function cannot return to its caller.
7.20.4.5 The getenv function
Synopsis
#include <stdlib.h>
char *getenv(const char *name);
Description
The getenv function searches an environment list, provided by the host environment, for a string that matches the string pointed to by name. The set of environment names and the method for altering the environment list are implementation-defined.
The implementation shall behave as if no library function calls the getenv function.
Returns
The getenv function returns a pointer to a string associated with the matched list member. The string pointed to shall not be modified by the program, but may be overwritten by a subsequent call to the getenv function. If the specified name cannot be found, a null pointer is returned.
7.20.4.6 The system function
Synopsis
#include <stdlib.h>
int system(const char *string);
Description
If string is a null pointer, the system function determines whether the host environment has a command processor. If string is not a null pointer, the system function passes the string pointed to by string to that command processor to be executed in a manner which the implementation shall document; this might then cause the program calling system to behave in a non-conforming manner or to terminate.
Returns
If the argument is a null pointer, the system function returns nonzero only if a command processor is available. If the argument is not a null pointer, and the system function does return, it returns an implementation-defined value.
7.20.5 Searching and sorting utilities
These utilities make use of a comparison function to search or sort arrays of unspecified type. Where an argument declared as size_t nmemb specifies the length of the array for a function, nmemb can have the value zero on a call to that function; the comparison function is not called, a search finds no matching element, and sorting performs no rearrangement. Pointer arguments on such a call shall still have valid values, as described in 7.1.4.
The implementation shall ensure that the second argument of the comparison function (when called from bsearch), or both arguments (when called from qsort), are pointers to elements of the array.263) The first argument when called from bsearch shall equal key.
The comparison function shall not alter the contents of the array. The implementation may reorder elements of the array between calls to the comparison function, but shall not alter the contents of any individual element.
When the same objects (consisting of size bytes, irrespective of their current positions in the array) are passed more than once to the comparison function, the results shall be consistent with one another. That is, for qsort they shall define a total ordering on the array, and for bsearch the same object shall always compare the same way with the key.
A sequence point occurs immediately before and immediately after each call to the comparison function, and also between any call to the comparison function and any movement of the objects passed as arguments to that call.
7.20.5.1 The bsearch function
Synopsis
#include <stdlib.h>
void *bsearch(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
Description
The bsearch function searches an array of nmemb objects, the initial element of which is pointed to by base, for an element that matches the object pointed to by key. The size of each element of the array is specified by size.
The comparison function pointed to by compar is called with two arguments that point to the key object and to an array element, in that order. The function shall return an integer less than, equal to, or greater than zero if the key object is considered, respectively, to be less than, to match, or to be greater than the array element. The array shall consist of: all the elements that compare less than, all the elements that compare equal to, and all the elements that compare greater than the key object, in that order.264)
Returns
The bsearch function returns a pointer to a matching element of the array, or a null pointer if no match is found. If two elements compare as equal, which element is matched is unspecified.
7.20.5.2 The qsort function
Synopsis
#include <stdlib.h>
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
Description
The qsort function sorts an array of nmemb objects, the initial element of which is pointed to by base. The size of each object is specified by size.
The contents of the array are sorted into ascending order according to a comparison function pointed to by compar, which is called with two arguments that point to the objects being compared. The function shall return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
If two elements compare as equal, their order in the resulting sorted array is unspecified.
Returns
The qsort function returns no value.
7.20.6 Integer arithmetic functions
7.20.6.1 The abs, labs and llabs functions
Synopsis
#include <stdlib.h>
int abs(int j);
long int labs(long int j);
long long int llabs(long long int j);
Description
The abs, labs, and llabs functions compute the absolute value of an integer j. If the result cannot be represented, the behavior is undefined.265)
Returns
The abs, labs, and llabs, functions return the absolute value.
7.20.6.2 The div, ldiv, and lldiv functions
Synopsis
#include <stdlib.h>
div_t div(int numer, int denom);
ldiv_t ldiv(long int numer, long int denom);
lldiv_t lldiv(long long int numer, long long int denom);
Description
The div, ldiv, and lldiv, functions compute numer / denom and numer % denom in a single operation.
Returns
The div, ldiv, and lldiv functions return a structure of type div_t, ldiv_t, and lldiv_t, respectively, comprising both the quotient and the remainder. The structures shall contain (in either order) the members quot (the quotient) and rem (the remainder), each of which has the same type as the arguments numer and denom. If either part of the result cannot be represented, the behavior is undefined.
7.20.7 Multibyte/wide character conversion functions
The behavior of the multibyte character functions is affected by the LC_CTYPE category of the current locale. For a state-dependent encoding, each function is placed into its initial conversion state by a call for which its character pointer argument, s, is a null pointer. Subsequent calls with s as other than a null pointer cause the internal conversion state of the function to be altered as necessary. A call with s as a null pointer causes these functions to return a nonzero value if encodings have state dependency, and zero otherwise.266) Changing the LC_CTYPE category causes the conversion state of these functions to be indeterminate.
7.20.7.1 The mblen function
Synopsis
#include <stdlib.h>
int mblen(const char *s, size_t n);
Description
If s is not a null pointer, the mblen function determines the number of bytes contained in the multibyte character pointed to by s. Except that the conversion state of the mbtowc function is not affected, it is equivalent to
mbtowc((wchar_t *)0, s, n);
The implementation shall behave as if no library function calls the mblen function.
Returns
If s is a null pointer, the mblen function returns a nonzero or zero value, if multibyte character encodings, respectively, do or do not have state-dependent encodings. If s is not a null pointer, the mblen function either returns 0 (if s points to the null character), or returns the number of bytes that are contained in the multibyte character (if the next n or fewer bytes form a valid multibyte character), or returns −1 (if they do not form a valid multibyte character). Forward references: the mbtowc function ( 7.20.7.2 The mbtowc function ).
7.20.7.2 The mbtowc function
Synopsis
#include <stdlib.h>
int mbtowc(wchar_t * restrict pwc,
const char * restrict s,
size_t n);
Description
If s is not a null pointer, the mbtowc function inspects at most n bytes beginning with the byte pointed to by s to determine the number of bytes needed to complete the next multibyte character (including any shift sequences). If the function determines that the next multibyte character is complete and valid, it determines the value of the corresponding wide character and then, if pwc is not a null pointer, stores that value in the object pointed to by pwc. If the corresponding wide character is the null wide character, the function is left in the initial conversion state.
The implementation shall behave as if no library function calls the mbtowc function.
Returns
If s is a null pointer, the mbtowc function returns a nonzero or zero value, if multibyte character encodings, respectively, do or do not have state-dependent encodings. If s is not a null pointer, the mbtowc function either returns 0 (if s points to the null character), or returns the number of bytes that are contained in the converted multibyte character (if the next n or fewer bytes form a valid multibyte character), or returns −1 (if they do not form a valid multibyte character).
In no case will the value returned be greater than n or the value of the MB_CUR_MAX macro.
7.20.7.3 The wctomb function
Synopsis
#include <stdlib.h>
int wctomb(char *s, wchar_t wc);
Description
The wctomb function determines the number of bytes needed to represent the multibyte character corresponding to the wide character given by wc (including any shift sequences), and stores the multibyte character representation in the array whose first element is pointed to by s (if s is not a null pointer). At most MB_CUR_MAX characters are stored. If wc is a null wide character, a null byte is stored, preceded by any shift sequence needed to restore the initial shift state, and the function is left in the initial conversion state.
The implementation shall behave as if no library function calls the wctomb function.
Returns
If s is a null pointer, the wctomb function returns a nonzero or zero value, if multibyte character encodings, respectively, do or do not have state-dependent encodings. If s is not a null pointer, the wctomb function returns −1 if the value of wc does not correspond to a valid multibyte character, or returns the number of bytes that are contained in the multibyte character corresponding to the value of wc.
In no case will the value returned be greater than the value of the MB_CUR_MAX macro.
7.20.8 Multibyte/wide string conversion functions
The behavior of the multibyte string functions is affected by the LC_CTYPE category of the current locale.
7.20.8.1 The mbstowcs function
Synopsis
#include <stdlib.h>
size_t mbstowcs(wchar_t * restrict pwcs,
const char * restrict s,
size_t n);
Description
The mbstowcs function converts a sequence of multibyte characters that begins in the initial shift state from the array pointed to by s into a sequence of corresponding wide characters and stores not more than n wide characters into the array pointed to by pwcs. No multibyte characters that follow a null character (which is converted into a null wide character) will be examined or converted. Each multibyte character is converted as if by a call to the mbtowc function, except that the conversion state of the mbtowc function is not affected.
No more than n elements will be modified in the array pointed to by pwcs. If copying takes place between objects that overlap, the behavior is undefined.
Returns
If an invalid multibyte character is encountered, the mbstowcs function returns (size_t)(-1). Otherwise, the mbstowcs function returns the number of array elements modified, not including a terminating null wide character, if any.267)
7.20.8.2 The wcstombs function
Synopsis
#include <stdlib.h>
size_t wcstombs(char * restrict s,
const wchar_t * restrict pwcs,
size_t n);
Description
The wcstombs function converts a sequence of wide characters from the array pointed to by pwcs into a sequence of corresponding multibyte characters that begins in the initial shift state, and stores these multibyte characters into the array pointed to by s, stopping if a multibyte character would exceed the limit of n total bytes or if a null character is stored. Each wide character is converted as if by a call to the wctomb function, except that the conversion state of the wctomb function is not affected.
No more than n bytes will be modified in the array pointed to by s. If copying takes place between objects that overlap, the behavior is undefined.
Returns
If a wide character is encountered that does not correspond to a valid multibyte character, the wcstombs function returns (size_t)(-1). Otherwise, the wcstombs function returns the number of bytes modified, not including a terminating null character, if any.267)
7.21 String handling <string.h>
7.21.1 String function conventions
The header <string.h> declares one type and several functions, and defines one macro useful for manipulating arrays of character type and other objects treated as arrays of character type.268) The type is size_t and the macro is NULL (both described in 7.17 Common definitions <stddef.h> ). Various methods are used for determining the lengths of the arrays, but in all cases a char * or void * argument points to the initial (lowest addressed) character of the array. If an array is accessed beyond the end of an object, the behavior is undefined.
Where an argument declared as size_t n specifies the length of the array for a function, n can have the value zero on a call to that function. Unless explicitly stated otherwise in the description of a particular function in this subclause, pointer arguments on such a call shall still have valid values, as described in 7.1.4. On such a call, a function that locates a character finds no occurrence, a function that compares two character sequences returns zero, and a function that copies characters copies zero characters.
For all functions in this subclause, each character shall be interpreted as if it had the type unsigned char (and therefore every possible object representation is valid and has a different value).
7.21.2 Copying functions
7.21.2.1 The memcpy function
Synopsis
#include <string.h>
void *memcpy(void * restrict s1,
const void * restrict s2,
size_t n);
Description
The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.
Returns
The memcpy function returns the value of s1.
7.21.2.2 The memmove function
Synopsis
#include <string.h>
void *memmove(void *s1, const void *s2, size_t n);
Description
The memmove function copies n characters from the object pointed to by s2 into the object pointed to by s1. Copying takes place as if the n characters from the object pointed to by s2 are first copied into a temporary array of n characters that does not overlap the objects pointed to by s1 and s2, and then the n characters from the temporary array are copied into the object pointed to by s1.
Returns
The memmove function returns the value of s1.
7.21.2.3 The strcpy function
Synopsis
#include <string.h>
char *strcpy(char * restrict s1,
const char * restrict s2);
Description
The strcpy function copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.
Returns
The strcpy function returns the value of s1.
7.21.2.4 The strncpy function
Synopsis
#include <string.h>
char *strncpy(char * restrict s1,
const char * restrict s2,
size_t n);
Description
The strncpy function copies not more than n characters (characters that follow a null character are not copied) from the array pointed to by s2 to the array pointed to by s 1.269 ) If copying takes place between objects that overlap, the behavior is undefined.
If the array pointed to by s2 is a string that is shorter than n characters, null characters are appended to the copy in the array pointed to by s1, until n characters in all have been written.
Returns
The strncpy function returns the value of s1.
7.21.3 Concatenation functions
7.21.3.1 The strcat function
Synopsis
#include <string.h>
char *strcat(char * restrict s1,
const char * restrict s2);
Description
The strcat function appends a copy of the string pointed to by s2 (including the terminating null character) to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1. If copying takes place between objects that overlap, the behavior is undefined.
Returns
The strcat function returns the value of s1.
7.21.3.2 The strncat function
Synopsis
#include <string.h>
char *strncat(char * restrict s1,
const char * restrict s2,
size_t n);
Description
The strncat function appends not more than n characters (a null character and characters that follow it are not appended) from the array pointed to by s2 to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1. A terminating null character is always appended to the result.270) If copying takes place between objects that overlap, the behavior is undefined.
Returns
The strncat function returns the value of s1. Forward references: the strlen function ( 7.21.6.3 The strlen function ).
7.21.4 Comparison functions
The sign of a nonzero value returned by the comparison functions memcmp, strcmp, and strncmp is determined by the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char) that differ in the objects being compared.
7.21.4.1 The memcmp function
Synopsis
#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n);
Description
The memcmp function compares the first n characters of the object pointed to by s1 to the first n characters of the object pointed to by s 2.271 )
Returns
The memcmp function returns an integer greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2.
7.21.4.2 The strcmp function
Synopsis
#include <string.h>
int strcmp(const char *s1, const char *s2);
Description
The strcmp function compares the string pointed to by s1 to the string pointed to by s2.
Returns
The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.
7.21.4.3 The strcoll function
Synopsis
#include <string.h>
int strcoll(const char *s1, const char *s2);
Description
The strcoll function compares the string pointed to by s1 to the string pointed to by s2, both interpreted as appropriate to the LC_COLLATE category of the current locale.
Returns
The strcoll function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2 when both are interpreted as appropriate to the current locale.
7.21.4.4 The strncmp function
Synopsis
#include <string.h>
int strncmp(const char *s1, const char *s2, size_t n);
Description
The strncmp function compares not more than n characters (characters that follow a null character are not compared) from the array pointed to by s1 to the array pointed to by s2.
Returns
The strncmp function returns an integer greater than, equal to, or less than zero, accordingly as the possibly null-terminated array pointed to by s1 is greater than, equal to, or less than the possibly null-terminated array pointed to by s2.
7.21.4.5 The strxfrm function
Synopsis
#include <string.h>
size_t strxfrm(char * restrict s1,
const char * restrict s2,
size_t n);
Description
The strxfrm function transforms the string pointed to by s2 and places the resulting string into the array pointed to by s1. The transformation is such that if the strcmp function is applied to two transformed strings, it returns a value greater than, equal to, or less than zero, corresponding to the result of the strcoll function applied to the same two original strings. No more than n characters are placed into the resulting array pointed to by s1, including the terminating null character. If n is zero, s1 is permitted to be a null pointer. If copying takes place between objects that overlap, the behavior is undefined.
Returns
The strxfrm function returns the length of the transformed string (not including the terminating null character). If the value returned is n or more, the contents of the array pointed to by s1 are indeterminate.
EXAMPLE The value of the following expression is the size of the array needed to hold the transformation of the string pointed to by s. 1 + strxfrm(NULL, s, 0)
7.21.5 Search functions
7.21.5.1 The memchr function
Synopsis
#include <string.h>
void *memchr(const void *s, int c, size_t n);
Description
The memchr function locates the first occurrence of c (converted to an unsigned char) in the initial n characters (each interpreted as unsigned char) of the object pointed to by s.
Returns
The memchr function returns a pointer to the located character, or a null pointer if the character does not occur in the object.
7.21.5.2 The strchr function
Synopsis
#include <string.h>
char *strchr(const char *s, int c);
Description
The strchr function locates the first occurrence of c (converted to a char) in the string pointed to by s. The terminating null character is considered to be part of the string.
Returns
The strchr function returns a pointer to the located character, or a null pointer if the character does not occur in the string.
7.21.5.3 The strcspn function
Synopsis
#include <string.h>
size_t strcspn(const char *s1, const char *s2);
Description
The strcspn function computes the length of the maximum initial segment of the string pointed to by s1 which consists entirely of characters not from the string pointed to by s2.
Returns
The strcspn function returns the length of the segment.
7.21.5.4 The strpbrk function
Synopsis
#include <string.h>
char *strpbrk(const char *s1, const char *s2);
Description
The strpbrk function locates the first occurrence in the string pointed to by s1 of any character from the string pointed to by s2.
Returns
The strpbrk function returns a pointer to the character, or a null pointer if no character from s2 occurs in s1.
7.21.5.5 The strrchr function
Synopsis
#include <string.h>
char *strrchr(const char *s, int c);
Description
The strrchr function locates the last occurrence of c (converted to a char) in the string pointed to by s. The terminating null character is considered to be part of the string.
Returns
The strrchr function returns a pointer to the character, or a null pointer if c does not occur in the string.
7.21.5.6 The strspn function
Synopsis
#include <string.h>
size_t strspn(const char *s1, const char *s2);
Description
The strspn function computes the length of the maximum initial segment of the string pointed to by s1 which consists entirely of characters from the string pointed to by s2.
Returns
The strspn function returns the length of the segment.
7.21.5.7 The strstr function
Synopsis
#include <string.h>
char *strstr(const char *s1, const char *s2);
Description
The strstr function locates the first occurrence in the string pointed to by s1 of the sequence of characters (excluding the terminating null character) in the string pointed to by s2.
Returns
The strstr function returns a pointer to the located string, or a null pointer if the string is not found. If s2 points to a string with zero length, the function returns s1.
7.21.5.8 The strtok function
Synopsis
#include <string.h>
char *strtok(char * restrict s1,
const char * restrict s2);
Description
A sequence of calls to the strtok function breaks the string pointed to by s1 into a sequence of tokens, each of which is delimited by a character from the string pointed to by s2. The first call in the sequence has a non-null first argument; subsequent calls in the sequence have a null first argument. The separator string pointed to by s2 may be different from call to call.
The first call in the sequence searches the string pointed to by s1 for the first character that is not contained in the current separator string pointed to by s2. If no such character is found, then there are no tokens in the string pointed to by s1 and the strtok function returns a null pointer. If such a character is found, it is the start of the first token.
The strtok function then searches from there for a character that is contained in the current separator string. If no such character is found, the current token extends to the end of the string pointed to by s1, and subsequent searches for a token will return a null pointer. If such a character is found, it is overwritten by a null character, which terminates the current token. The strtok function saves a pointer to the following character, from which the next search for a token will start.
Each subsequent call, with a null pointer as the value of the first argument, starts searching from the saved pointer and behaves as described above.
The implementation shall behave as if no library function calls the strtok function.
Returns
The strtok function returns a pointer to the first character of a token, or a null pointer if there is no token.
#include <string.h>
static char str[] = "?a???b,,,#c";
char *t;
t = strtok(str, "?"); // t points to the token "a"
t = strtok(NULL, ","); // t points to the token "??b"
t = strtok(NULL, "#,"); // t points to the token "c"
t = strtok(NULL, "?"); // t is a null pointer
7.21.6 Miscellaneous functions
7.21.6.1 The memset function
Synopsis
#include <string.h>
void *memset(void *s, int c, size_t n);
Description
The memset function copies the value of c (converted to an unsigned char) into each of the first n characters of the object pointed to by s.
Returns
The memset function returns the value of s.
7.21.6.2 The strerror function
Synopsis
#include <string.h>
char *strerror(int errnum);
Description
The strerror function maps the number in errnum to a message string. Typically, the values for errnum come from errno, but strerror shall map any value of type int to a message.
The implementation shall behave as if no library function calls the strerror function.
Returns
The strerror function returns a pointer to the string, the contents of which are locale-specific. The array pointed to shall not be modified by the program, but may be overwritten by a subsequent call to the strerror function.
7.21.6.3 The strlen function
Synopsis
#include <string.h>
size_t strlen(const char *s);
Description
The strlen function computes the length of the string pointed to by s.
Returns
The strlen function returns the number of characters that precede the terminating null character.
7.22 Type-generic math <tgmath.h>
The header <tgmath.h> includes the headers <math.h> and <complex.h> and defines several type-generic macros.
Of the <math.h> and <complex.h> functions without an f (float) or l (long double) suffix, several have one or more parameters whose corresponding real type is double. For each such function, except modf, there is a corresponding type-generic macro.272) The parameters whose corresponding real type is double in the function synopsis are generic parameters. Use of the macro invokes a function whose corresponding real type and type domain are determined by the arguments for the generic parameters.273)
Use of the macro invokes a function whose generic parameters have the corresponding real type determined as follows:
- First, if any argument for generic parameters has type long double, the type determined is long double.
- Otherwise, if any argument for generic parameters has type double or is of integer type, the type determined is double.
- Otherwise, the type determined is float.
For each unsuffixed function in <math.h> for which there is a function in <complex.h> with the same name except for a c prefix, the corresponding type-generic macro (for both functions) has the same name as the function in <math.h>. The corresponding type-generic macro for fabs and cabs is fabs.
<math.h> <complex.h> type-generic
function function macro
acos cacos acos
asin casin asin
atan catan atan
acosh cacosh acosh
asinh casinh asinh
atanh catanh atanh
cos ccos cos
sin csin sin
tan ctan tan
cosh ccosh cosh
sinh csinh sinh
tanh ctanh tanh
exp cexp exp
log clog log
pow cpow pow
sqrt csqrt sqrt
fabs cabs fabs
If at least one argument for a generic parameter is complex, then use of the macro invokes a complex function; otherwise, use of the macro invokes a real function.
For each unsuffixed function in <math.h> without a c-prefixed counterpart in <complex.h> (except modf), the corresponding type-generic macro has the same name as the function. These type-generic macros are:
atan2 fma llround remainder
cbrt fmax log10 remquo
ceil fmin log1p rint
copysign fmod log2 round
erf frexp logb scalbn
erfc hypot lrint scalbln
exp2 ilogb lround tgamma
expm1 ldexp nearbyint trunc
fdim lgamma nextafter
floor llrint nexttoward
If all arguments for generic parameters are real, then use of the macro invokes a real function; otherwise, use of the macro results in undefined behavior.
For each unsuffixed function in <complex.h> that is not a c-prefixed counterpart to a function in <math.h>, the corresponding type-generic macro has the same name as the function. These type-generic macros are:
carg conj creal
cimag cproj
Use of the macro with any real or complex argument invokes a complex function.
With the declarations
#include <tgmath.h>
int n;
float f;
double d;
long double ld;
float complex fc;
double complex dc;
long double complex ldc;
functions invoked by use of type-generic macros are shown in the following table:
macro use invokes
exp(n) exp(n), the function
acosh(f) acoshf(f)
sin(d) sin(d), the function
atan(ld) atanl(ld)
log(fc) clogf(fc)
sqrt(dc) csqrt(dc)
pow(ldc, f) cpowl(ldc, f)
remainder(n, n) remainder(n, n), the function
nextafter(d, f) nextafter(d, f), the function
nexttoward(f, ld) nexttowardf(f, ld)
copysign(n, ld) copysignl(n, ld)
ceil(fc) undefined behavior
rint(dc) undefined behavior
fmax(ldc, ld) undefined behavior
carg(n) carg(n), the function
cproj(f) cprojf(f)
creal(d) creal(d), the function
cimag(ld) cimagl(ld)
fabs(fc) cabsf(fc)
carg(dc) carg(dc), the function
cproj(ldc) cprojl(ldc)
7.23 Date and time <time.h>
7.23.1 Components of time
The header <time.h> defines two macros, and declares several types and functions for manipulating time. Many functions deal with a calendar time that represents the current date (according to the Gregorian calendar) and time. Some functions deal with local time, which is the calendar time expressed for some specific time zone, and with Daylight Saving Time, which is a temporary change in the algorithm for determining local time. The local time zone and Daylight Saving Time are implementation-defined.
The macros defined are NULL (described in 7.17 Common definitions <stddef.h> ); and
CLOCKS_PER_SEC
which expands to an expression with type clock_t (described below) that is the number per second of the value returned by the clock function.
The types declared are size_t (described in 7.17 Common definitions <stddef.h> ); clock_t and time_t which are arithmetic types capable of representing times; and
struct tm
which holds the components of a calendar time, called the broken-down time.
The range and precision of times representable in clock_t and time_t are implementation-defined. The tm structure shall contain at least the following members, in any order. The semantics of the members and their normal ranges are expressed in the comments.274)
int tm_sec; // seconds after the minute — [0, 60]
int tm_min; // minutes after the hour — [0, 59]
int tm_hour; // hours since midnight — [0, 23]
int tm_mday; // day of the month — [1, 31]
int tm_mon; // months since January — [0, 11]
int tm_year; // years since 1900
int tm_wday; // days since Sunday — [0, 6]
int tm_yday; // days since January 1 — [0, 365]
int tm_isdst; // Daylight Saving Time flag
The value of tm_isdst is positive if Daylight Saving Time is in effect, zero if Daylight Saving Time is not in effect, and negative if the information is not available.
7.23.2 Time manipulation functions
7.23.2.1 The clock function
Synopsis
#include <time.h>
clock_t clock(void);
Description
The clock function determines the processor time used.
Returns
The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation. To determine the time in seconds, the value returned by the clock function should be divided by the value of the macro CLOCKS_PER_SEC. If the processor time used is not available or its value cannot be represented, the function returns the value (clock_t)(-1).275)
7.23.2.2 The difftime function
Synopsis
#include <time.h>
double difftime(time_t time1, time_t time0);
Description
The difftime function computes the difference between two calendar times: time1 - time0.
Returns
The difftime function returns the difference expressed in seconds as a double.
7.23.2.3 The mktime function
Synopsis
#include <time.h>
time_t mktime(struct tm *timeptr);
Description
The mktime function converts the broken-down time, expressed as local time, in the structure pointed to by timeptr into a calendar time value with the same encoding as that of the values returned by the time function. The original values of the tm_wday and tm_yday components of the structure are ignored, and the original values of the other components are not restricted to the ranges indicated above.276) On successful completion, the values of the tm_wday and tm_yday components of the structure are set appropriately, and the other components are set to represent the specified calendar time, but with their values forced to the ranges indicated above; the final value of tm_mday is not set until tm_mon and tm_year are determined.
Returns
The mktime function returns the specified calendar time encoded as a value of type time_t. If the calendar time cannot be represented, the function returns the value (time_t)(-1).
What day of the week is July 4, 2001?
#include <stdio.h>
#include <time.h>
static const char *const wday[] = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "-unknown-"
};
struct tm time_str;
/* ... */
time_str.tm_year = 2001 - 1900;
time_str.tm_mon = 7 - 1;
time_str.tm_mday = 4;
time_str.tm_hour = 0;
time_str.tm_min = 0;
time_str.tm_sec = 1;
time_str.tm_isdst = -1;
if (mktime(&time_str) == (time_t)(-1))
time_str.tm_wday = 7;
printf("%s\n", wday[time_str.tm_wday]);
7.23.2.4 The time function
Synopsis
#include <time.h>
time_t time(time_t *timer);
Description
The time function determines the current calendar time. The encoding of the value is unspecified.
Returns
The time function returns the implementation’s best approximation to the current calendar time. The value (time_t)(-1) is returned if the calendar time is not available. If timer is not a null pointer, the return value is also assigned to the object it points to.
7.23.3 Time conversion functions
Except for the strftime function, these functions each return a pointer to one of two types of static objects: a broken-down time structure or an array of char. Execution of any of the functions that return a pointer to one of these object types may overwrite the information in any object of the same type pointed to by the value returned from any previous call to any of them. The implementation shall behave as if no other library functions call these functions.
7.23.3.1 The asctime function
Synopsis
#include <time.h>
char *asctime(const struct tm *timeptr);
Description
The asctime function converts the broken-down time in the structure pointed to by timeptr into a string in the form Sun Sep 16 01:03:52 1973\n\0 using the equivalent of the following algorithm.
char *asctime(const struct tm *timeptr)
{
static const char wday_name[7][3] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static const char mon_name[12][3] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static char result[26];
sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
wday_name[timeptr->tm_wday],
mon_name[timeptr->tm_mon],
timeptr->tm_mday, timeptr->tm_hour,
timeptr->tm_min, timeptr->tm_sec,
1900 + timeptr->tm_year);
return result;
}
Returns
The asctime function returns a pointer to the string.
7.23.3.2 The ctime function
Synopsis
#include <time.h>
char *ctime(const time_t *timer);
Description
The ctime function converts the calendar time pointed to by timer to local time in the form of a string. It is equivalent to
asctime(localtime(timer))
Returns
The ctime function returns the pointer returned by the asctime function with that broken-down time as argument. Forward references: the localtime function ( 7.23.3.4 The localtime function ).
7.23.3.3 The gmtime function
Synopsis
#include <time.h>
struct tm *gmtime(const time_t *timer);
Description
The gmtime function converts the calendar time pointed to by timer into a broken-down time, expressed as UTC.
Returns
The gmtime function returns a pointer to the broken-down time, or a null pointer if the specified time cannot be converted to UTC.
7.23.3.4 The localtime function
Synopsis
#include <time.h>
struct tm *localtime(const time_t *timer);
Description
The localtime function converts the calendar time pointed to by timer into a broken-down time, expressed as local time.
Returns
The localtime function returns a pointer to the broken-down time, or a null pointer if the specified time cannot be converted to local time.
7.23.3.5 The strftime function
Synopsis
#include <time.h>
size_t strftime(char * restrict s,
size_t maxsize,
const char * restrict format,
const struct tm * restrict timeptr);
Description
The strftime function places characters into the array pointed to by s as controlled by the string pointed to by format. The format shall be a multibyte character sequence, beginning and ending in its initial shift state. The format string consists of zero or more conversion specifiers and ordinary multibyte characters. A conversion specifier consists of a % character, possibly followed by an E or O modifier character (described below), followed by a character that determines the behavior of the conversion specifier. All ordinary multibyte characters (including the terminating null character) are copied unchanged into the array. If copying takes place between objects that overlap, the behavior is undefined. No more than maxsize characters are placed into the array.
Each conversion specifier is replaced by appropriate characters as described in the following list. The appropriate characters are determined using the LC_TIME category of the current locale and by the values of zero or more members of the broken-down time structure pointed to by timeptr, as specified in brackets in the description. If any of the specified values is outside the normal range, the characters stored are unspecified. %a is replaced by the locale’s abbreviated weekday name. [tm_wday] %A is replaced by the locale’s full weekday name. [tm_wday] %b is replaced by the locale’s abbreviated month name. [tm_mon] %B is replaced by the locale’s full month name. [tm_mon] %c is replaced by the locale’s appropriate date and time representation. [all specified in 7.23.1 Components of time ] %C is replaced by the year divided by 100 and truncated to an integer, as a decimal number (00−99). [tm_year] %d is replaced by the day of the month as a decimal number (01−31). [tm_mday] %D is equivalent to ‘‘%m/%d/%y’’. [tm_mon, tm_mday, tm_year] %e is replaced by the day of the month as a decimal number (1−31); a single digit is preceded by a space. [tm_mday] %F is equivalent to ‘‘%Y−%m−%d’’ (the ISO 8601 date format). [tm_year, tm_mon, tm_mday] %g is replaced by the last 2 digits of the week-based year (see below) as a decimal number (00−99). [tm_year, tm_wday, tm_yday] %G is replaced by the week-based year (see below) as a decimal number (e.g., 1997). [tm_year, tm_wday, tm_yday] %h is equivalent to ‘‘%b’’. [tm_mon] %H is replaced by the hour (24-hour clock) as a decimal number (00−23). [tm_hour] %I is replaced by the hour (12-hour clock) as a decimal number (01−12). [tm_hour] %j is replaced by the day of the year as a decimal number (001−366). [tm_yday] %m is replaced by the month as a decimal number (01−12). [tm_mon] %M is replaced by the minute as a decimal number (00−59). [tm_min] %n is replaced by a new-line character. %p is replaced by the locale’s equivalent of the AM/PM designations associated with a 12-hour clock. [tm_hour] %r is replaced by the locale’s 12-hour clock time. [tm_hour, tm_min, tm_sec] %R is equivalent to ‘‘%H:%M’’. [tm_hour, tm_min] %S is replaced by the second as a decimal number (00−60). [tm_sec] %t is replaced by a horizontal-tab character. %T is equivalent to ‘‘%H:%M:%S’’ (the ISO 8601 time format). [tm_hour, tm_min, tm_sec] %u is replaced by the ISO 8601 weekday as a decimal number (1−7), where Monday is 1. [tm_wday] %U is replaced by the week number of the year (the first Sunday as the first day of week %OI is replaced by the hour (12-hour clock), using the locale’s alternative numeric symbols. %Om is replaced by the month, using the locale’s alternative numeric symbols. %OM is replaced by the minutes, using the locale’s alternative numeric symbols. %OS is replaced by the seconds, using the locale’s alternative numeric symbols. %Ou is replaced by the ISO 8601 weekday as a number in the locale’s alternative representation, where Monday is 1. %OU is replaced by the week number, using the locale’s alternative numeric symbols. %OV is replaced by the ISO 8601 week number, using the locale’s alternative numeric symbols. %Ow is replaced by the weekday as a number, using the locale’s alternative numeric symbols. %OW is replaced by the week number of the year, using the locale’s alternative numeric symbols. %Oy is replaced by the last 2 digits of the year, using the locale’s alternative numeric symbols. 5 %g, %G, and %V give values according to the ISO 8601 week-based year. In this system, weeks begin on a Monday and week 1 of the year is the week that includes January 4th, which is also the week that includes the first Thursday of the year, and is also the first week that contains at least four days in the year. If the first Monday of January is the 2nd, 3rd, or 4th, the preceding days are part of the last week of the preceding year; thus, for Saturday 2nd January 1999, %G is replaced by 1998 and %V is replaced by 53. If December 29th, 30th, or 31st is a Monday, it and any following days are part of week 1 of the following year. Thus, for Tuesday 30th December 1997, %G is replaced by 1998 and %V is replaced by 01.
- 6
- If a conversion specifier is not one of the above, the behavior is undefined.
- 7
- In the "C" locale, the E and O modifiers are ignored and the replacement strings for the following specifiers are: %a the first three characters of %A. %A one of ‘‘Sunday’’, ‘‘Monday’’, ... , ‘‘Saturday’’. %b the first three characters of %B. %B one of ‘‘January’’, ‘‘February’’, ... , ‘‘December’’. %c equivalent to ‘‘%a %b %e %T %Y’’. %p one of ‘‘AM’’ or ‘‘PM’’. %r equivalent to ‘‘%I:%M:%S %p’’. %x equivalent to ‘‘%m/%d/%y’’. %X equivalent to %T. %Z implementation-defined.
Returns
If the total number of resulting characters including the terminating null character is not more than maxsize, the strftime function returns the number of characters placed into the array pointed to by s not including the terminating null character. Otherwise, zero is returned and the contents of the array are indeterminate.
7.24 Extended multibyte and wide character utilities <wchar.h>
7.24.1 Introduction
The header <wchar.h> declares four data types, one tag, four macros, and many functions.277)
The types declared are wchar_t and size_t (both described in 7.17 Common definitions <stddef.h> ); mbstate_t which is an object type other than an array type that can hold the conversion state information necessary to convert between sequences of multibyte characters and wide characters; wint_t which is an integer type unchanged by default argument promotions that can hold any value corresponding to members of the extended character set, as well as at least one value that does not correspond to any member of the extended character set (see WEOF below); [278] and
struct tm
which is declared as an incomplete structure type (the contents are described in 7.23.1 Components of time ).
The macros defined are NULL (described in 7.17 Common definitions <stddef.h> ); WCHAR_MIN and WCHAR_MAX (described in 7.18.3 Limits of other integer types ); and
WEOF
which expands to a constant expression of type wint_t whose value does not correspond to any member of the extended character set.279) It is accepted (and returned) by several functions in this subclause to indicate end-of-file, that is, no more input from a stream. It is also used as a wide character value that does not correspond to any member of the extended character set.
The functions declared are grouped as follows:
- Functions that perform input and output of wide characters, or multibyte characters, or both;
- Functions that provide wide string numeric conversion;
- Functions that perform general wide string manipulation;
- Functions for wide string date and time conversion; and
- Functions that provide extended capabilities for conversion between multibyte and wide character sequences.
Unless explicitly stated otherwise, if the execution of a function described in this subclause causes copying to take place between objects that overlap, the behavior is undefined.
7.24.2 Formatted wide character input/output functions
The formatted wide character input/output functions shall behave as if there is a sequence point after the actions associated with each specifier.280)
7.24.2.1 The fwprintf function
Synopsis
#include <stdio.h>
#include <wchar.h>
int fwprintf(FILE * restrict stream,
const wchar_t * restrict format, ...);
Description
The fwprintf function writes output to the stream pointed to by stream, under control of the wide string pointed to by format that specifies how subsequent arguments are converted for output. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. The fwprintf function returns when the end of the format string is encountered.
The format is composed of zero or more directives: ordinary wide characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent arguments, converting them, if applicable, according to the corresponding conversion specifier, and then writing the result to the output stream.
Each conversion specification is introduced by the wide character %. After the %, the following appear in sequence:
- Zero or more flags (in any order) that modify the meaning of the conversion specification.
- An optional minimum field width. If the converted value has fewer wide characters than the field width, it is padded with spaces (by default) on the left (or right, if the left adjustment flag, described later, has been given) to the field width. The field width takes the form of an asterisk * (described later) or a nonnegative decimal integer.281)
- An optional precision that gives the minimum number of digits to appear for the d, i, o, u, x, and X conversions, the number of digits to appear after the decimal-point wide character for a, A, e, E, f, and F conversions, the maximum number of significant digits for the g and G conversions, or the maximum number of wide characters to be written for s conversions. The precision takes the form of a period (.) followed either by an asterisk * (described later) or by an optional decimal integer; if only the period is specified, the precision is taken as zero. If a precision appears with any other conversion specifier, the behavior is undefined.
- An optional length modifier that specifies the size of the argument.
- A conversion specifier wide character that specifies the type of conversion to be applied.
As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an int argument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted. A negative field width argument is taken as a - flag followed by a positive field width. A negative precision argument is taken as if the precision were omitted.
The flag wide characters and their meanings are:
- -
- The result of the conversion is left-justified within the field. (It is right-justified if this flag is not specified.)
- +
- The result of a signed conversion always begins with a plus or minus sign. (It begins with a sign only when a negative value is converted if this flag is not specified.)282)
- space
- If the first wide character of a signed conversion is not a sign, or if a signed conversion results in no wide characters, a space is prefixed to the result. If the space and + flags both appear, the space flag is ignored.
- #
- The result is converted to an ‘‘alternative form’’. For o conversion, it increases the precision, if and only if necessary, to force the first digit of the result to be a zero (if the value and precision are both 0, a single 0 is printed). For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it. For a, A, e, E, f, F, g, and G conversions, the result of converting a floating-point number always contains a decimal-point wide character, even if no digits follow it. (Normally, a decimal-point wide character appears in the result of these conversions only if a digit follows it.) For g and G conversions, trailing zeros are not removed from the result. For other conversions, the behavior is undefined.
0 For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, leading zeros (following any indication of sign or base) are used to pad to the field width rather than performing space padding, except when converting an infinity or NaN. If the 0 and - flags both appear, the 0 flag is ignored. For d, i, o, u, x, and X conversions, if a precision is specified, the 0 flag is ignored. For other conversions, the behavior is undefined.
The length modifiers and their meanings are:
- hh
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following n conversion specifier applies to a pointer to a signed char argument.
- h
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to a short int or unsigned short int argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to short int or unsigned short int before printing); or that a following n conversion specifier applies to a pointer to a short int argument.
- l (ell)
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.
- ll (ell-ell)
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long long int or unsigned long long int argument; or that a following n conversion specifier applies to a pointer to a long long int argument.
- j
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to an intmax_t or uintmax_t argument; or that a following n conversion specifier applies to a pointer to an intmax_t argument.
- z
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to a size_t or the corresponding signed integer type argument; or that a following n conversion specifier applies to a pointer to a signed integer type corresponding to size_t argument.
- t
- Specifies that a following d, i, o, u, x, or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned integer type argument; or that a following n conversion specifier applies to a pointer to a ptrdiff_t argument.
- L
- Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument.
If a length modifier appears with any conversion specifier other than as specified above, the behavior is undefined.
The conversion specifiers and their meanings are: d,i The int argument is converted to signed decimal in the style [−]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no wide characters. o,u,x,X The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal notation (x or X) in the style dddd; the letters abcdef are used for x conversion and the letters ABCDEF for X conversion. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no wide characters. f,F A double argument representing a floating-point number is converted to decimal notation in the style [−]ddd.ddd, where the number of digits after the decimal-point wide character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is zero and the # flag is not specified, no decimal-point wide character appears. If a decimal-point wide character appears, at least one digit appears before it. The value is rounded to the appropriate number of digits. A double argument representing an infinity is converted in one of the styles [-]inf or [-]infinity — which style is implementation-defined. A double argument representing a NaN is converted in one of the styles [-]nan or [-]nan(n-wchar-sequence) — which style, and the meaning of any n-wchar-sequence, is implementation-defined. The F conversion specifier produces INF, INFINITY, or NAN instead of inf, infinity, or nan, respectively.283) e,E A double argument representing a floating-point number is converted in the style [−]d.ddd e±dd, where there is one digit (which is nonzero if the argument is nonzero) before the decimal-point wide 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 and the # flag is not specified, no decimal-point wide character appears. The value is rounded to the appropriate number of digits. The E conversion specifier produces a number with E instead of e introducing the exponent. The exponent always contains at least two digits, and only as many more digits as necessary to represent the exponent. If the value is zero, the exponent is zero. A double argument representing an infinity or NaN is converted in the style of an f or F conversion specifier. g,G A double argument representing a floating-point number is converted in style f or e (or in style F or E in the case of a G conversion specifier), depending on the value converted and the precision. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X :
- if P > X ≥ −4, the conversion is with style f (or F) and precision P − (X + 1).
- otherwise, the conversion is with style e (or E) and precision P − 1. Finally, unless the # flag is used, any trailing zeros are removed from the fractional portion of the result and the decimal-point wide character is removed if there is no fractional portion remaining. A double argument representing an infinity or NaN is converted in the style of an f or F conversion specifier. a,A A double argument representing a floating-point number is converted in the style [−]0xh.hhhh p±d, where there is one hexadecimal digit (which is nonzero if the argument is a normalized floating-point number and is otherwise unspecified) before the decimal-point wide character [284] and the number of hexadecimal digits after it is equal to the precision; if the precision is missing and FLT_RADIX is a power of 2, then the precision is sufficient for an exact representation of the value; if the precision is missing and FLT_RADIX is not a power of 2, then the precision is sufficient to distinguish [285] values of type double, except that trailing zeros may be omitted; if the precision is zero and the # flag is not specified, no decimal-point wide character appears. The letters abcdef are used for a conversion and the letters ABCDEF for A conversion. The A conversion specifier produces a number with X and P instead of x and p. The exponent always contains at least one digit, and only as many more digits as necessary to represent the decimal exponent of 2. If the value is zero, the exponent is zero. A double argument representing an infinity or NaN is converted in the style of an f or F conversion specifier. c If no l length modifier is present, the int argument is converted to a wide character as if by calling btowc and the resulting wide character is written. If an l length modifier is present, the wint_t argument is converted to wchar_t and written. s If no l length modifier is present, the argument shall be a pointer to the initial element of a character array containing a multibyte character sequence beginning in the initial shift state. Characters from the array are converted as if by repeated calls to the mbrtowc function, with the conversion state described by an mbstate_t object initialized to zero before the first multibyte character is converted, and written up to (but not including) the terminating null wide character. If the precision is specified, no more than that many wide characters are written. If the precision is not specified or is greater than the size of the converted array, the converted array shall contain a null wide character. If an l length modifier is present, the argument shall be a pointer to the initial element of an array of wchar_t type. Wide characters from the array are written up to (but not including) a terminating null wide character. If the precision is specified, no more than that many wide characters are written. If the precision is not specified or is greater than the size of the array, the array shall contain a null wide character. p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing wide characters, in an implementation-defined manner. n The argument shall be a pointer to signed integer into which is written the number of wide characters written to the output stream so far by this call to fwprintf. No argument is converted, but one is consumed. If the conversion specification includes any flags, a field width, or a precision, the behavior is undefined. % A % wide character is written. No argument is converted. The complete conversion specification shall be %%.
If a conversion specification is invalid, the behavior is undefined.286) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
In no case does a nonexistent 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.
For a and A conversions, if FLT_RADIX is a power of 2, the value is correctly rounded to a hexadecimal floating number with the given precision.
Recommended practice
For a and A conversions, if FLT_RADIX is not a power of 2 and the result is not exactly representable in the given precision, the result should be one of the two adjacent numbers in hexadecimal floating style with the given precision, with the extra stipulation that the error should have a correct sign for the current rounding direction.
For e, E, f, F, g, and G conversions, if the number of significant decimal digits is at most DECIMAL_DIG, then the result should be correctly rounded.287) If the number of significant decimal digits is more than DECIMAL_DIG but the source value is exactly representable with DECIMAL_DIG digits, then the result should be an exact representation with trailing zeros. Otherwise, the source value is bounded by two adjacent decimal strings L < U, both having DECIMAL_DIG significant digits; the value of the resultant decimal string D should satisfy L ≤ D ≤ U, with the extra stipulation that the error should have a correct sign for the current rounding direction.
Returns
The fwprintf function returns the number of wide characters transmitted, or a negative value if an output or encoding error occurred. Environmental limits
The number of wide characters that can be produced by any single conversion shall be at least 4095.
To print a date and time in the form ‘‘Sunday, July 3, 10:02’’ followed by π to five decimal places:
#include <math.h>
#include <stdio.h>
#include <wchar.h>
/* ... */
wchar_t *weekday, *month; // pointers to wide strings
int day, hour, min;
fwprintf(stdout, L"%ls, %ls %d, %.2d:%.2d\n",
weekday, month, day, hour, min);
fwprintf(stdout, L"pi = %.5f\n", 4 * atan(1.0));
Forward references: the btowc function ( 7.24.6.1.1 The btowc function ), the mbrtowc function ( 7.24.6.3.2 The mbrtowc function ).
7.24.2.2 The fwscanf function
Synopsis
#include <stdio.h>
#include <wchar.h>
int fwscanf(FILE * restrict stream,
const wchar_t * restrict format, ...);
Description
The fwscanf function reads input from the stream pointed to by stream, under control of the wide string pointed to by format that specifies the admissible input sequences and how they are to be converted for assignment, using subsequent arguments as pointers to the objects to receive the converted input. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored.
The format is composed of zero or more directives: one or more white-space wide characters, an ordinary wide character (neither % nor a white-space wide character), or a conversion specification. Each conversion specification is introduced by the wide character %. After the %, the following appear in sequence:
- An optional assignment-suppressing wide character *.
- An optional decimal integer greater than zero that specifies the maximum field width (in wide characters).
- An optional length modifier that specifies the size of the receiving object.
- A conversion specifier wide character that specifies the type of conversion to be applied.
The fwscanf function executes each directive of the format in turn. If a directive fails, as detailed below, the function returns. Failures are described as input failures (due to the occurrence of an encoding error or the unavailability of input characters), or matching failures (due to inappropriate input).
A directive composed of white-space wide character(s) is executed by reading input up to the first non-white-space wide character (which remains unread), or until no more wide characters can be read.
A directive that is an ordinary wide character is executed by reading the next wide character of the stream. If that wide character differs from the directive, the directive fails and the differing and subsequent wide characters remain unread. Similarly, if end-of-file, an encoding error, or a read error prevents a wide character from being read, the directive fails.
A directive that is a conversion specification defines a set of matching input sequences, as described below for each specifier. A conversion specification is executed in the following steps:
Input white-space wide characters (as specified by the iswspace function) are skipped, unless the specification includes a [, c, or n specifier.288)
An input item is read from the stream, unless the specification includes an n specifier. An input item is defined as the longest sequence of input wide characters which does not exceed any specified field width and which is, or is a prefix of, a matching input sequence.289) The first wide character, if any, after the input item remains unread. If the length of the input item is zero, the execution of the directive fails; this condition is a matching failure unless end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure.
Except in the case of a % specifier, the input item (or, in the case of a %n directive, the count of input wide characters) is converted to a type appropriate to the conversion specifier. If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure. Unless assignment suppression was indicated by a *, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.
The length modifiers and their meanings are:
- hh
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to signed char or unsigned char.
- h
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to short int or unsigned short int.
- l (ell)
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to long int or unsigned long int; that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double; or that a following c, s, or [ conversion specifier applies to an argument with type pointer to wchar_t.
- ll (ell-ell)
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to long long int or unsigned long long int.
- j
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to intmax_t or uintmax_t.
- z
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to size_t or the corresponding signed integer type.
- t
- Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to ptrdiff_t or the corresponding unsigned integer type.
- L
- Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to long double.
If a length modifier appears with any conversion specifier other than as specified above, the behavior is undefined.
The conversion specifiers and their meanings are:
- d
- Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the wcstol function with the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer.
- i
- Matches an optionally signed integer, whose format is the same as expected for the subject sequence of the wcstol function with the value 0 for the base argument. The corresponding argument shall be a pointer to signed integer.
- o
- Matches an optionally signed octal integer, whose format is the same as expected for the subject sequence of the wcstoul function with the value 8 for the base argument. The corresponding argument shall be a pointer to unsigned integer.
- u
- Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the wcstoul function with the value 10 for the base argument. The corresponding argument shall be a pointer to unsigned integer.
- x
- Matches an optionally signed hexadecimal integer, whose format is the same as expected for the subject sequence of the wcstoul function with the value 16 for the base argument. The corresponding argument shall be a pointer to unsigned integer.
- a,e,f,g
- Matches an optionally signed floating-point number, infinity, or NaN, whose format is the same as expected for the subject sequence of the wcstod function. The corresponding argument shall be a pointer to floating.
- c
- Matches a sequence of wide characters of exactly the number specified by the field width (1 if no field width is present in the directive). If no l length modifier is present, characters from the input field are converted as if by repeated calls to the wcrtomb function, with the conversion state described by an mbstate_t object initialized to zero before the first wide character is converted. The corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence. No null character is added. If an l length modifier is present, the corresponding argument shall be a pointer to the initial element of an array of wchar_t large enough to accept the sequence. No null wide character is added.
- s
- Matches a sequence of non-white-space wide characters. If no l length modifier is present, characters from the input field are converted as if by repeated calls to the wcrtomb function, with the conversion state described by an mbstate_t object initialized to zero before the first wide character is converted. The corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically. If an l length modifier is present, the corresponding argument shall be a pointer to the initial element of an array of wchar_t large enough to accept the sequence and the terminating null wide character, which will be added automatically.
- [
- Matches a nonempty sequence of wide characters from a set of expected characters (the scanset). If no l length modifier is present, characters from the input field are converted as if by repeated calls to the wcrtomb function, with the conversion state described by an mbstate_t object initialized to zero before the first wide character is converted. The corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically. If an l length modifier is present, the corresponding argument shall be a pointer to the initial element of an array of wchar_t large enough to accept the sequence and the terminating null wide character, which will be added automatically. The conversion specifier includes all subsequent wide characters in the format string, up to and including the matching right bracket (]). The wide characters between the brackets (the scanlist) compose the scanset, unless the wide character after the left bracket is a circumflex (^), in which case the scanset contains all wide characters that do not appear in the scanlist between the circumflex and the right bracket. If the conversion specifier begins with [] or [^], the right bracket wide character is in the scanlist and the next following right bracket wide character is the matching right bracket that ends the specification; otherwise the first following right bracket wide character is the one that ends the specification. If a - wide character is in the scanlist and is not the first, nor the second where the first wide character is a ^, nor the last character, the behavior is implementation-defined.
- p
- Matches an implementation-defined set of sequences, which should be the same as the set of sequences that may be produced by the %p conversion of the fwprintf function. The corresponding argument shall be a pointer to a pointer to void. The input item is converted to a pointer value in an implementation-defined manner. If the input item is a value converted earlier during the same program execution, the pointer that results shall compare equal to that value; otherwise the behavior of the %p conversion is undefined.
- n
- No input is consumed. The corresponding argument shall be a pointer to signed integer into which is to be written the number of wide characters read from the input stream so far by this call to the fwscanf function. Execution of a %n directive does not increment the assignment count returned at the completion of execution of the fwscanf function. No argument is converted, but one is consumed. If the conversion specification includes an assignment-suppressing wide character or a field width, the behavior is undefined.
- %
- Matches a single % wide character; no conversion or assignment occurs. The complete conversion specification shall be %%.
If a conversion specification is invalid, the behavior is undefined.290)
The conversion specifiers A, E, F, G, and X are also valid and behave the same as, respectively, a, e, f, g, and x.
Trailing white space (including new-line wide characters) is left unread unless matched by a directive. The success of literal matches and suppressed assignments is not directly determinable other than via the %n directive.
Returns
The fwscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
The call:
#include <stdio.h>
#include <wchar.h>
/* ... */
int n, i; float x; wchar_t name[50];
n = fwscanf(stdin, L"%d%f%ls", &i, &x, name);
with the input line: 25 54.32 E-1 thompson will assign to n the value 3, to i the value 25, to x the value 5.432 , and to name the sequence thompson\0.
The call:
#include <stdio.h>
#include <wchar.h>
/* ... */
int i; float x; double y;
fwscanf(stdin, L"%2d%f%*d %lf", &i, &x, &y);
with input: 56789 0123 56a72 will assign to i the value 56 and to x the value 789.0 , will skip past 0123, and will assign to y the value 56.0. The next wide character read from the input stream will be a. Forward references: the wcstod, wcstof, and wcstold functions ( 7.24.4.1.1 The wcstod, wcstof, and wcstold functions ), the wcstol, wcstoll, wcstoul, and wcstoull functions ( 7.24.4.1.2 The wcstol, wcstoll, wcstoul, and wcstoull functions ), the wcrtomb function ( 7.24.6.3.3 The wcrtomb function ).
7.24.2.3 The swprintf function
Synopsis
#include <wchar.h>
int swprintf(wchar_t * restrict s,
size_t n,
const wchar_t * restrict format, ...);
Description
The swprintf function is equivalent to fwprintf, except that the argument s specifies an array of wide characters into which the generated output is to be written, rather than written to a stream. No more than n wide characters are written, including a terminating null wide character, which is always added (unless n is zero).
Returns
The swprintf function returns the number of wide characters written in the array, not counting the terminating null wide character, or a negative value if an encoding error occurred or if n or more wide characters were requested to be written.
7.24.2.4 The swscanf function
Synopsis
#include <wchar.h>
int swscanf(const wchar_t * restrict s,
const wchar_t * restrict format, ...);
Description
The swscanf function is equivalent to fwscanf, except that the argument s specifies a wide string from which the input is to be obtained, rather than from a stream. Reaching the end of the wide string is equivalent to encountering end-of-file for the fwscanf function.
Returns
The swscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the swscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
7.24.2.5 The vfwprintf function
Synopsis
#include <stdarg.h>
#include <stdio.h>
#include <wchar.h>
int vfwprintf(FILE * restrict stream,
const wchar_t * restrict format,
va_list arg);
Description
The vfwprintf function is equivalent to fwprintf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vfwprintf function does not invoke the va_end macro.291)
Returns
The vfwprintf function returns the number of wide characters transmitted, or a negative value if an output or encoding error occurred.
The following shows the use of the vfwprintf function in a general error-reporting routine.
#include <stdarg.h>
#include <stdio.h>
#include <wchar.h>
void error(char *function_name, wchar_t *format, ...)
{
va_list args;
va_start(args, format);
// print out name of function causing error
fwprintf(stderr, L"ERROR in %s: ", function_name);
// print out remainder of message
vfwprintf(stderr, format, args);
va_end(args);
}
7.24.2.6 The vfwscanf function
Synopsis
#include <stdarg.h>
#include <stdio.h>
#include <wchar.h>
int vfwscanf(FILE * restrict stream,
const wchar_t * restrict format,
va_list arg);
Description
The vfwscanf function is equivalent to fwscanf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vfwscanf function does not invoke the va_end macro.291)
Returns
The vfwscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the vfwscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
7.24.2.7 The vswprintf function
Synopsis
#include <stdarg.h>
#include <wchar.h>
int vswprintf(wchar_t * restrict s,
size_t n,
const wchar_t * restrict format,
va_list arg);
Description
The vswprintf function is equivalent to swprintf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vswprintf function does not invoke the va_end macro.291)
Returns
The vswprintf function returns the number of wide characters written in the array, not counting the terminating null wide character, or a negative value if an encoding error occurred or if n or more wide characters were requested to be generated.
7.24.2.8 The vswscanf function
Synopsis
#include <stdarg.h>
#include <wchar.h>
int vswscanf(const wchar_t * restrict s,
const wchar_t * restrict format,
va_list arg);
Description
The vswscanf function is equivalent to swscanf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vswscanf function does not invoke the va_end macro.291)
Returns
The vswscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the vswscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
7.24.2.9 The vwprintf function
Synopsis
#include <stdarg.h>
#include <wchar.h>
int vwprintf(const wchar_t * restrict format,
va_list arg);
Description
The vwprintf function is equivalent to wprintf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vwprintf function does not invoke the va_end macro.291)
Returns
The vwprintf function returns the number of wide characters transmitted, or a negative value if an output or encoding error occurred.
7.24.2.10 The vwscanf function
Synopsis
#include <stdarg.h>
#include <wchar.h>
int vwscanf(const wchar_t * restrict format,
va_list arg);
Description
The vwscanf function is equivalent to wscanf, with the variable argument list replaced by arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls). The vwscanf function does not invoke the va_end macro.291)
Returns
The vwscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the vwscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
7.24.2.11 The wprintf function
Synopsis
#include <wchar.h>
int wprintf(const wchar_t * restrict format, ...);
Description
The wprintf function is equivalent to fwprintf with the argument stdout interposed before the arguments to wprintf.
Returns
The wprintf function returns the number of wide characters transmitted, or a negative value if an output or encoding error occurred.
7.24.2.12 The wscanf function
Synopsis
#include <wchar.h>
int wscanf(const wchar_t * restrict format, ...);
Description
The wscanf function is equivalent to fwscanf with the argument stdin interposed before the arguments to wscanf.
Returns
The wscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the wscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
7.24.3 Wide character input/output functions
7.24.3.1 The fgetwc function
Synopsis
#include <stdio.h>
#include <wchar.h>
wint_t fgetwc(FILE *stream);
Description
If the end-of-file indicator for the input stream pointed to by stream is not set and a next wide character is present, the fgetwc function obtains that wide character as a wchar_t converted to a wint_t and advances the associated file position indicator for the stream (if defined).
Returns
If the end-of-file indicator for the stream is set, or if the stream is at end-of-file, the end-of-file indicator for the stream is set and the fgetwc function returns WEOF. Otherwise, the fgetwc function returns the next wide character from the input stream pointed to by stream. If a read error occurs, the error indicator for the stream is set and the fgetwc function returns WEOF. If an encoding error occurs (including too few bytes), the value of the macro EILSEQ is stored in errno and the fgetwc function returns WEOF.292)
7.24.3.2 The fgetws function
Synopsis
#include <stdio.h>
#include <wchar.h>
wchar_t *fgetws(wchar_t * restrict s,
int n, FILE * restrict stream);
Description
The fgetws function reads at most one less than the number of wide characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional wide characters are read after a new-line wide character (which is retained) or after end-of-file. A null wide character is written immediately after the last wide character read into the array.
Returns
The fgetws function returns s if successful. If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned. If a read or encoding error occurs during the operation, the array contents are indeterminate and a null pointer is returned.
7.24.3.3 The fputwc function
Synopsis
#include <stdio.h>
#include <wchar.h>
wint_t fputwc(wchar_t c, FILE *stream);
Description
The fputwc function writes the wide character specified by c to the output stream pointed to by stream, at the position indicated by the associated file position indicator for the stream (if defined), and advances the indicator appropriately. If the file cannot support positioning requests, or if the stream was opened with append mode, the character is appended to the output stream.
Returns
The fputwc function returns the wide character written. If a write error occurs, the error indicator for the stream is set and fputwc returns WEOF. If an encoding error occurs, the value of the macro EILSEQ is stored in errno and fputwc returns WEOF.
7.24.3.4 The fputws function
Synopsis
#include <stdio.h>
#include <wchar.h>
int fputws(const wchar_t * restrict s,
FILE * restrict stream);
Description
The fputws function writes the wide string pointed to by s to the stream pointed to by stream. The terminating null wide character is not written.
Returns
The fputws function returns EOF if a write or encoding error occurs; otherwise, it returns a nonnegative value.
7.24.3.5 The fwide function
Synopsis
#include <stdio.h>
#include <wchar.h>
int fwide(FILE *stream, int mode);
Description
The fwide function determines the orientation of the stream pointed to by stream. If mode is greater than zero, the function first attempts to make the stream wide oriented. If mode is less than zero, the function first attempts to make the stream byte oriented.293) Otherwise, mode is zero and the function does not alter the orientation of the stream.
Returns
The fwide function returns a value greater than zero if, after the call, the stream has wide orientation, a value less than zero if the stream has byte orientation, or zero if the stream has no orientation.
7.24.3.6 The getwc function
Synopsis
#include <stdio.h>
#include <wchar.h>
wint_t getwc(FILE *stream);
Description
The getwc function is equivalent to fgetwc, except that if it is implemented as a macro, it may evaluate stream more than once, so the argument should never be an expression with side effects.
Returns
The getwc function returns the next wide character from the input stream pointed to by stream, or WEOF.
7.24.3.7 The getwchar function
Synopsis
#include <wchar.h>
wint_t getwchar(void);
Description
The getwchar function is equivalent to getwc with the argument stdin.
Returns
The getwchar function returns the next wide character from the input stream pointed to by stdin, or WEOF.
7.24.3.8 The putwc function
Synopsis
#include <stdio.h>
#include <wchar.h>
wint_t putwc(wchar_t c, FILE *stream);
Description
The putwc function is equivalent to fputwc, except that if it is implemented as a macro, it may evaluate stream more than once, so that argument should never be an expression with side effects.
Returns
The putwc function returns the wide character written, or WEOF.
7.24.3.9 The putwchar function
Synopsis
#include <wchar.h>
wint_t putwchar(wchar_t c);
Description
The putwchar function is equivalent to putwc with the second argument stdout.
Returns
The putwchar function returns the character written, or WEOF.
7.24.3.10 The ungetwc function
Synopsis
#include <stdio.h>
#include <wchar.h>
wint_t ungetwc(wint_t c, FILE *stream);
Description
The ungetwc function pushes the wide character specified by c back onto the input stream pointed to by stream. Pushed-back wide characters will be returned by subsequent reads on that stream in the reverse order of their pushing. A successful intervening call (with the stream pointed to by stream) to a file positioning function (fseek, fsetpos, or rewind) discards any pushed-back wide characters for the stream. The external storage corresponding to the stream is unchanged.
One wide character of pushback is guaranteed, even if the call to the ungetwc function follows just after a call to a formatted wide character input function fwscanf, vfwscanf, vwscanf, or wscanf. If the ungetwc function is called too many times on the same stream without an intervening read or file positioning operation on that stream, the operation may fail.
If the value of c equals that of the macro WEOF, the operation fails and the input stream is unchanged.
A successful call to the ungetwc function clears the end-of-file indicator for the stream. The value of the file position indicator for the stream after reading or discarding all pushed-back wide characters is the same as it was before the wide characters were pushed back. For a text or binary stream, the value of its file position indicator after a successful call to the ungetwc function is unspecified until all pushed-back wide characters are read or discarded.
Returns
The ungetwc function returns the wide character pushed back, or WEOF if the operation fails.
7.24.4 General wide string utilities
The header <wchar.h> declares a number of functions useful for wide string manipulation. Various methods are used for determining the lengths of the arrays, but in all cases a wchar_t * argument points to the initial (lowest addressed) element of the array. If an array is accessed beyond the end of an object, the behavior is undefined.
Where an argument declared as size_t n determines the length of the array for a function, n can have the value zero on a call to that function. Unless explicitly stated otherwise in the description of a particular function in this subclause, pointer arguments on such a call shall still have valid values, as described in 7.1.4. On such a call, a function that locates a wide character finds no occurrence, a function that compares two wide character sequences returns zero, and a function that copies wide characters copies zero wide characters.
7.24.4.1 Wide string numeric conversion functions
7.24.4.1.1 The wcstod, wcstof, and wcstold functions
Synopsis
#include <wchar.h>
double wcstod(const wchar_t * restrict nptr,
wchar_t ** restrict endptr);
float wcstof(const wchar_t * restrict nptr,
wchar_t ** restrict endptr);
long double wcstold(const wchar_t * restrict nptr,
wchar_t ** restrict endptr);
Description
The wcstod, wcstof, and wcstold functions convert the initial portion of the wide string pointed to by nptr to double, float, and long double representation, respectively. First, they decompose the input string into three parts: an initial, possibly empty, sequence of white-space wide characters (as specified by the iswspace function), a subject sequence resembling a floating-point constant or representing an infinity or NaN; and a final wide string of one or more unrecognized wide characters, including the terminating null wide character of the input wide string. Then, they attempt to convert the subject sequence to a floating-point number, and return the result.
The expected form of the subject sequence is an optional plus or minus sign, then one of the following:
- a nonempty sequence of decimal digits optionally containing a decimal-point wide character, then an optional exponent part as defined for the corresponding single-byte characters in 6.4.4.2 ;
- a 0x or 0X, then a nonempty sequence of hexadecimal digits optionally containing a decimal-point wide character, then an optional binary exponent part as defined in 6.4.4.2 ;
- INF or INFINITY, or any other wide string equivalent except for case
- NAN or NAN(n-wchar-sequenceopt), or any other wide string equivalent except for case in the NAN part, where: n-wchar-sequence: digit nondigit n-wchar-sequence digit n-wchar-sequence nondigit The subject sequence is defined as the longest initial subsequence of the input wide string, starting with the first non-white-space wide character, that is of the expected form. The subject sequence contains no wide characters if the input wide string is not of the expected form.
If the subject sequence has the expected form for a floating-point number, the sequence of wide characters starting with the first digit or the decimal-point wide character (whichever occurs first) is interpreted as a floating constant according to the rules of 6.4.4.2 , except that the decimal-point wide character is used in place of a period, and that if neither an exponent part nor a decimal-point wide character appears in a decimal floating point number, or if a binary exponent part does not appear in a hexadecimal floating point number, an exponent part of the appropriate type with value zero is assumed to follow the last digit in the string. If the subject sequence begins with a minus sign, the sequence is interpreted as negated.294) A wide character sequence INF or INFINITY is interpreted as an infinity, if representable in the return type, else like a floating constant that is too large for the range of the return type. A wide character sequence NAN or NAN(n-wchar-sequenceopt) is interpreted as a quiet NaN, if supported in the return type, else like a subject sequence part that does not have the expected form; the meaning of the n-wchar sequences is implementation-defined.295) A pointer to the final wide string is stored in the object pointed to by endptr, provided that endptr is not a null pointer.
If the subject sequence has the hexadecimal form and FLT_RADIX is a power of 2, the value resulting from the conversion is correctly rounded.
In other than the "C" locale, additional locale-specific subject sequence forms may be accepted.
If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.
Recommended practice
If the subject sequence has the hexadecimal form, FLT_RADIX is not a power of 2, and the result is not exactly representable, the result should be one of the two numbers in the appropriate internal format that are adjacent to the hexadecimal floating source value, with the extra stipulation that the error should have a correct sign for the current rounding direction.
If the subject sequence has the decimal form and at most DECIMAL_DIG (defined in <float.h>) significant digits, the result should be correctly rounded. If the subject sequence D has the decimal form and more than DECIMAL_DIG significant digits, consider the two bounding, adjacent decimal strings L and U, both having DECIMAL_DIG significant digits, such that the values of L, D, and U satisfy L ≤ D ≤ U. The result should be one of the (equal or adjacent) values that would be obtained by correctly rounding L and U according to the current rounding direction, with the extra stipulation that the error with respect to D should have a correct sign for the current rounding direction.296)
Returns
The functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value is outside the range of representable values, plus or minus HUGE_VAL, HUGE_VALF, or HUGE_VALL is returned (according to the return type and sign of the value), and the value of the macro ERANGE is stored in errno. If the result underflows ( 7.12.1 Treatment of error conditions ), the functions return a value whose magnitude is no greater than the smallest normalized positive number in the return type; whether errno acquires the value ERANGE is implementation-defined.
7.24.4.1.2 The wcstol, wcstoll, wcstoul, and wcstoull functions
Synopsis
#include <wchar.h>
long int wcstol(
const wchar_t * restrict nptr,
wchar_t ** restrict endptr,
int base);
long long int wcstoll(
const wchar_t * restrict nptr,
wchar_t ** restrict endptr,
int base);
unsigned long int wcstoul(
const wchar_t * restrict nptr,
wchar_t ** restrict endptr,
int base);
unsigned long long int wcstoull(
const wchar_t * restrict nptr,
wchar_t ** restrict endptr,
int base);
Description
The wcstol, wcstoll, wcstoul, and wcstoull functions convert the initial portion of the wide string pointed to by nptr to long int, long long int, unsigned long int, and unsigned long long int representation, respectively. First, they decompose the input string into three parts: an initial, possibly empty, sequence of white-space wide characters (as specified by the iswspace function), a subject sequence resembling an integer represented in some radix determined by the value of base, and a final wide string of one or more unrecognized wide characters, including the terminating null wide character of the input wide string. Then, they attempt to convert the subject sequence to an integer, and return the result.
If the value of base is zero, the expected form of the subject sequence is that of an integer constant as described for the corresponding single-byte characters in 6.4.4.1 , optionally preceded by a plus or minus sign, but not including an integer suffix. If the value of base is between 2 and 36 (inclusive), the expected form of the subject sequence is a sequence of letters and digits representing an integer with the radix specified by base, optionally preceded by a plus or minus sign, but not including an integer suffix. The letters from a (or A) through z (or Z) are ascribed the values 10 through 35; only letters and digits whose ascribed values are less than that of base are permitted. If the value of base is 16, the wide characters 0x or 0X may optionally precede the sequence of letters and digits, following the sign if present.
The subject sequence is defined as the longest initial subsequence of the input wide string, starting with the first non-white-space wide character, that is of the expected form. The subject sequence contains no wide characters if the input wide string is empty or consists entirely of white space, or if the first non-white-space wide character is other than a sign or a permissible letter or digit.
If the subject sequence has the expected form and the value of base is zero, the sequence of wide characters starting with the first digit is interpreted as an integer constant according to the rules of 6.4.4.1. If the subject sequence has the expected form and the value of base is between 2 and 36, it is used as the base for conversion, ascribing to each letter its value as given above. If the subject sequence begins with a minus sign, the value resulting from the conversion is negated (in the return type). A pointer to the final wide string is stored in the object pointed to by endptr, provided that endptr is not a null pointer.
In other than the "C" locale, additional locale-specific subject sequence forms may be accepted.
If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.
Returns
The wcstol, wcstoll, wcstoul, and wcstoull functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value is outside the range of representable values, LONG_MIN, LONG_MAX, LLONG_MIN, LLONG_MAX, ULONG_MAX, or ULLONG_MAX is returned (according to the return type sign of the value, if any), and the value of the macro ERANGE is stored in errno.
7.24.4.2 Wide string copying functions
7.24.4.2.1 The wcscpy function
Synopsis
#include <wchar.h>
wchar_t *wcscpy(wchar_t * restrict s1,
const wchar_t * restrict s2);
Description
The wcscpy function copies the wide string pointed to by s2 (including the terminating null wide character) into the array pointed to by s1.
Returns
The wcscpy function returns the value of s1.
7.24.4.2.2 The wcsncpy function
Synopsis
#include <wchar.h>
wchar_t *wcsncpy(wchar_t * restrict s1,
const wchar_t * restrict s2,
size_t n);
Description
The wcsncpy function copies not more than n wide characters (those that follow a null wide character are not copied) from the array pointed to by s2 to the array pointed to by s 1.297 )
If the array pointed to by s2 is a wide string that is shorter than n wide characters, null wide characters are appended to the copy in the array pointed to by s1, until n wide characters in all have been written.
Returns
The wcsncpy function returns the value of s1.
7.24.4.2.3 The wmemcpy function
Synopsis
#include <wchar.h>
wchar_t *wmemcpy(wchar_t * restrict s1,
const wchar_t * restrict s2,
size_t n);
Description
The wmemcpy function copies n wide characters from the object pointed to by s2 to the object pointed to by s1.
Returns
The wmemcpy function returns the value of s1.
7.24.4.2.4 The wmemmove function
Synopsis
#include <wchar.h>
wchar_t *wmemmove(wchar_t *s1, const wchar_t *s2,
size_t n);
Description
The wmemmove function copies n wide characters from the object pointed to by s2 to the object pointed to by s1. Copying takes place as if the n wide characters from the object pointed to by s2 are first copied into a temporary array of n wide characters that does not overlap the objects pointed to by s1 or s2, and then the n wide characters from the temporary array are copied into the object pointed to by s1.
Returns
The wmemmove function returns the value of s1.
7.24.4.3 Wide string concatenation functions
7.24.4.3.1 The wcscat function
Synopsis
#include <wchar.h>
wchar_t *wcscat(wchar_t * restrict s1,
const wchar_t * restrict s2);
Description
The wcscat function appends a copy of the wide string pointed to by s2 (including the terminating null wide character) to the end of the wide string pointed to by s1. The initial wide character of s2 overwrites the null wide character at the end of s1.
Returns
The wcscat function returns the value of s1.
7.24.4.3.2 The wcsncat function
Synopsis
#include <wchar.h>
wchar_t *wcsncat(wchar_t * restrict s1,
const wchar_t * restrict s2,
size_t n);
Description
The wcsncat function appends not more than n wide characters (a null wide character and those that follow it are not appended) from the array pointed to by s2 to the end of the wide string pointed to by s1. The initial wide character of s2 overwrites the null wide character at the end of s1. A terminating null wide character is always appended to the result.298)
Returns
The wcsncat function returns the value of s1.
7.24.4.4 Wide string comparison functions
Unless explicitly stated otherwise, the functions described in this subclause order two wide characters the same way as two integers of the underlying integer type designated by wchar_t.
7.24.4.4.1 The wcscmp function
Synopsis
#include <wchar.h>
int wcscmp(const wchar_t *s1, const wchar_t *s2);
Description
The wcscmp function compares the wide string pointed to by s1 to the wide string pointed to by s2.
Returns
The wcscmp function returns an integer greater than, equal to, or less than zero, accordingly as the wide string pointed to by s1 is greater than, equal to, or less than the wide string pointed to by s2.
7.24.4.4.2 The wcscoll function
Synopsis
#include <wchar.h>
int wcscoll(const wchar_t *s1, const wchar_t *s2);
Description
The wcscoll function compares the wide string pointed to by s1 to the wide string pointed to by s2, both interpreted as appropriate to the LC_COLLATE category of the current locale.
Returns
The wcscoll function returns an integer greater than, equal to, or less than zero, accordingly as the wide string pointed to by s1 is greater than, equal to, or less than the wide string pointed to by s2 when both are interpreted as appropriate to the current locale.
7.24.4.4.3 The wcsncmp function
Synopsis
#include <wchar.h>
int wcsncmp(const wchar_t *s1, const wchar_t *s2,
size_t n);
Description
The wcsncmp function compares not more than n wide characters (those that follow a null wide character are not compared) from the array pointed to by s1 to the array pointed to by s2.
Returns
The wcsncmp function returns an integer greater than, equal to, or less than zero, accordingly as the possibly null-terminated array pointed to by s1 is greater than, equal to, or less than the possibly null-terminated array pointed to by s2.
7.24.4.4.4 The wcsxfrm function
Synopsis
#include <wchar.h>
size_t wcsxfrm(wchar_t * restrict s1,
const wchar_t * restrict s2,
size_t n);
Description
The wcsxfrm function transforms the wide string pointed to by s2 and places the resulting wide string into the array pointed to by s1. The transformation is such that if the wcscmp function is applied to two transformed wide strings, it returns a value greater than, equal to, or less than zero, corresponding to the result of the wcscoll function applied to the same two original wide strings. No more than n wide characters are placed into the resulting array pointed to by s1, including the terminating null wide character. If n is zero, s1 is permitted to be a null pointer.
Returns
The wcsxfrm function returns the length of the transformed wide string (not including the terminating null wide character). If the value returned is n or greater, the contents of the array pointed to by s1 are indeterminate.
EXAMPLE The value of the following expression is the length of the array needed to hold the transformation of the wide string pointed to by s: 1 + wcsxfrm(NULL, s, 0)
7.24.4.4.5 The wmemcmp function
Synopsis
#include <wchar.h>
int wmemcmp(const wchar_t *s1, const wchar_t *s2,
size_t n);
Description
The wmemcmp function 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.
Returns
The wmemcmp function returns an integer greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2.
7.24.4.5 Wide string search functions
7.24.4.5.1 The wcschr function
Synopsis
#include <wchar.h>
wchar_t *wcschr(const wchar_t *s, wchar_t c);
Description
The wcschr function locates the first occurrence of c in the wide string pointed to by s. The terminating null wide character is considered to be part of the wide string.
Returns
The wcschr function returns a pointer to the located wide character, or a null pointer if the wide character does not occur in the wide string.
7.24.4.5.2 The wcscspn function
Synopsis
#include <wchar.h>
size_t wcscspn(const wchar_t *s1, const wchar_t *s2);
Description
The wcscspn function computes the length of the maximum initial segment of the wide string pointed to by s1 which consists entirely of wide characters not from the wide string pointed to by s2.
Returns
The wcscspn function returns the length of the segment.
7.24.4.5.3 The wcspbrk function
Synopsis
#include <wchar.h>
wchar_t *wcspbrk(const wchar_t *s1, const wchar_t *s2);
Description
The wcspbrk function locates the first occurrence in the wide string pointed to by s1 of any wide character from the wide string pointed to by s2.
Returns
The wcspbrk function returns a pointer to the wide character in s1, or a null pointer if no wide character from s2 occurs in s1.
7.24.4.5.4 The wcsrchr function
Synopsis
#include <wchar.h>
wchar_t *wcsrchr(const wchar_t *s, wchar_t c);
Description
The wcsrchr function locates the last occurrence of c in the wide string pointed to by s. The terminating null wide character is considered to be part of the wide string.
Returns
The wcsrchr function returns a pointer to the wide character, or a null pointer if c does not occur in the wide string.
7.24.4.5.5 The wcsspn function
Synopsis
#include <wchar.h>
size_t wcsspn(const wchar_t *s1, const wchar_t *s2);
Description
The wcsspn function computes the length of the maximum initial segment of the wide string pointed to by s1 which consists entirely of wide characters from the wide string pointed to by s2.
Returns
The wcsspn function returns the length of the segment.
7.24.4.5.6 The wcsstr function
Synopsis
#include <wchar.h>
wchar_t *wcsstr(const wchar_t *s1, const wchar_t *s2);
Description
The wcsstr function 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.
Returns
The wcsstr function returns a pointer to the located wide string, or a null pointer if the wide string is not found. If s2 points to a wide string with zero length, the function returns s1.
7.24.4.5.7 The wcstok function
Synopsis
#include <wchar.h>
wchar_t *wcstok(wchar_t * restrict s1,
const wchar_t * restrict s2,
wchar_t ** restrict ptr);
Description
A sequence of calls to the wcstok function breaks the wide string pointed to by s1 into a sequence of tokens, each of which is delimited by a wide character from the wide string pointed to by s2. The third argument points to a caller-provided wchar_t pointer into which the wcstok function stores information necessary for it to continue scanning the same wide string.
The first call in a sequence has a non-null first argument and stores an initial value in the object pointed to by ptr. Subsequent calls in the sequence have a null first argument and the object pointed to by ptr is required to have the value stored by the previous call in the sequence, which is then updated. The separator wide string pointed to by s2 may be different from call to call.
The first call in the sequence searches the wide string pointed to by s1 for the first wide character that is not contained in the current separator wide string pointed to by s2. If no such wide character is found, then there are no tokens in the wide string pointed to by s1 and the wcstok function returns a null pointer. If such a wide character is found, it is the start of the first token.
The wcstok function then searches from there for a wide character that is contained in the current separator wide string. If no such wide character is found, the current token extends to the end of the wide string pointed to by s1, and subsequent searches in the same wide string for a token return a null pointer. If such a wide character is found, it is overwritten by a null wide character, which terminates the current token.
In all cases, the wcstok function stores sufficient information in the pointer pointed to by ptr so that subsequent calls, with a null pointer for s1 and the unmodified pointer value for ptr, shall start searching just past the element overwritten by a null wide character (if any).
Returns
The wcstok function returns a pointer to the first wide character of a token, or a null pointer if there is no token.
#include <wchar.h>
static wchar_t str1[] = L"?a???b,,,#c";
static wchar_t str2[] = L"\t \t";
wchar_t *t, *ptr1, *ptr2;
t = wcstok(str1, L"?", &ptr[[FOOTNOTE:1]]; // t points to the token L"a"
t = wcstok(NULL, L",", &ptr[[FOOTNOTE:1]]; // t points to the token L"??b"
t = wcstok(str2, L" \t", &ptr2); // t is a null pointer
t = wcstok(NULL, L"#,", &ptr[[FOOTNOTE:1]]; // t points to the token L"c"
t = wcstok(NULL, L"?", &ptr[[FOOTNOTE:1]]; // t is a null pointer
7.24.4.5.8 The wmemchr function
Synopsis
#include <wchar.h>
wchar_t *wmemchr(const wchar_t *s, wchar_t c,
size_t n);
Description
The wmemchr function locates the first occurrence of c in the initial n wide characters of the object pointed to by s.
Returns
The wmemchr function returns a pointer to the located wide character, or a null pointer if the wide character does not occur in the object.
7.24.4.6 Miscellaneous functions
7.24.4.6.1 The wcslen function
Synopsis
#include <wchar.h>
size_t wcslen(const wchar_t *s);
Description
The wcslen function computes the length of the wide string pointed to by s.
Returns
The wcslen function returns the number of wide characters that precede the terminating null wide character.
7.24.4.6.2 The wmemset function
Synopsis
#include <wchar.h>
wchar_t *wmemset(wchar_t *s, wchar_t c, size_t n);
Description
The wmemset function copies the value of c into each of the first n wide characters of the object pointed to by s.
Returns
The wmemset function returns the value of s.
7.24.5 Wide character time conversion functions
7.24.5.1 The wcsftime function
Synopsis
#include <time.h>
#include <wchar.h>
size_t wcsftime(wchar_t * restrict s,
size_t maxsize,
const wchar_t * restrict format,
const struct tm * restrict timeptr);
Description
The wcsftime function is equivalent to the strftime function, except that:
- The argument s points to the initial element of an array of wide characters into which the generated output is to be placed.
- The argument maxsize indicates the limiting number of wide characters.
- The argument format is a wide string and the conversion specifiers are replaced by corresponding sequences of wide characters.
- The return value indicates the number of wide characters.
Returns
If the total number of resulting wide characters including the terminating null wide character is not more than maxsize, the wcsftime function returns the number of wide characters placed into the array pointed to by s not including the terminating null wide character. Otherwise, zero is returned and the contents of the array are indeterminate.
7.24.6 Extended multibyte/wide character conversion utilities
The header <wchar.h> declares an extended set of functions useful for conversion between multibyte characters and wide characters.
Most of the following functions — those that are listed as ‘‘restartable’’, 7.24.6.3 Restartable multibyte/wide character conversion functions and 7.24.6.4 Restartable multibyte/wide string conversion functions — take as a last argument a pointer to an object of type mbstate_t that is used to describe the current conversion state from a particular multibyte character sequence to a wide character sequence (or the reverse) under the rules of a particular setting for the LC_CTYPE category of the current locale.
The initial conversion state corresponds, for a conversion in either direction, to the beginning of a new multibyte character in the initial shift state. A zero-valued mbstate_t object is (at least) one way to describe an initial conversion state. A zero-valued mbstate_t object can be used to initiate conversion involving any multibyte character sequence, in any LC_CTYPE category setting. If an mbstate_t object has been altered by any of the functions described in this subclause, and is then used with a different multibyte character sequence, or in the other conversion direction, or with a different LC_CTYPE category setting than on earlier function calls, the behavior is undefined.299)
On entry, each function takes the described conversion state (either internal or pointed to by an argument) as current. The conversion state described by the pointed-to object is altered as needed to track the shift state, and the position within a multibyte character, for the associated multibyte character sequence.
7.24.6.1 Single-byte/wide character conversion functions
7.24.6.1.1 The btowc function
Synopsis
#include <stdio.h>
#include <wchar.h>
wint_t btowc(int c);
Description
The btowc function determines whether c constitutes a valid single-byte character in the initial shift state.
Returns
The btowc function returns WEOF if c has the value EOF or if (unsigned char)c does not constitute a valid single-byte character in the initial shift state. Otherwise, it returns the wide character representation of that character.
7.24.6.1.2 The wctob function
Synopsis
#include <stdio.h>
#include <wchar.h>
int wctob(wint_t c);
Description
The wctob function determines whether c corresponds to a member of the extended character set whose multibyte character representation is a single byte when in the initial shift state.
Returns
The wctob function returns EOF if c does not correspond to a multibyte character with length one in the initial shift state. Otherwise, it returns the single-byte representation of that character as an unsigned char converted to an int.
7.24.6.2 Conversion state functions
7.24.6.2.1 The mbsinit function
Synopsis
#include <wchar.h>
int mbsinit(const mbstate_t *ps);
Description
If ps is not a null pointer, the mbsinit function determines whether the pointed-to mbstate_t object describes an initial conversion state.
Returns
The mbsinit function returns nonzero if ps is a null pointer or if the pointed-to object describes an initial conversion state; otherwise, it returns zero.
7.24.6.3 Restartable multibyte/wide character conversion functions
These functions differ from the corresponding multibyte character functions of 7.20.7 Multibyte/wide character conversion functions (mblen, mbtowc, and wctomb) in that they have an extra parameter, ps, of type pointer to mbstate_t that points to an object that can completely describe the current conversion state of the associated multibyte character sequence. If ps is a null pointer, each function uses its own internal mbstate_t object instead, which is initialized at program startup to the initial conversion state. The implementation behaves as if no library function calls these functions with a null pointer for ps.
Also unlike their corresponding functions, the return value does not represent whether the encoding is state-dependent.
7.24.6.3.1 The mbrlen function
Synopsis
#include <wchar.h>
size_t mbrlen(const char * restrict s,
size_t n,
mbstate_t * restrict ps);
Description
The mbrlen function is equivalent to the call:
mbrtowc(NULL, s, n, ps != NULL ? ps : &internal)
where internal is the mbstate_t object for the mbrlen function, except that the expression designated by ps is evaluated only once.
Returns
The mbrlen function returns a value between zero and n, inclusive, (size_t)(-2), or (size_t)(-1). Forward references: the mbrtowc function ( 7.24.6.3.2 The mbrtowc function ).
7.24.6.3.2 The mbrtowc function
Synopsis
#include <wchar.h>
size_t mbrtowc(wchar_t * restrict pwc,
const char * restrict s,
size_t n,
mbstate_t * restrict ps);
Description
If s is a null pointer, the mbrtowc function is equivalent to the call:
mbrtowc(NULL, "", 1, ps)
In this case, the values of the parameters pwc and n are ignored.
If s is not a null pointer, the mbrtowc function inspects at most n bytes beginning with the byte pointed to by s to determine the number of bytes needed to complete the next multibyte character (including any shift sequences). If the function determines that the next multibyte character is complete and valid, it determines the value of the corresponding wide character and then, if pwc is not a null pointer, stores that value in the object pointed to by pwc. If the corresponding wide character is the null wide character, the resulting state described is the initial conversion state.
Returns
The mbrtowc function returns the first of the following that applies (given the current conversion state):
0 if the next n or fewer bytes complete the multibyte character that
corresponds to the null wide character (which is the value stored).
between 1 and n inclusive if the next n or fewer bytes complete a valid multibyte character (which is the value stored); the value returned is the number of bytes that complete the multibyte character. (size_t)(-2) if the next n bytes contribute to an incomplete (but potentially valid) multibyte character, and all n bytes have been processed (no value is stored).300) (size_t)(-1) if an encoding error occurs, in which case the next n or fewer bytes do not contribute to a complete and valid multibyte character (no value is stored); the value of the macro EILSEQ is stored in errno, and the conversion state is unspecified.
7.24.6.3.3 The wcrtomb function
Synopsis
#include <wchar.h>
size_t wcrtomb(char * restrict s,
wchar_t wc,
mbstate_t * restrict ps);
Description
If s is a null pointer, the wcrtomb function is equivalent to the call
wcrtomb(buf, L'\0', ps)
where buf is an internal buffer.
If s is not a null pointer, the wcrtomb function determines the number of bytes needed to represent the multibyte character that corresponds to the wide character given by wc (including any shift sequences), and stores the multibyte character representation in the array whose first element is pointed to by s. At most MB_CUR_MAX bytes are stored. If wc is a null wide character, a null byte is stored, preceded by any shift sequence needed to restore the initial shift state; the resulting state described is the initial conversion state.
Returns
The wcrtomb function returns the number of bytes stored in the array object (including any shift sequences). When wc is not a valid wide character, an encoding error occurs: the function stores the value of the macro EILSEQ in errno and returns (size_t)(-1); the conversion state is unspecified.
7.24.6.4 Restartable multibyte/wide string conversion functions
These functions differ from the corresponding multibyte string functions of 7.20.8 Multibyte/wide string conversion functions (mbstowcs and wcstombs) in that they have an extra parameter, ps, of type pointer to mbstate_t that points to an object that can completely describe the current conversion state of the associated multibyte character sequence. If ps is a null pointer, each function uses its own internal mbstate_t object instead, which is initialized at program startup to the initial conversion state. The implementation behaves as if no library function calls these functions with a null pointer for ps.
Also unlike their corresponding functions, the conversion source parameter, src, has a pointer-to-pointer type. When the function is storing the results of conversions (that is, when dst is not a null pointer), the pointer object pointed to by this parameter is updated to reflect the amount of the source processed by that invocation.
7.24.6.4.1 The mbsrtowcs function
Synopsis
#include <wchar.h>
size_t mbsrtowcs(wchar_t * restrict dst,
const char ** restrict src,
size_t len,
mbstate_t * restrict ps);
Description
The mbsrtowcs function converts a sequence of multibyte characters that begins in the conversion state described by the object pointed to by ps, from the array indirectly pointed to by src into a sequence of corresponding wide characters. If dst is not a null pointer, the converted characters are stored into the array pointed to by dst. Conversion continues up to and including a terminating null character, which is also stored. Conversion stops earlier in two cases: when a sequence of bytes is encountered that does not form a valid multibyte character, or (if dst is not a null pointer) when len wide characters have been stored into the array pointed to by dst.301) Each conversion takes place as if by a call to the mbrtowc function.
If dst is not a null pointer, the pointer object pointed to by src is assigned either a null pointer (if conversion stopped due to reaching a terminating null character) or the address just past the last multibyte character converted (if any). If conversion stopped due to reaching a terminating null character and if dst is not a null pointer, the resulting state described is the initial conversion state.
Returns
If the input conversion encounters a sequence of bytes that do not form a valid multibyte character, an encoding error occurs: the mbsrtowcs function stores the value of the macro EILSEQ in errno and returns (size_t)(-1); the conversion state is unspecified. Otherwise, it returns the number of multibyte characters successfully converted, not including the terminating null character (if any).
7.24.6.4.2 The wcsrtombs function
Synopsis
#include <wchar.h>
size_t wcsrtombs(char * restrict dst,
const wchar_t ** restrict src,
size_t len,
mbstate_t * restrict ps);
Description
The wcsrtombs function converts a sequence of wide characters from the array indirectly pointed to by src into a sequence of corresponding multibyte characters that begins in the conversion state described by the object pointed to by ps. If dst is not a null pointer, the converted characters are then stored into the array pointed to by dst. Conversion continues up to and including a terminating null wide character, which is also stored. Conversion stops earlier in two cases: when a wide character is reached that does not correspond to a valid multibyte character, or (if dst is not a null pointer) when the next multibyte character would exceed the limit of len total bytes to be stored into the array pointed to by dst. Each conversion takes place as if by a call to the wcrtomb function.302)
If dst is not a null pointer, the pointer object pointed to by src is assigned either a null pointer (if conversion stopped due to reaching a terminating null wide character) or the address just past the last wide character converted (if any). If conversion stopped due to reaching a terminating null wide character, the resulting state described is the initial conversion state.
Returns
If conversion stops because a wide character is reached that does not correspond to a valid multibyte character, an encoding error occurs: the wcsrtombs function stores the value of the macro EILSEQ in errno and returns (size_t)(-1); the conversion state is unspecified. Otherwise, it returns the number of bytes in the resulting multibyte character sequence, not including the terminating null character (if any).
7.25 Wide character classification and mapping utilities <wctype.h>
7.25.1 Introduction
The header <wctype.h> declares three data types, one macro, and many functions.303)
The types declared are wint_t described in 7.24.1 Introduction ; wctrans_t which is a scalar type that can hold values which represent locale-specific character mappings; and wctype_t which is a scalar type that can hold values which represent locale-specific character classifications.
The macro defined is WEOF (described in 7.24.1 Introduction ).
The functions declared are grouped as follows:
- Functions that provide wide character classification;
- Extensible functions that provide wide character classification;
- Functions that provide wide character case mapping;
- Extensible functions that provide wide character mapping.
For all functions described in this subclause that accept an argument of type wint_t, the value shall be representable as a wchar_t or shall equal the value of the macro WEOF. If this argument has any other value, the behavior is undefined.
The behavior of these functions is affected by the LC_CTYPE category of the current locale.
7.25.2 Wide character classification utilities
The header <wctype.h> declares several functions useful for classifying wide characters.
The term printing wide character refers to a member of a locale-specific set of wide characters, each of which occupies at least one printing position on a display device. The term control wide character refers to a member of a locale-specific set of wide characters that are not printing wide characters.
7.25.2.1 Wide character classification functions
The functions in this subclause return nonzero (true) if and only if the value of the argument wc conforms to that in the description of the function.
Each of the following functions returns true for each wide character that corresponds (as if by a call to the wctob function) to a single-byte character for which the corresponding character classification function from 7.4.1 Character classification functions returns true, except that the iswgraph and iswpunct functions may differ with respect to wide characters other than L' ' that are both printing and white-space wide characters.304) Forward references: the wctob function ( 7.24.6.1.2 The wctob function ).
7.25.2.1.1 The iswalnum function
Synopsis
#include <wctype.h>
int iswalnum(wint_t wc);
Description
The iswalnum function tests for any wide character for which iswalpha or iswdigit is true.
7.25.2.1.2 The iswalpha function
Synopsis
#include <wctype.h>
int iswalpha(wint_t wc);
Description
The iswalpha function tests for any wide character for which iswupper or iswlower is true, or any wide character that is one of a locale-specific set of alphabetic wide characters for which none of iswcntrl, iswdigit, iswpunct, or iswspace is true.305)
7.25.2.1.3 The iswblank function
Synopsis
#include <wctype.h>
int iswblank(wint_t wc);
Description
The iswblank function tests for any wide character that is a standard blank wide character or is one of a locale-specific set of wide characters for which iswspace is true and that is used to separate words within a line of text. The standard blank wide characters are the following: space (L' '), and horizontal tab (L'\t'). In the "C" locale, iswblank returns true only for the standard blank characters.
7.25.2.1.4 The iswcntrl function
Synopsis
#include <wctype.h>
int iswcntrl(wint_t wc);
Description
The iswcntrl function tests for any control wide character.
7.25.2.1.5 The iswdigit function
Synopsis
#include <wctype.h>
int iswdigit(wint_t wc);
Description
The iswdigit function tests for any wide character that corresponds to a decimal-digit character (as defined in 5.2.1 ).
7.25.2.1.6 The iswgraph function
Synopsis
#include <wctype.h>
int iswgraph(wint_t wc);
Description
The iswgraph function tests for any wide character for which iswprint is true and iswspace is false.306)
7.25.2.1.7 The iswlower function
Synopsis
#include <wctype.h>
int iswlower(wint_t wc);
Description
The iswlower function tests for any wide character that corresponds to a lowercase letter or is one of a locale-specific set of wide characters for which none of iswcntrl, iswdigit, iswpunct, or iswspace is true.
7.25.2.1.8 The iswprint function
Synopsis
#include <wctype.h>
int iswprint(wint_t wc);
Description
The iswprint function tests for any printing wide character.
7.25.2.1.9 The iswpunct function
Synopsis
#include <wctype.h>
int iswpunct(wint_t wc);
Description
The iswpunct function tests for any printing wide character that is one of a locale-specific set of punctuation wide characters for which neither iswspace nor iswalnum is true.306)
7.25.2.1.10 The iswspace function
Synopsis
#include <wctype.h>
int iswspace(wint_t wc);
Description
The iswspace function tests for any wide character that corresponds to a locale-specific set of white-space wide characters for which none of iswalnum, iswgraph, or iswpunct is true.
7.25.2.1.11 The iswupper function
Synopsis
#include <wctype.h>
int iswupper(wint_t wc);
Description
The iswupper function tests for any wide character that corresponds to an uppercase letter or is one of a locale-specific set of wide characters for which none of iswcntrl, iswdigit, iswpunct, or iswspace is true.
7.25.2.1.12 The iswxdigit function
Synopsis
#include <wctype.h>
int iswxdigit(wint_t wc);
Description
The iswxdigit function tests for any wide character that corresponds to a hexadecimal-digit character (as defined in 6.4.4.1 ).
7.25.2.2 Extensible wide character classification functions
The functions wctype and iswctype provide extensible wide character classification as well as testing equivalent to that performed by the functions described in the previous subclause ( 7.25.2.1 Wide character classification functions ).
7.25.2.2.1 The iswctype function
Synopsis
#include <wctype.h>
int iswctype(wint_t wc, wctype_t desc);
Description
The iswctype function determines whether the wide character wc has the property described by desc. The current setting of the LC_CTYPE category shall be the same as during the call to wctype that returned the value desc.
Each of the following expressions has a truth-value equivalent to the call to the wide character classification function ( 7.25.2.1 Wide character classification functions ) in the comment that follows the expression:
iswctype(wc, wctype("alnum")) // iswalnum(wc)
iswctype(wc, wctype("alpha")) // iswalpha(wc)
iswctype(wc, wctype("blank")) // iswblank(wc)
iswctype(wc, wctype("cntrl")) // iswcntrl(wc)
iswctype(wc, wctype("digit")) // iswdigit(wc)
iswctype(wc, wctype("graph")) // iswgraph(wc)
iswctype(wc, wctype("lower")) // iswlower(wc)
iswctype(wc, wctype("print")) // iswprint(wc)
iswctype(wc, wctype("punct")) // iswpunct(wc)
iswctype(wc, wctype("space")) // iswspace(wc)
iswctype(wc, wctype("upper")) // iswupper(wc)
iswctype(wc, wctype("xdigit")) // iswxdigit(wc)
Returns
The iswctype function returns nonzero (true) if and only if the value of the wide character wc has the property described by desc. Forward references: the wctype function ( 7.25.2.2.2 The wctype function ).
7.25.2.2.2 The wctype function
Synopsis
#include <wctype.h>
wctype_t wctype(const char *property);
Description
The wctype function constructs a value with type wctype_t that describes a class of wide characters identified by the string argument property.
The strings listed in the description of the iswctype function shall be valid in all locales as property arguments to the wctype function.
Returns
If property identifies a valid class of wide characters according to the LC_CTYPE category of the current locale, the wctype function returns a nonzero value that is valid
as the second argument to the iswctype function; otherwise, it returns zero. ∗
7.25.3 Wide character case mapping utilities
The header <wctype.h> declares several functions useful for mapping wide characters.
7.25.3.1 Wide character case mapping functions
7.25.3.1.1 The towlower function
Synopsis
#include <wctype.h>
wint_t towlower(wint_t wc);
Description
The towlower function converts an uppercase letter to a corresponding lowercase letter.
Returns
If the argument is a wide character for which iswupper is true and there are one or
more corresponding wide characters, as specified by the current locale, for which
iswlower is true, the towlower function returns one of the corresponding wide
characters (always the same one for any given locale); otherwise, the argument is
returned unchanged.
7.25.3.1.2 The towupper function
Synopsis
#include <wctype.h>
wint_t towupper(wint_t wc);
Description
The towupper function converts a lowercase letter to a corresponding uppercase letter.
Returns
If the argument is a wide character for which iswlower is true and there are one or
more corresponding wide characters, as specified by the current locale, for which
iswupper is true, the towupper function returns one of the corresponding wide
characters (always the same one for any given locale); otherwise, the argument is
returned unchanged.
7.25.3.2 Extensible wide character case mapping functions
The functions wctrans and towctrans provide extensible wide character mapping as well as case mapping equivalent to that performed by the functions described in the previous subclause ( 7.25.3.1 Wide character case mapping functions ).
7.25.3.2.1 The towctrans function
Synopsis
#include <wctype.h>
wint_t towctrans(wint_t wc, wctrans_t desc);
Description
The towctrans function maps the wide character wc using the mapping described by desc. The current setting of the LC_CTYPE category shall be the same as during the call to wctrans that returned the value desc.
Each of the following expressions behaves the same as the call to the wide character case mapping function ( 7.25.3.1 Wide character case mapping functions ) in the comment that follows the expression:
towctrans(wc, wctrans("tolower")) // towlower(wc)
towctrans(wc, wctrans("toupper")) // towupper(wc)
Returns
The towctrans function returns the mapped value of wc using the mapping described by desc.
7.25.3.2.2 The wctrans function
Synopsis
#include <wctype.h>
wctrans_t wctrans(const char *property);
Description
The wctrans function constructs a value with type wctrans_t that describes a mapping between wide characters identified by the string argument property.
The strings listed in the description of the towctrans function shall be valid in all locales as property arguments to the wctrans function.
Returns
If property identifies a valid mapping of wide characters according to the LC_CTYPE category of the current locale, the wctrans function returns a nonzero value that is valid as the second argument to the towctrans function; otherwise, it returns zero.
7.26 Future library directions
The following names are grouped under individual headers for convenience. All external names described below are reserved no matter what headers are included by the program.
7.26.1 Complex arithmetic <complex.h>
The function names
cerf cexpm1 clog2
cerfc clog10 clgamma
cexp2 clog1p ctgamma
and the same names suffixed with f or l may be added to the declarations in the <complex.h> header.
7.26.2 Character handling <ctype.h>
Function names that begin with either is or to, and a lowercase letter may be added to the declarations in the <ctype.h> header.
7.26.3 Errors <errno.h>
Macros that begin with E and a digit or E and an uppercase letter may be added to the declarations in the <errno.h> header.
7.26.4 Format conversion of integer types <inttypes.h>
Macro names beginning with PRI or SCN followed by any lowercase letter or X may be added to the macros defined in the <inttypes.h> header.
7.26.5 Localization <locale.h>
Macros that begin with LC_ and an uppercase letter may be added to the definitions in the <locale.h> header.
7.26.6 Signal handling <signal.h>
Macros that begin with either SIG and an uppercase letter or SIG_ and an uppercase letter may be added to the definitions in the <signal.h> header.
7.26.7 Boolean type and values <stdbool.h>
The ability to undefine and perhaps then redefine the macros bool, true, and false is an obsolescent feature.
7.26.8 Integer types <stdint.h>
Typedef names beginning with int or uint and ending with _t may be added to the types defined in the <stdint.h> header. Macro names beginning with INT or UINT and ending with _MAX, _MIN, or _C may be added to the macros defined in the <stdint.h> header.
7.26.9 Input/output <stdio.h>
Lowercase letters may be added to the conversion specifiers and length modifiers in fprintf and fscanf. Other characters may be used in extensions.
The gets function is obsolescent, and is deprecated.
The use of ungetc on a binary stream where the file position indicator is zero prior to the call is an obsolescent feature.
7.26.10 General utilities <stdlib.h>
Function names that begin with str and a lowercase letter may be added to the declarations in the <stdlib.h> header.
7.26.11 String handling <string.h>
Function names that begin with str, mem, or wcs and a lowercase letter may be added to the declarations in the <string.h> header.
7.26.12 Extended multibyte and wide character utilities <wchar.h>
Function names that begin with wcs and a lowercase letter may be added to the declarations in the <wchar.h> header.
Lowercase letters may be added to the conversion specifiers and length modifiers in fwprintf and fwscanf. Other characters may be used in extensions.
7.26.13 Wide character classification and mapping utilities
<wctype.h>
Function names that begin with is or to and a lowercase letter may be added to the declarations in the <wctype.h> header.
FOOTNOTES
- Footnote 157
- The functions that make use of the decimal-point character are the numeric conversion functions ( 7.20.1 Numeric conversion functions , 7.24.4.1 Wide string numeric conversion functions ) and the formatted input/output functions ( 7.19.6 Formatted input/output functions , 7.24.2 Formatted wide character input/output functions ).
- Footnote 158
- For state-dependent encodings, the values for MB_CUR_MAX and MB_LEN_MAX shall thus be large enough to count all the bytes in any complete multibyte character plus at least one adjacent shift sequence of maximum length. Whether these counts provide for more than one shift sequence is the implementation’s choice.
- Footnote 159
- A header is not necessarily a source file, nor are the < and > delimited sequences in header names necessarily valid source file names.
- Footnote 160
- The list of reserved identifiers with external linkage includes errno, math_errhandling, setjmp, and va_end.
- Footnote 161
- This means that an implementation shall provide an actual function for each library function, even if it also provides a macro for that function.
- Footnote 162
- Such macros might not contain the sequence points that the corresponding function calls do.
- Footnote 163
- Because external identifiers and some macro names beginning with an
underscore are reserved, implementations may provide special semantics for
such names. For example, the identifier _BUILTIN_abs could be used to
indicate generation of in-line code for the abs function. Thus, the
appropriate header could specify
#define abs(x) _BUILTIN_abs(x) for a compiler whose code generator will accept it. In this manner, a user desiring to guarantee that a given library function such as abs will be a genuine function may write #undef abs whether the implementation’s header provides a macro implementation of abs or a built-in implementation. The prototype for the function, which precedes and is hidden by any macro definition, is thereby revealed also.
- Footnote 164
- Thus, a signal handler cannot, in general, call standard library functions.
- Footnote 165
- The message written might be of the form: Assertion failed: expression, function abc, file xyz, line nnn.
- Footnote 166
- See ‘‘future library directions’’ ( 7.26.1 Complex arithmetic <complex.h> ).
- Footnote 167
- The imaginary unit is a number i such that i 2 = −1.
- Footnote 168
- A specification for imaginary types is in informative annex G.
- Footnote 169
- The purpose of the pragma is to allow the implementation to use the formulas: (x + iy) × (u + iv) = (xu − yv) + i(yu + xv) (x + iy) / (u + iv) = [(xu + yv) + i(yu − xv)]/(u2 + v 2 ) | x + iy | = √ x 2 + y2 where the programmer can determine they are safe.
- Footnote 170
- For a variable z of complex type, z == creal(z) + cimag(z)*I.
- Footnote 171
- For a variable z of complex type, z == creal(z) + cimag(z)*I.
- Footnote 172
- See ‘‘future library directions’’ ( 7.26.2 Character handling <ctype.h> ).
- Footnote 173
- In an implementation that uses the seven-bit US ASCII character set, the printing characters are those whose values lie from 0x20 (space) through 0x7E (tilde); the control characters are those whose values lie from 0 (NUL) through 0x1F (US), and the character 0x7F (DEL).
- Footnote 174
- The functions islower and isupper test true or false separately for each of these additional characters; all four combinations are possible.
- Footnote 175
- The macro errno need not be the identifier of an object. It might expand to a modifiable lvalue resulting from a function call (for example, *errno()).
- Footnote 176
- Thus, a program that uses errno for error checking should set it to zero before a library function call, then inspect it before a subsequent library function call. Of course, a library function can save the value of errno on entry and then set it to zero, as long as the original value is restored if errno’s value is still zero just before the return.
- Footnote 177
- See ‘‘future library directions’’ ( 7.26.3 Errors <errno.h> ).
- Footnote 178
- This header is designed to support the floating-point exception status flags and directed-rounding control modes required by IEC 60559, and other similar floating-point state information. Also it is designed to facilitate code portability among all systems.
- Footnote 179
- A floating-point status flag is not an object and can be set more than once within an expression.
- Footnote 180
- With these conventions, a programmer can safely assume default floating-point control modes (or be unaware of them). The responsibilities associated with accessing the floating-point environment fall on the programmer or program that does so explicitly.
- Footnote 181
- The implementation supports an exception if there are circumstances where a call to at least one of the functions in 7.6.2 Floating-point exceptions , using the macro as the appropriate argument, will succeed. It is not necessary for all the functions to succeed all the time.
- Footnote 182
- The macros should be distinct powers of two.
- Footnote 183
- Even though the rounding direction macros may expand to constants corresponding to the values of FLT_ROUNDS, they are not required to do so.
- Footnote 184
- The purpose of the FENV_ACCESS pragma is to allow certain optimizations that could subvert flag tests and mode changes (e.g., global common subexpression elimination, code motion, and constant folding). In general, if the state of FENV_ACCESS is ‘‘off’’, the translator can assume that default modes are in effect and the flags are not tested.
- Footnote 185
- The side effects impose a temporal ordering that requires two evaluations of x + 1. On the other hand, without the #pragma STDC FENV_ACCESS ON pragma, and assuming the default state is ‘‘off’’, just one evaluation of x + 1 would suffice.
- Footnote 186
- The functions fetestexcept, feraiseexcept, and feclearexcept support the basic abstraction of flags that are either set or clear. An implementation may endow floating-point status flags with more information — for example, the address of the code which first raised the floating-point exception; the functions fegetexceptflag and fesetexceptflag deal with the full content of flags.
- Footnote 187
- The effect is intended to be similar to that of floating-point exceptions raised by arithmetic operations. Hence, enabled traps for floating-point exceptions raised by this function are taken. The specification in F.7.6 is in the same spirit.
- Footnote 188
- This mechanism allows testing several floating-point exceptions with just one function call.
- Footnote 189
- IEC 60559 systems have a default non-stop mode, and typically at least one other mode for trap handling or aborting; if the system provides only the non-stop mode then installing it is trivial. For such systems, the feholdexcept function can be used in conjunction with the feupdateenv function to write routines that hide spurious floating-point exceptions from their callers.
- Footnote 190
- See ‘‘future library directions’’ ( 7.26.4 Format conversion of integer types <inttypes.h> ).
- Footnote 191
- C++ implementations should define these macros only when _ _STDC_FORMAT_MACROS is defined before <inttypes.h> is included.
- Footnote 192
- Separate macros are given for use with fprintf and fscanf functions because, in the general case, different format specifiers may be required for fprintf and fscanf, even when the type is the same.
- Footnote 193
- The absolute value of the most negative number cannot be represented in two’s complement.
- Footnote 194
- ISO/IEC 9945−2 specifies locale and charmap formats that may be used to specify locales for C.
- Footnote 195
- See ‘‘future library directions’’ ( 7.26.5 Localization <locale.h> ).
- Footnote 196
- The only functions in 7.4 Character handling <ctype.h> whose behavior is not affected by the current locale are isdigit and isxdigit.
- Footnote 197
- The implementation shall arrange to encode in a string the various categories due to a heterogeneous locale when category has the value LC_ALL.
- Footnote 198
- Particularly on systems with wide expression evaluation, a <math.h> function might pass arguments and return values in wider format than the synopsis prototype indicates.
- Footnote 199
- The types float_t and double_t are intended to be the implementation’s most efficient types at least as wide as float and double, respectively. For FLT_EVAL_METHOD equal 0, 1, or 2, the type float_t is the narrowest type used by the implementation to evaluate floating expressions.
- Footnote 200
- HUGE_VAL, HUGE_VALF, and HUGE_VALL can be positive infinities in an implementation that supports infinities.
- Footnote 201
- In this case, using INFINITY will violate the constraint in 6.4.4 and thus require a diagnostic.
- Footnote 202
- Typically, the FP_FAST_FMA macro is defined if and only if the fma function is implemented directly with a hardware multiply-add instruction. Software implementations are expected to be substantially slower.
- Footnote 203
- In an implementation that supports infinities, this allows an infinity as an argument to be a domain error if the mathematical domain of the function does not include the infinity.
- Footnote 204
- The term underflow here is intended to encompass both ‘‘gradual underflow’’ as in IEC 60559 and also ‘‘flush-to-zero’’ underflow.
- Footnote 205
- Since an expression can be evaluated with more range and precision than its type has, it is important to know the type that classification is based on. For example, a normal long double value might become subnormal when converted to double, and zero when converted to float.
- Footnote 206
- For the isnan macro, the type for determination does not matter unless the implementation supports NaNs in the evaluation type but not in the semantic type.
- Footnote 207
- The signbit macro reports the sign of all values, including infinities, zeros, and NaNs. If zero is unsigned, it is treated as positive.
- Footnote 208
- For small magnitude x, expm1(x) is expected to be more accurate than exp(x) - 1.
- Footnote 209
- For small magnitude x, log1p(x) is expected to be more accurate than log(1 + x).
- Footnote 210
- ‘‘When y ≠ 0, the remainder r = x REM y is defined regardless of the rounding mode by the mathematical relation r = x − ny, where n is the integer nearest the exact value of x/y; whenever | n − x/y | = 1/2, then n is even. Thus, the remainder is always exact. If r = 0, its sign shall be that of x.’’ This definition is applicable for all implementations.
- Footnote 211
- The argument values are converted to the type of the function, even by a macro implementation of the function.
- Footnote 212
- The result of the nexttoward functions is determined in the type of the function, without loss of range or precision in a floating second argument.
- Footnote 213
- NaN arguments are treated as missing data: if one argument is a NaN and the other numeric, then the fmax functions choose the numeric value. See F.9.9.2.
- Footnote 214
- The fmin functions are analogous to the fmax functions in their treatment of NaNs.
- Footnote 215
- IEC 60559 requires that the built-in relational operators raise the ‘‘invalid’’ floating-point exception if the operands compare unordered, as an error indicator for programs written without consideration of NaNs; the result in these cases is false.
- Footnote 216
- These functions are useful for dealing with unusual conditions encountered in a low-level function of a program.
- Footnote 217
- For example, by executing a return statement or because another longjmp call has caused a transfer to a setjmp invocation in a function earlier in the set of nested calls.
- Footnote 218
- This includes, but is not limited to, the floating-point status flags and the state of open files.
- Footnote 219
- See ‘‘future library directions’’ ( 7.26.9 Input/output <stdio.h> ). The names of the signal numbers reflect the following terms (respectively): abort, floating-point exception, illegal instruction, interrupt, segmentation violation, and termination.
- Footnote 220
- If any signal is generated by an asynchronous signal handler, the behavior is undefined.
- Footnote 221
- It is permitted to create a pointer to a va_list and pass that pointer to another function, in which case the original function may make further use of the original list after the other function returns.
- Footnote 222
- See ‘‘future library directions’’ ( 7.26.7 Boolean type and values <stdbool.h> ).
- Footnote 223
- See ‘‘future library directions’’ ( 7.26.8 Integer types <stdint.h> ).
- Footnote 224
- Some of these types may denote implementation-defined extended integer types.
- Footnote 225
- The designated type is not guaranteed to be fastest for all purposes; if the implementation has no clear grounds for choosing one type over another, it will simply pick some integer type satisfying the signedness and width requirements.
- Footnote 226
- C++ implementations should define these macros only when _ _STDC_LIMIT_MACROS is defined before <stdint.h> is included.
- Footnote 227
- C++ implementations should define these macros only when _ _STDC_LIMIT_MACROS is defined before <stdint.h> is included.
- Footnote 228
- A freestanding implementation need not provide all of these types.
- Footnote 229
- The values WCHAR_MIN and WCHAR_MAX do not necessarily correspond to members of the extended character set.
- Footnote 230
- C++ implementations should define these macros only when _ _STDC_CONSTANT_MACROS is defined before <stdint.h> is included.
- Footnote 231
- If the implementation imposes no practical limit on the length of file name strings, the value of FILENAME_MAX should instead be the recommended size of an array intended to hold a file name string. Of course, file name string contents are subject to other system-specific constraints; therefore all possible strings of length FILENAME_MAX cannot be expected to be opened successfully.
- Footnote 232
- An implementation need not distinguish between text streams and binary streams. In such an implementation, there need be no new-line characters in a text stream nor any limit to the length of a line.
- Footnote 233
- The three predefined streams stdin, stdout, and stderr are unoriented at program startup.
- Footnote 234
- Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream (because of possible trailing null characters) or for any stream with state-dependent encoding that does not assuredly end in the initial shift state.
- Footnote 235
- Among the reasons the implementation may cause the rename function to fail are that the file is open or that it is necessary to copy its contents to effectuate its renaming.
- Footnote 236
- Files created using strings generated by the tmpnam function are temporary only in the sense that their names should not collide with those generated by conventional naming rules for the implementation. It is still necessary to use the remove function to remove such files when their use is ended, and before program termination.
- Footnote 237
- If the string begins with one of the above sequences, the implementation might choose to ignore the remaining characters, or it might use them to select different kinds of a file (some of which might not conform to the properties in 7.19.2 Streams ).
- Footnote 238
- The primary use of the freopen function is to change the file associated with a standard text stream (stderr, stdin, or stdout), as those identifiers need not be modifiable lvalues to which the value returned by the fopen function may be assigned.
- Footnote 239
- The buffer has to have a lifetime at least as great as the open stream, so the stream should be closed before a buffer that has automatic storage duration is deallocated upon block exit.
- Footnote 240
- The fprintf functions perform writes to memory for the %n specifier.
- Footnote 241
- Note that 0 is taken as a flag, not as the beginning of a field width.
- Footnote 242
- The results of all floating conversions of a negative zero, and of negative values that round to zero, include a minus sign.
- Footnote 243
- When applied to infinite and NaN values, the -, +, and space flag characters have their usual meaning; the # and 0 flag characters have no effect.
- Footnote 244
- Binary implementations can choose the hexadecimal digit to the left of the decimal-point character so that subsequent digits align to nibble (4-bit) boundaries.
- Footnote 245
- The precision p is sufficient to distinguish values of the source type if 16 p−1 > b n where b is FLT_RADIX and n is the number of base-b digits in the significand of the source type. A smaller p might suffice depending on the implementation’s scheme for determining the digit to the left of the decimal-point character.
- Footnote 246
- No special provisions are made for multibyte characters.
- Footnote 247
- Redundant shift sequences may result if multibyte characters have a state-dependent encoding.
- Footnote 248
- See ‘‘future library directions’’ ( 7.26.9 Input/output <stdio.h> ).
- Footnote 249
- For binary-to-decimal conversion, the result format’s values are the numbers representable with the given format specifier. The number of significant digits is determined by the format specifier, and in the case of fixed-point conversion by the source value as well.
- Footnote 250
- These white-space characters are not counted against a specified field width.
- Footnote 251
- fscanf pushes back at most one input character onto the input stream. Therefore, some sequences that are acceptable to strtod, strtol, etc., are unacceptable to fscanf.
- Footnote 252
- No special provisions are made for multibyte characters in the matching rules used by the c, s, and [ conversion specifiers — the extent of the input field is determined on a byte-by-byte basis. The resulting field is nevertheless a sequence of multibyte characters that begins in the initial shift state.
- Footnote 253
- See ‘‘future library directions’’ ( 7.26.9 Input/output <stdio.h> ).
- Footnote 254
- As the functions vfprintf, vfscanf, vprintf, vscanf, vsnprintf, vsprintf, and vsscanf invoke the va_arg macro, the value of arg after the return is indeterminate.
- Footnote 255
- An end-of-file and a read error can be distinguished by use of the feof and ferror functions.
- Footnote 256
- See ‘‘future library directions’’ ( 7.26.9 Input/output <stdio.h> ).
- Footnote 257
- See ‘‘future library directions’’ ( 7.26.10 General utilities <stdlib.h> ).
- Footnote 258
- It is unspecified whether a minus-signed sequence is converted to a negative number directly or by negating the value resulting from converting the corresponding unsigned sequence (see F.5); the two methods may yield different results if rounding is toward positive or negative infinity. In either case, the functions honor the sign of zero if floating-point arithmetic supports signed zeros.
- Footnote 259
- An implementation may use the n-char sequence to determine extra information to be represented in the NaN’s significand.
- Footnote 260
- DECIMAL_DIG, defined in <float.h>, should be sufficiently large that L and U will usually round to the same internal floating value, but if not will round to adjacent values.
- Footnote 261
- Note that this need not be the same as the representation of floating-point zero or a null pointer constant.
- Footnote 262
- Each function is called as many times as it was registered, and in the correct order with respect to other registered functions.
- Footnote 263
- That is, if the value passed is p, then the following expressions are always nonzero: ((char *)p - (char *)base) % size == 0 (char *)p >= (char *)base (char *)p < (char *)base + nmemb * size
- Footnote 264
- In practice, the entire array is sorted according to the comparison function.
- Footnote 265
- The absolute value of the most negative number cannot be represented in two’s complement.
- Footnote 266
- If the locale employs special bytes to change the shift state, these bytes do not produce separate wide character codes, but are grouped with an adjacent multibyte character.
- Footnote 267
- The array will not be null-terminated if the value returned is n.
- Footnote 268
- See ‘‘future library directions’’ ( 7.26.11 String handling <string.h> ).
- Footnote 269
- Thus, if there is no null character in the first n characters of the array pointed to by s2, the result will not be null-terminated.
- Footnote 270
- Thus, the maximum number of characters that can end up in the array pointed to by s1 is strlen(s1)+n+1.
- Footnote 271
- The contents of ‘‘holes’’ used as padding for purposes of alignment within structure objects are indeterminate. Strings shorter than their allocated space and unions may also cause problems in comparison.
- Footnote 272
- Like other function-like macros in Standard libraries, each type-generic macro can be suppressed to make available the corresponding ordinary function.
- Footnote 273
- If the type of the argument is not compatible with the type of the parameter for the selected function, the behavior is undefined.
- Footnote 274
- The range [0, 60] for tm_sec allows for a positive leap second.
- Footnote 275
- In order to measure the time spent in a program, the clock function should be called at the start of the program and its return value subtracted from the value returned by subsequent calls.
- Footnote 276
- Thus, a positive or zero value for tm_isdst causes the mktime function to presume initially that Daylight Saving Time, respectively, is or is not in effect for the specified time. A negative value causes it to attempt to determine whether Daylight Saving Time is in effect for the specified time.
- Footnote 1
- as a decimal number (00−53). [tm_year, tm_wday, tm_yday] %V is replaced by the ISO 8601 week number (see below) as a decimal number (01−53). [tm_year, tm_wday, tm_yday] %w is replaced by the weekday as a decimal number (0−6), where Sunday is 0. [tm_wday] %W is replaced by the week number of the year (the first Monday as the first day of week 1) as a decimal number (00−53). [tm_year, tm_wday, tm_yday] %x is replaced by the locale’s appropriate date representation. [all specified in 7.23.1 Components of time ] %X is replaced by the locale’s appropriate time representation. [all specified in 7.23.1 Components of time ] %y is replaced by the last 2 digits of the year as a decimal number (00−99). [tm_year] %Y is replaced by the year as a decimal number (e.g., 1997). [tm_year] %z is replaced by the offset from UTC in the ISO 8601 format ‘‘−0430’’ (meaning 4 hours 30 minutes behind UTC, west of Greenwich), or by no characters if no time zone is determinable. [tm_isdst] %Z is replaced by the locale’s time zone name or abbreviation, or by no characters if no time zone is determinable. [tm_isdst] %% is replaced by %. 4 Some conversion specifiers can be modified by the inclusion of an E or O modifier character to indicate an alternative format or specification. If the alternative format or specification does not exist for the current locale, the modifier is ignored. %Ec is replaced by the locale’s alternative date and time representation. %EC is replaced by the name of the base year (period) in the locale’s alternative representation. %Ex is replaced by the locale’s alternative date representation. %EX is replaced by the locale’s alternative time representation. %Ey is replaced by the offset from %EC (year only) in the locale’s alternative representation. %EY is replaced by the locale’s full alternative year representation. %Od is replaced by the day of the month, using the locale’s alternative numeric symbols (filled as needed with leading zeros, or with leading spaces if there is no alternative symbol for zero). %Oe is replaced by the day of the month, using the locale’s alternative numeric symbols (filled as needed with leading spaces). %OH is replaced by the hour (24-hour clock), using the locale’s alternative numeric symbols.
- Footnote 277
- See ‘‘future library directions’’ ( 7.26.12 Extended multibyte and wide character utilities <wchar.h> ).
- Footnote 278
- wchar_t and wint_t can be the same integer type.
- Footnote 279
- The value of the macro WEOF may differ from that of EOF and need not be negative.
- Footnote 280
- The fwprintf functions perform writes to memory for the %n specifier.
- Footnote 281
- Note that 0 is taken as a flag, not as the beginning of a field width.
- Footnote 282
- The results of all floating conversions of a negative zero, and of negative values that round to zero, include a minus sign.
- Footnote 283
- When applied to infinite and NaN values, the -, +, and space flag wide characters have their usual meaning; the # and 0 flag wide characters have no effect.
- Footnote 284
- Binary implementations can choose the hexadecimal digit to the left of the decimal-point wide character so that subsequent digits align to nibble (4-bit) boundaries.
- Footnote 285
- The precision p is sufficient to distinguish values of the source type if 16 p−1 > b n where b is FLT_RADIX and n is the number of base-b digits in the significand of the source type. A smaller p might suffice depending on the implementation’s scheme for determining the digit to the left of the decimal-point wide character.
- Footnote 286
- See ‘‘future library directions’’ ( 7.26.12 Extended multibyte and wide character utilities <wchar.h> ).
- Footnote 287
- For binary-to-decimal conversion, the result format’s values are the numbers representable with the given format specifier. The number of significant digits is determined by the format specifier, and in the case of fixed-point conversion by the source value as well.
- Footnote 288
- These white-space wide characters are not counted against a specified field width.
- Footnote 289
- fwscanf pushes back at most one input wide character onto the input stream. Therefore, some sequences that are acceptable to wcstod, wcstol, etc., are unacceptable to fwscanf.
- Footnote 290
- See ‘‘future library directions’’ ( 7.26.12 Extended multibyte and wide character utilities <wchar.h> ).
- Footnote 291
- As the functions vfwprintf, vswprintf, vfwscanf, vwprintf, vwscanf, and vswscanf invoke the va_arg macro, the value of arg after the return is indeterminate.
- Footnote 292
- An end-of-file and a read error can be distinguished by use of the feof and ferror functions. Also, errno will be set to EILSEQ by input/output functions only if an encoding error occurs.
- Footnote 293
- If the orientation of the stream has already been determined, fwide does not change it.
- Footnote 294
- It is unspecified whether a minus-signed sequence is converted to a negative number directly or by negating the value resulting from converting the corresponding unsigned sequence (see F.5); the two methods may yield different results if rounding is toward positive or negative infinity. In either case, the functions honor the sign of zero if floating-point arithmetic supports signed zeros.
- Footnote 295
- An implementation may use the n-wchar sequence to determine extra information to be represented in the NaN’s significand.
- Footnote 296
- DECIMAL_DIG, defined in <float.h>, should be sufficiently large that L and U will usually round to the same internal floating value, but if not will round to adjacent values.
- Footnote 297
- Thus, if there is no null wide character in the first n wide characters of the array pointed to by s2, the result will not be null-terminated.
- Footnote 298
- Thus, the maximum number of wide characters that can end up in the array pointed to by s1 is wcslen(s1)+n+1.
- Footnote 299
- Thus, a particular mbstate_t object can be used, for example, with both the mbrtowc and mbsrtowcs functions as long as they are used to step sequentially through the same multibyte character string.
- Footnote 300
- When n has at least the value of the MB_CUR_MAX macro, this case can only occur if s points at a sequence of redundant shift sequences (for implementations with state-dependent encodings).
- Footnote 301
- Thus, the value of len is ignored if dst is a null pointer.
- Footnote 302
- If conversion stops because a terminating null wide character has been reached, the bytes stored include those necessary to reach the initial shift state immediately before the null byte.
- Footnote 303
- See ‘‘future library directions’’ ( 7.26.13 Wide character classification and mapping utilities ).
- Footnote 304
- For example, if the expression isalpha(wctob(wc)) evaluates to true, then the call iswalpha(wc) also returns true. But, if the expression isgraph(wctob(wc)) evaluates to true (which cannot occur for wc == L' ' of course), then either iswgraph(wc) or iswprint(wc) && iswspace(wc) is true, but not both.
- Footnote 305
- The functions iswlower and iswupper test true or false separately for each of these additional wide characters; all four combinations are possible.
- Footnote 306
- Note that the behavior of the iswgraph and iswpunct functions may differ from their corresponding functions in 7.4.1 Character classification functions with respect to printing, white-space, single-byte execution characters other than ' '.
- Footnote 307
- ‘‘Extended’’ is IEC 60559’s double-extended data format. Extended refers to both the common 80-bit and quadruple 128-bit IEC 60559 formats.
- Footnote 308
- A non-IEC 60559 long double type is required to provide infinity and NaNs, as its values include all double values.
- Footnote 309
- Since NaNs created by IEC 60559 operations are always quiet, quiet NaNs (along with infinities) are sufficient for closure of the arithmetic.
- Footnote 310
- ANSI/IEEE 854, but not IEC 60559 (ANSI/IEEE 754), directly specifies that floating-to-integer conversions raise the ‘‘inexact’’ floating-point exception for non-integer in-range values. In those cases where it matters, library functions can be used to effect such conversions with or without raising the ‘‘inexact’’ floating-point exception. See rint, lrint, llrint, and nearbyint in <math.h>.
- Footnote 311
- If the minimum-width IEC 60559 extended format (64 bits of precision) is supported, DECIMAL_DIG shall be at least 21. If IEC 60559 double (53 bits of precision) is the widest IEC 60559 format supported, then DECIMAL_DIG shall be at least 17. (By contrast, LDBL_DIG and DBL_DIG are 18 and 15, respectively, for these formats.)
- Footnote 312
- This specification does not require dynamic rounding precision nor trap enablement modes.
- Footnote 313
- If the state for the FENV_ACCESS pragma is ‘‘off’’, the implementation is free to assume the floating-point control modes will be the default ones and the floating-point status flags will not be tested, which allows certain optimizations (see F.8).
- Footnote 314
- As floating constants are converted to appropriate internal representations at translation time, their conversion is subject to default rounding modes and raises no execution-time floating-point exceptions (even where the state of the FENV_ACCESS pragma is ‘‘on’’). Library functions, for example strtod, provide execution-time conversion of numeric strings.
- Footnote 315
- Where the state for the FENV_ACCESS pragma is ‘‘on’’, results of inexact expressions like 1.0 / 3.0 are affected by rounding modes set at execution time, and expressions such as 0.0 / 0.0 and 1.0 / 0.0 generate execution-time floating-point exceptions. The programmer can achieve the efficiency of translation-time evaluation through static initialization, such as const static double one_third = 1.0 / 3.0 ;
- Footnote 316
- Use of float_t and double_t variables increases the likelihood of translation-time computation. For example, the automatic initialization double_t x = 1.1 e75; could be done at translation time, regardless of the expression evaluation method.
- Footnote 317
- Strict support for signaling NaNs — not required by this specification — would invalidate these and other transformations that remove arithmetic operators.
- Footnote 318
- IEC 60559 prescribes a signed zero to preserve mathematical identities across certain discontinuities. Examples include: 1/(1/ ± ∞) is ± ∞ and conj(csqrt(z)) is csqrt(conj(z)), for complex z.
- Footnote 319
- 0 − 0 yields −0 instead of +0 just when the rounding direction is downward.
- Footnote 320
- IEC 60559 allows different definitions of underflow. They all result in the same values, but differ on when the floating-point exception is raised.
- Footnote 321
- It is intended that undeserved ‘‘underflow’’ and ‘‘inexact’’ floating-point exceptions are raised only if avoiding them would be too costly.
- Footnote 322
- atan2(0, 0) does not raise the ‘‘invalid’’ floating-point exception, nor does atan2( y , 0) raise the ‘‘divide-by-zero’’ floating-point exception.
- Footnote 323
- Ideally, fmax would be sensitive to the sign of zero, for example fmax(−0. 0, +0. 0) would return +0; however, implementation in software might be impractical.
- Footnote 324
- See 6.3.1.2.
- Footnote 325
- These properties are already implied for those cases covered in the tables, but are required for all cases (at least where the state for CX_LIMITED_RANGE is ‘‘off’’).
- Footnote 326
- As noted in G.3, a complex value with at least one infinite part is regarded as an infinity even if its other part is a NaN.
- Footnote 327
- This allows cpow( z , c ) to be implemented as cexp(c clog( z )) without precluding implementations that treat special cases more carefully.