C2011-7(7) Miscellaneous Information Manual C2011-7(7)

7 LibraryWG14 N1570, clause 7

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.180) 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.181) Forward references: character handling ( 7.4 Character handling <ctype.h> ), the setlocale function ( 7.11.1.1 The setlocale function ).

Each library function is declared, with a type that includes a prototype, in a header, [182] 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 [183]

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 of the header or when any macro defined in the header is expanded.

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> ).

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) and errno are always reserved for use as identifiers with external linkage.184)
  • 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.

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.185) 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.186) 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.187) 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 or thread storage duration.188)

Unless explicitly stated otherwise in the detailed descriptions that follow, library functions shall prevent data races as follows: A library function shall not directly or indirectly access objects accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function’s arguments. A library function shall not directly or indirectly modify objects accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function’s non-const arguments.189) Implementations may share their own internal objects between threads if the objects are not visible to users and are protected against data races.

Unless otherwise specified, library functions shall perform all operations solely within the current thread if those operations have effects that are visible to users.190)

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);

The header <assert.h> defines the assert and static_assert macros 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.

The macro static_assert expands to _Static_assert.

    #include <assert.h>
            void assert(scalar expression);

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.191) It then calls the abort function.

The assert macro returns no value. Forward references: the abort function ( 7.22.4.1 The abort function ).

The header <complex.h> defines macros and declares functions that support complex arithmetic.192)

Implementations that define the macro _ _STDC_NO_COMPLEX_ _ need not provide this header nor support any of its facilities.

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.193)

The macros imaginary and _Imaginary_I are defined if and only if the implementation supports imaginary types; [194] 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).

Values are interpreted as radians, not degrees. An implementation may set errno but is not required to.

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.

    #include <complex.h>
             #pragma STDC CX_LIMITED_RANGE on-off-switch

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.195) 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’’.

    #include <complex.h>
             double complex cacos(double complex z);
             float complex cacosf(float complex z);
             long double complex cacosl(long double complex z);

The cacos functions compute the complex arc cosine of z, with branch cuts outside the interval [−1, +1] along the real axis.

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.

    #include <complex.h>
             double complex casin(double complex z);
             float complex casinf(float complex z);
             long double complex casinl(long double complex z);

The casin functions compute the complex arc sine of z, with branch cuts outside the interval [−1, +1] along the real axis.

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.

    #include <complex.h>
            double complex catan(double complex z);
            float complex catanf(float complex z);
            long double complex catanl(long double complex z);

The catan functions compute the complex arc tangent of z, with branch cuts outside the interval [−i, +i] along the imaginary axis.

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.

    #include <complex.h>
            double complex ccos(double complex z);
            float complex ccosf(float complex z);
            long double complex ccosl(long double complex z);

The ccos functions compute the complex cosine of z.

The ccos functions return the complex cosine value.

    #include <complex.h>
            double complex csin(double complex z);
            float complex csinf(float complex z);
            long double complex csinl(long double complex z);

The csin functions compute the complex sine of z.

The csin functions return the complex sine value.

    #include <complex.h>
           double complex ctan(double complex z);
           float complex ctanf(float complex z);
           long double complex ctanl(long double complex z);

The ctan functions compute the complex tangent of z.

The ctan functions return the complex tangent value.

    #include <complex.h>
           double complex cacosh(double complex z);
           float complex cacoshf(float complex z);
           long double complex cacoshl(long double complex z);

The cacosh functions compute the complex arc hyperbolic cosine of z, with a branch cut at values less than 1 along the real axis.

The cacosh functions return the complex arc hyperbolic cosine value, in the range of a half-strip of nonnegative values along the real axis and in the interval [−iπ , +iπ ] along the imaginary axis.

    #include <complex.h>
           double complex casinh(double complex z);
           float complex casinhf(float complex z);
           long double complex casinhl(long double complex z);

The casinh functions compute the complex arc hyperbolic sine of z, with branch cuts outside the interval [−i, +i] along the imaginary axis.

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.

    #include <complex.h>
            double complex catanh(double complex z);
            float complex catanhf(float complex z);
            long double complex catanhl(long double complex z);

The catanh functions compute the complex arc hyperbolic tangent of z, with branch cuts outside the interval [−1, +1] along the real axis.

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.

    #include <complex.h>
            double complex ccosh(double complex z);
            float complex ccoshf(float complex z);
            long double complex ccoshl(long double complex z);

The ccosh functions compute the complex hyperbolic cosine of z.

The ccosh functions return the complex hyperbolic cosine value.

    #include <complex.h>
           double complex csinh(double complex z);
           float complex csinhf(float complex z);
           long double complex csinhl(long double complex z);

The csinh functions compute the complex hyperbolic sine of z.

The csinh functions return the complex hyperbolic sine value.

    #include <complex.h>
           double complex ctanh(double complex z);
           float complex ctanhf(float complex z);
           long double complex ctanhl(long double complex z);

The ctanh functions compute the complex hyperbolic tangent of z.

The ctanh functions return the complex hyperbolic tangent value.

    #include <complex.h>
           double complex cexp(double complex z);
           float complex cexpf(float complex z);
           long double complex cexpl(long double complex z);

The cexp functions compute the complex base-e exponential of z.

The cexp functions return the complex base-e exponential value.

    #include <complex.h>
            double complex clog(double complex z);
            float complex clogf(float complex z);
            long double complex clogl(long double complex z);

The clog functions compute the complex natural (base-e) logarithm of z, with a branch cut along the negative real axis.

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.

    #include <complex.h>
            double cabs(double complex z);
            float cabsf(float complex z);
            long double cabsl(long double complex z);

The cabs functions compute the complex absolute value (also called norm, modulus, or magnitude) of z.

The cabs functions return the complex absolute value.

    #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);

The cpow functions compute the complex power function xy , with a branch cut for the first parameter along the negative real axis.

The cpow functions return the complex power function value.

    #include <complex.h>
           double complex csqrt(double complex z);
           float complex csqrtf(float complex z);
           long double complex csqrtl(long double complex z);

The csqrt functions compute the complex square root of z, with a branch cut along the negative real axis.

The csqrt functions return the complex square root value, in the range of the right half-plane (including the imaginary axis).

    #include <complex.h>
           double carg(double complex z);
           float cargf(float complex z);
           long double cargl(long double complex z);

The carg functions compute the argument (also called phase angle) of z, with a branch cut along the negative real axis.

The carg functions return the value of the argument in the interval [−π , +π ].

    #include <complex.h>
            double cimag(double complex z);
            float cimagf(float complex z);
            long double cimagl(long double complex z);

The cimag functions compute the imaginary part of z.196)

The cimag functions return the imaginary part value (as a real).

    #include <complex.h>
            double complex CMPLX(double x, double y);
            float complex CMPLXF(float x, float y);
            long double complex CMPLXL(long double x, long double y);

The CMPLX macros expand to an expression of the specified complex type, with the real part having the (converted) value of x and the imaginary part having the (converted) value of y. The resulting expression shall be suitable for use as an initializer for an object with static or thread storage duration, provided both arguments are likewise suitable.

The CMPLX macros return the complex value x + i y.

These macros act as if the implementation supported imaginary types and the definitions were:
         #define CMPLX(x, y)  ((double complex)((double)(x) + \
                                       _Imaginary_I * (double)(y)))
         #define CMPLXF(x, y) ((float complex)((float)(x) + \
                                       _Imaginary_I * (float)(y)))
         #define CMPLXL(x, y) ((long double complex)((long double)(x) + \
                                       _Imaginary_I * (long double)(y)))

    #include <complex.h>
           double complex conj(double complex z);
           float complex conjf(float complex z);
           long double complex conjl(long double complex z);

The conj functions compute the complex conjugate of z, by reversing the sign of its imaginary part.

The conj functions return the complex conjugate value.

    #include <complex.h>
           double complex cproj(double complex z);
           float complex cprojf(float complex z);
           long double complex cprojl(long double complex z);

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))

The cproj functions return the value of the projection onto the Riemann sphere.

    #include <complex.h>
           double creal(double complex z);
           float crealf(float complex z);
           long double creall(long double complex z);

The creal functions compute the real part of z.197)

The creal functions return the real part value.

The header <ctype.h> declares several functions useful for classifying and mapping characters.198) 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.199) All letters and digits are printing characters. Forward references: EOF ( 7.21.1 Introduction ), localization ( 7.11 Localization <locale.h> ).

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.

    #include <ctype.h>
             int isalnum(int c);

The isalnum function tests for any character for which isalpha or isdigit is true.

    #include <ctype.h>
             int isalpha(int c);

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.200) In the "C" locale, isalpha returns true only for the characters for which isupper or islower is true.

    #include <ctype.h>
            int isblank(int c);

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.

    #include <ctype.h>
            int iscntrl(int c);

The iscntrl function tests for any control character.

    #include <ctype.h>
            int isdigit(int c);

The isdigit function tests for any decimal-digit character (as defined in 5.2.1 ).

    #include <ctype.h>
            int isgraph(int c);

The isgraph function tests for any printing character except space (' ').

    #include <ctype.h>
           int islower(int c);

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 ).

    #include <ctype.h>
           int isprint(int c);

The isprint function tests for any printing character including space (' ').

    #include <ctype.h>
           int ispunct(int c);

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.

    #include <ctype.h>
           int isspace(int c);

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.

    #include <ctype.h>
            int isupper(int c);

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 ).

    #include <ctype.h>
            int isxdigit(int c);

The isxdigit function tests for any hexadecimal-digit character (as defined in 6.4.4.1 ).

    #include <ctype.h>
            int tolower(int c);

The tolower function converts an uppercase letter to a corresponding lowercase letter.

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.

    #include <ctype.h>
           int toupper(int c);

The toupper function converts a lowercase letter to a corresponding uppercase letter.

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.

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 [201] that has type int and thread local storage duration, the value of which is set to a positive error number by several library functions. 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 in the initial thread is zero at program startup (the initial value of errno in other threads is an indeterminate value), but is never set to zero by any library function.202) 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, [203] may also be specified by the implementation.

The header <fenv.h> defines several macros, and declares types and functions that 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.204) 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.205) 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.

The floating-point environment has thread storage duration. The initial state for a thread’s floating-point environment is the current state of the floating-point environment of the thread that creates it at the time of creation.

Certain programming conventions support the intended model of use for the floating-point environment: [206]

  • 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.207 ) Additional implementation-defined floating-point exceptions, with macro definitions beginning with FE_ and an uppercase letter, [208] 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.209)

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, [210] may also be specified by the implementation. The defined macros expand to integer constant expressions whose values are distinct nonnegative values.211)

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, [212] and having type ‘‘pointer to const-qualified fenv_t’’, may also be specified by the implementation.

    #include <fenv.h>
              #pragma STDC FENV_ACCESS on-off-switch

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.213) 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.214)

The following functions provide access to the floating-point status flags.215) 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.

    #include <fenv.h>
            int feclearexcept(int excepts);

The feclearexcept function attempts to clear the supported floating-point exceptions represented by its argument.

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.

    #include <fenv.h>
             int fegetexceptflag(fexcept_t *flagp,
                  int excepts);

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.

The fegetexceptflag function returns zero if the representation was successfully stored. Otherwise, it returns a nonzero value.

    #include <fenv.h>
             int feraiseexcept(int excepts);

The feraiseexcept function attempts to raise the supported floating-point exceptions represented by its argument.216) The order in which these floating-point exceptions are raised is unspecified, except as stated in F.8.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.

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.

    #include <fenv.h>
             int fesetexceptflag(const fexcept_t *flagp,
                  int excepts);

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.

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.

    #include <fenv.h>
             int fetestexcept(int excepts);

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.217)

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();
                   /* ... */
           }

The fegetround and fesetround functions provide control of rounding direction modes.

    #include <fenv.h>
           int fegetround(void);

The fegetround function gets the current rounding direction.

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.

    #include <fenv.h>
           int fesetround(int round);

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.

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);
                  /* ... */
            }

The functions in this section manage the floating-point environment — status flags and control modes — as one entity.

    #include <fenv.h>
            int fegetenv(fenv_t *envp);

The fegetenv function attempts to store the current floating-point environment in the object pointed to by envp.

The fegetenv function returns zero if the environment was successfully stored. Otherwise, it returns a nonzero value.

    #include <fenv.h>
            int feholdexcept(fenv_t *envp);

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.218)

The feholdexcept function returns zero if and only if non-stop floating-point exception handling was successfully installed.

    #include <fenv.h>
            int fesetenv(const fenv_t *envp);

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.

The fesetenv function returns zero if the environment was successfully established. Otherwise, it returns a nonzero value.

    #include <fenv.h>
            int feupdateenv(const fenv_t *envp);

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.

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;
            }

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.

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.219) Forward references: integer types <stdint.h> ( 7.20 Integer types <stdint.h> ), formatted input/output functions ( 7.21.6 Formatted input/output functions ), formatted wide character input/output functions ( 7.29.2 Formatted wide character input/output functions ).

Each of the following object-like macros 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), [220] followed by the conversion specifier, followed by a name corresponding to a similar type name in 7.20.1. In these names, N represents the width of the type as described in 7.20.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;
            }

    #include <inttypes.h>
            intmax_t imaxabs(intmax_t j);

The imaxabs function computes the absolute value of an integer j. If the result cannot be represented, the behavior is undefined.221)

The imaxabs function returns the absolute value.

    #include <inttypes.h>
            imaxdiv_t imaxdiv(intmax_t numer, intmax_t denom);

The imaxdiv function computes numer / denom and numer % denom in a single operation.

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.

    #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);

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.

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.22.1.4 The strtol, strtoll, strtoul, and strtoull functions ).

    #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);

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.

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.29.4.1.2 The wcstol, wcstoll, wcstoul, and wcstoull functions ).

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     ^=

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.

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.19 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.222) Additional macro definitions, beginning with the characters LC_ and an uppercase letter, [223] may also be specified by the implementation.

    #include <locale.h>
             char *setlocale(int category, const char *locale);

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 [224] 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.

A call to the setlocale function may introduce a data race with other calls to the setlocale function or with calls to functions that are affected by the current locale. The implementation shall behave as if no library function calls the setlocale function.

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.225)

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.21.6 Formatted input/output functions ), multibyte/wide character conversion functions ( 7.22.7 Multibyte/wide character conversion functions ), multibyte/wide string conversion functions ( 7.22.8 Multibyte/wide string conversion functions ), numeric conversion functions ( 7.22.1 Numeric conversion functions ), the strcoll function ( 7.24.4.3 The strcoll function ), the strftime function ( 7.27.3.5 The strftime function ), the strxfrm function ( 7.24.4.5 The strxfrm function ).

    #include <locale.h>
            struct lconv *localeconv(void);

The localeconv function sets the components of an object with type struct lconv with values appropriate for the formatting of numeric quantities (monetary and otherwise) according to the rules of the current locale.

The 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:

No further grouping is to be performed.
The previous element is to be repeatedly used for the remainder of the digits.
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:

No space separates the currency symbol and value.
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.
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:

Parentheses surround the quantity and currency symbol.
The sign string precedes the quantity and currency symbol.
The sign string succeeds the quantity and currency symbol.
The sign string immediately precedes the currency symbol.
The sign string immediately succeeds the currency symbol.

The implementation shall behave as if no library function calls the localeconv function.

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.

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

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

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.226) 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.227)

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.228)

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.229)

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.230) 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>.

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 raising SIGFPE and without generating any of the floating-point exceptions ‘‘invalid’’, ‘‘divide-by-zero’’, or ‘‘overflow’’ except to reflect the result of the function.

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.231) 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 pole error (also known as a singularity or infinitary) occurs if the mathematical function has an exact infinite result as the finite input argument(s) are approached in the limit (for example, log( 0.0 )). The description of each function lists any required pole errors; an implementation may define additional pole errors, provided that such errors are consistent with the mathematical definition of the function. On a pole 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 ERANGE; if the integer expression math_errhandling & MATH_ERREXCEPT is nonzero, the ‘‘divide-by-zero’’ floating-point exception is raised.

Likewise, 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, 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 ‘‘overflow’’ floating-point exception is raised.

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.232) 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.

If a domain, pole, or range error occurs and the integer expression math_errhandling & MATH_ERRNO is zero, [233] then errno shall either be set to the value corresponding to the error or left unmodified. If no such error occurs, errno shall be left unmodified regardless of the setting of math_errhandling.

    #include <math.h>
             #pragma STDC FP_CONTRACT on-off-switch

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.

In the synopses in this subclause, real-floating indicates that the argument shall be an expression of real floating type.

    #include <math.h>
             int fpclassify(real-floating x);

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.234)

The fpclassify macro returns the value of the number classification macro appropriate to the value of its argument.

    #include <math.h>
            int isfinite(real-floating x);

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.

The isfinite macro returns a nonzero value if and only if its argument has a finite value.

    #include <math.h>
            int isinf(real-floating x);

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.

The isinf macro returns a nonzero value if and only if its argument has an infinite value.

    #include <math.h>
            int isnan(real-floating x);

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.235)

The isnan macro returns a nonzero value if and only if its argument has a NaN value.

    #include <math.h>
            int isnormal(real-floating x);

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.

The isnormal macro returns a nonzero value if and only if its argument has a normal value.

    #include <math.h>
            int signbit(real-floating x);

The signbit macro determines whether the sign of its argument value is negative.236)

The signbit macro returns a nonzero value if and only if the sign of its argument value is negative.

    #include <math.h>
           double acos(double x);
           float acosf(float x);
           long double acosl(long double x);

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].

The acos functions return arccos x in the interval [0, π ] radians.

    #include <math.h>
           double asin(double x);
           float asinf(float x);
           long double asinl(long double x);

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].

The asin functions return arcsin x in the interval [−π /2, +π /2] radians.

    #include <math.h>
           double atan(double x);
           float atanf(float x);
           long double atanl(long double x);

The atan functions compute the principal value of the arc tangent of x.

The atan functions return arctan x in the interval [−π /2, +π /2] radians.

    #include <math.h>
            double atan2(double y, double x);
            float atan2f(float y, float x);
            long double atan2l(long double y, long double x);

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.

The atan2 functions return arctan y/x in the interval [−π , +π ] radians.

    #include <math.h>
            double cos(double x);
            float cosf(float x);
            long double cosl(long double x);

The cos functions compute the cosine of x (measured in radians).

The cos functions return cos x.

    #include <math.h>
            double sin(double x);
            float sinf(float x);
            long double sinl(long double x);

The sin functions compute the sine of x (measured in radians).

The sin functions return sin x.

    #include <math.h>
           double tan(double x);
           float tanf(float x);
           long double tanl(long double x);

The tan functions return the tangent of x (measured in radians).

The tan functions return tan x.

    #include <math.h>
           double acosh(double x);
           float acoshf(float x);
           long double acoshl(long double x);

The acosh functions compute the (nonnegative) arc hyperbolic cosine of x. A domain error occurs for arguments less than 1.

The acosh functions return arcosh x in the interval [0, +∞].

    #include <math.h>
           double asinh(double x);
           float asinhf(float x);
           long double asinhl(long double x);

The asinh functions compute the arc hyperbolic sine of x.

The asinh functions return arsinh x.

    #include <math.h>
            double atanh(double x);
            float atanhf(float x);
            long double atanhl(long double x);

The atanh functions compute the arc hyperbolic tangent of x. A domain error occurs for arguments not in the interval [−1, +1]. A pole error may occur if the argument equals −1 or +1.

The atanh functions return artanh x.

    #include <math.h>
            double cosh(double x);
            float coshf(float x);
            long double coshl(long double x);

The cosh functions compute the hyperbolic cosine of x. A range error occurs if the magnitude of x is too large.

The cosh functions return cosh x.

    #include <math.h>
            double sinh(double x);
            float sinhf(float x);
            long double sinhl(long double x);

The sinh functions compute the hyperbolic sine of x. A range error occurs if the magnitude of x is too large.

The sinh functions return sinh x.

    #include <math.h>
           double tanh(double x);
           float tanhf(float x);
           long double tanhl(long double x);

The tanh functions compute the hyperbolic tangent of x.

The tanh functions return tanh x.

    #include <math.h>
           double exp(double x);
           float expf(float x);
           long double expl(long double x);

The exp functions compute the base-e exponential of x. A range error occurs if the magnitude of x is too large.

The exp functions return ex.

    #include <math.h>
           double exp2(double x);
           float exp2f(float x);
           long double exp2l(long double x);

The exp2 functions compute the base-2 exponential of x. A range error occurs if the magnitude of x is too large.

The exp2 functions return 2x.

    #include <math.h>
            double expm1(double x);
            float expm1f(float x);
            long double expm1l(long double x);

The expm1 functions compute the base-e exponential of the argument, minus 1. A range error occurs if x is too large.237)

The expm1 functions return ex1.

    #include <math.h>
            double frexp(double value, int *exp);
            float frexpf(float value, int *exp);
            long double frexpl(long double value, int *exp);

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.

If value is not a floating-point number or if the integral power of 2 is outside the range of int, 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.

    #include <math.h>
           int ilogb(double x);
           int ilogbf(float x);
           int ilogbl(long double x);

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.

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 ).

    #include <math.h>
           double ldexp(double x, int exp);
           float ldexpf(float x, int exp);
           long double ldexpl(long double x, int exp);

The ldexp functions multiply a floating-point number by an integral power of 2. A range error may occur.

The ldexp functions return x×2exp.

    #include <math.h>
           double log(double x);
           float logf(float x);
           long double logl(long double x);

The log functions compute the base-e (natural) logarithm of x. A domain error occurs if the argument is negative. A pole error may occur if the argument is zero.

The log functions return logex.

    #include <math.h>
            double log10(double x);
            float log10f(float x);
            long double log10l(long double x);

The log10 functions compute the base-10 (common) logarithm of x. A domain error occurs if the argument is negative. A pole error may occur if the argument is zero.

The log10 functions return log10x.

    #include <math.h>
            double log1p(double x);
            float log1pf(float x);
            long double log1pl(long double x);

The log1p functions compute the base-e (natural) logarithm of 1 plus the argument.238) A domain error occurs if the argument is less than −1. A pole error may occur if the argument equals −1.

The log1p functions return loge(1+x).

    #include <math.h>
           double log2(double x);
           float log2f(float x);
           long double log2l(long double x);

The log2 functions compute the base-2 logarithm of x. A domain error occurs if the argument is less than zero. A pole error may occur if the argument is zero.

The log2 functions return log2x.

    #include <math.h>
           double logb(double x);
           float logbf(float x);
           long double logbl(long double x);

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 pole error may occur if the argument is zero.

The logb functions return the signed exponent of x.

    #include <math.h>
           double modf(double value, double *iptr);
           float modff(float value, float *iptr);
           long double modfl(long double value, long double *iptr);

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.

The modf functions return the signed fractional part of value.

    #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);

The scalbn and scalbln functions compute x × FLT_RADIXn efficiently, not normally by computing FLT_RADIXn explicitly. A range error may occur.

The scalbn and scalbln functions return x×FLT_RADIXn.

    #include <math.h>
            double cbrt(double x);
            float cbrtf(float x);
            long double cbrtl(long double x);

The cbrt functions compute the real cube root of x.

The cbrt functions return x13.

    #include <math.h>
           double fabs(double x);
           float fabsf(float x);
           long double fabsl(long double x);

The fabs functions compute the absolute value of a floating-point number x.

The fabs functions return x.

    #include <math.h>
           double hypot(double x, double y);
           float hypotf(float x, float y);
           long double hypotl(long double x, long double y);

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.

The hypot functions return x2+y2.

    #include <math.h>
           double pow(double x, double y);
           float powf(float x, float y);
           long double powl(long double x, long double y);

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 pole error may occur if x is zero and y is less than zero.

The pow functions return xy.

    #include <math.h>
            double sqrt(double x);
            float sqrtf(float x);
            long double sqrtl(long double x);

The sqrt functions compute the nonnegative square root of x. A domain error occurs if the argument is less than zero.

The sqrt functions return x.

    #include <math.h>
            double erf(double x);
            float erff(float x);
            long double erfl(long double x);

The erf functions compute the error function of x.

The erf functions return erf(x)=2π0xet2dt.

    #include <math.h>
            double erfc(double x);
            float erfcf(float x);
            long double erfcl(long double x);

The erfc functions compute the complementary error function of x. A range error occurs if x is too large.

The erfc functions return erfc(x)=1erf(x)=2πxet2dt.

    #include <math.h>
           double lgamma(double x);
           float lgammaf(float x);
           long double lgammal(long double x);

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 pole error may occur if x is a negative integer or zero.

The lgamma functions return logeΓ(x).

    #include <math.h>
           double tgamma(double x);
           float tgammaf(float x);
           long double tgammal(long double x);

The tgamma functions compute the gamma function of x. A domain error or pole error may occur if x is a negative integer or zero. A range error occurs if the magnitude of x is too large and may occur if the magnitude of x is too small.

The tgamma functions return Γ(x).

    #include <math.h>
            double ceil(double x);
            float ceilf(float x);
            long double ceill(long double x);

The ceil functions compute the smallest integer value not less than x.

The ceil functions return ⎡x⎤, expressed as a floating-point number.

    #include <math.h>
            double floor(double x);
            float floorf(float x);
            long double floorl(long double x);

The floor functions compute the largest integer value not greater than x.

The floor functions return ⎣x⎦, expressed as a floating-point number.

    #include <math.h>
            double nearbyint(double x);
            float nearbyintf(float x);
            long double nearbyintl(long double x);

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.

The nearbyint functions return the rounded integer value.

    #include <math.h>
           double rint(double x);
           float rintf(float x);
           long double rintl(long double x);

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.

The rint functions return the rounded integer value.

    #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);

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.

The lrint and llrint functions return the rounded integer value.

    #include <math.h>
            double round(double x);
            float roundf(float x);
            long double roundl(long double x);

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.

The round functions return the rounded integer value.

    #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);

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.

The lround and llround functions return the rounded integer value.

    #include <math.h>
            double trunc(double x);
            float truncf(float x);
            long double truncl(long double x);

The trunc functions round their argument to the integer value, in floating format, nearest to but no larger in magnitude than the argument.

The trunc functions return the truncated integer value.

    #include <math.h>
             double fmod(double x, double y);
             float fmodf(float x, float y);
             long double fmodl(long double x, long double y);

The fmod functions compute the floating-point remainder of x/y.

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.

    #include <math.h>
             double remainder(double x, double y);
             float remainderf(float x, float y);
             long double remainderl(long double x, long double y);

The remainder functions compute the remainder x REM y required by IEC 60559.239 )

The remainder functions return x REM y. If y is zero, whether a domain error occurs or the functions return zero is implementation defined.

    #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);

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.

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.

    #include <math.h>
            double copysign(double x, double y);
            float copysignf(float x, float y);
            long double copysignl(long double x, long double y);

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.

The copysign functions return a value with the magnitude of x and the sign of y.

    #include <math.h>
            double nan(const char *tagp);
            float nanf(const char *tagp);
            long double nanl(const char *tagp);

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.

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.22.1.3 The strtod, strtof, and strtold functions ).

    #include <math.h>
            double nextafter(double x, double y);
            float nextafterf(float x, float y);
            long double nextafterl(long double x, long double y);

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.240) 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.

The nextafter functions return the next representable value in the specified format after x in the direction of y.

    #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);

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.241)

    #include <math.h>
            double fdim(double x, double y);
            float fdimf(float x, float y);
            long double fdiml(long double x, long double y);

The fdim functions determine the positive difference between their arguments: ⎧x − y if x > y ⎨

          ⎩+0     if x ≤ y

A range error may occur.

The fdim functions return the positive difference value.

    #include <math.h>
            double fmax(double x, double y);
            float fmaxf(float x, float y);
            long double fmaxl(long double x, long double y);

The fmax functions determine the maximum numeric value of their arguments.242)

The fmax functions return the maximum numeric value of their arguments.

    #include <math.h>
            double fmin(double x, double y);
            float fminf(float x, float y);
            long double fminl(long double x, long double y);

The fmin functions determine the minimum numeric value of their arguments.243)

The fmin functions return the minimum numeric value of their arguments.

    #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);

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.

The fma functions return (x × y) + z, rounded as one ternary operation.

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.244) 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 [245] (both arguments need not have the same type).246)

    #include <math.h>
             int isgreater(real-floating x, real-floating y);

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.

The isgreater macro returns the value of (x) > (y).

    #include <math.h>
             int isgreaterequal(real-floating x, real-floating y);

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.

The isgreaterequal macro returns the value of (x) >= (y).

    #include <math.h>
          int isless(real-floating x, real-floating y);

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.

The isless macro returns the value of (x) < (y).

    #include <math.h>
          int islessequal(real-floating x, real-floating y);

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.

The islessequal macro returns the value of (x) <= (y).

    #include <math.h>
            int islessgreater(real-floating x, real-floating y);

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).

The islessgreater macro returns the value of (x) < (y) || (x) > (y).

    #include <math.h>
            int isunordered(real-floating x, real-floating y);

The isunordered macro determines whether its arguments are unordered.

The isunordered macro returns 1 if its arguments are unordered and 0 otherwise.

The header <setjmp.h> defines the macro setjmp, and declares one function and one type, for bypassing the normal function call and return discipline.247)

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.

    #include <setjmp.h>
            int setjmp(jmp_buf env);

The setjmp macro saves its calling environment in its jmp_buf argument for later use by the longjmp function.

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.

    #include <setjmp.h>
             _Noreturn void longjmp(jmp_buf env, int val);

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 invocation was from another thread of execution, or if the function containing the invocation of the setjmp macro has terminated execution [248] 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 [249] 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.

After longjmp is completed, thread 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

}

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, [250] 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.

    #include <signal.h>
             void (*signal(int sig, void (*func)(int)))(int);

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), [251] 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 or thread storage duration that is not a lock-free atomic object 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, the quick_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.252)

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.

Use of this function in a multi-threaded program results in undefined behavior. The implementation shall behave as if no library function calls the signal function.

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.22.4.1 The abort function ), the exit function ( 7.22.4.4 The exit function ), the _Exit function ( 7.22.4.5 The _Exit function ), the quick_exit function ( 7.22.4.7 The quick_exit function ).

    #include <signal.h>
            int raise(int sig);

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.

The raise function returns zero if successful, nonzero if unsuccessful.

The header <stdalign.h> defines four macros.

The macro alignas expands to _Alignas; the macro alignof expands to _Alignof.

The remaining macros are suitable for use in #if preprocessing directives. They are _ _alignas_is_defined and _ _alignof_is_defined which both expand to the integer constant 1.

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 a complete 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.253)

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.

    #include <stdarg.h>
            type va_arg(va_list ap, type);

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.

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.

    #include <stdarg.h>
           void va_copy(va_list dest, va_list src);

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.

The va_copy macro returns no value.

    #include <stdarg.h>
           void va_end(va_list ap);

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.

The va_end macro returns no value.

    #include <stdarg.h>
            void va_start(va_list ap, parmN);

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.

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);
             }

The header <stdatomic.h> defines several macros and declares several types and functions for performing atomic operations on data shared between threads.254)

Implementations that define the macro _ _STDC_NO_ATOMICS_ _ need not provide this header nor support any of its facilities.

The macros defined are the atomic lock-free macros

             ATOMIC_BOOL_LOCK_FREE
             ATOMIC_CHAR_LOCK_FREE
             ATOMIC_CHAR16_T_LOCK_FREE
             ATOMIC_CHAR32_T_LOCK_FREE
             ATOMIC_WCHAR_T_LOCK_FREE
             ATOMIC_SHORT_LOCK_FREE
             ATOMIC_INT_LOCK_FREE
             ATOMIC_LONG_LOCK_FREE
             ATOMIC_LLONG_LOCK_FREE
             ATOMIC_POINTER_LOCK_FREE

which indicate the lock-free property of the corresponding atomic types (both signed and unsigned); and

             ATOMIC_FLAG_INIT

which expands to an initializer for an object of type atomic_flag.

The types include memory_order which is an enumerated type whose enumerators identify memory ordering constraints; atomic_flag which is a structure type representing a lock-free, primitive atomic flag; and several ∗ atomic analogs of integer types.

In the following synopses:

  • An A refers to one of the atomic types.
  • A C refers to its corresponding non-atomic type. ∗
  • An M refers to the type of the other argument for arithmetic operations. For atomic integer types, M is C. For atomic pointer types, M is ptrdiff_t.
  • The functions not ending in _explicit have the same semantics as the corresponding _explicit function with memory_order_seq_cst for the memory_order argument.

Many operations are volatile-qualified. The ‘‘volatile as device register’’ semantics have not changed in the standard. This qualification means that volatility is preserved when applying these operations to volatile objects.

    #include <stdatomic.h>
            #define ATOMIC_VAR_INIT(C value)

The ATOMIC_VAR_INIT macro expands to a token sequence suitable for initializing an atomic object of a type that is initialization-compatible with value. An atomic object with automatic storage duration that is not explicitly initialized using ATOMIC_VAR_INIT is initially in an indeterminate state; however, the default (zero) initialization for objects with static or thread-local storage duration is guaranteed to produce a valid state.

Concurrent access to the variable being initialized, even via an atomic operation, constitutes a data race.

    #include <stdatomic.h>
            void atomic_init(volatile A *obj, C value);

The atomic_init generic function initializes the atomic object pointed to by obj to the value value, while also initializing any additional state that the implementation might need to carry for the atomic object.

Although this function initializes an atomic object, it does not avoid data races; concurrent access to the variable being initialized, even via an atomic operation, constitutes a data race.

The atomic_init generic function returns no value.

atomic_int guide;

              atomic_init(&guide, 42);

The enumerated type memory_order specifies the detailed regular (non-atomic) memory synchronization operations as defined in 5.1.2.4 and may provide for operation ordering. Its enumeration constants are as follows: [255] memory_order_relaxed memory_order_consume memory_order_acquire memory_order_release memory_order_acq_rel memory_order_seq_cst

For memory_order_relaxed, no operation orders memory.

For memory_order_release, memory_order_acq_rel, and memory_order_seq_cst, a store operation performs a release operation on the affected memory location.

For memory_order_acquire, memory_order_acq_rel, and memory_order_seq_cst, a load operation performs an acquire operation on the affected memory location.

For memory_order_consume, a load operation performs a consume operation on the affected memory location.

There shall be a single total order S on all memory_order_seq_cst operations, consistent with the ‘‘happens before’’ order and modification orders for all affected locations, such that each memory_order_seq_cst operation B that loads a value from an atomic object M observes one of the following values:

  • the result of the last modification A of M that precedes B in S, if it exists, or
  • if A exists, the result of some modification of M in the visible sequence of side effects with respect to B that is not memory_order_seq_cst and that does not happen before A, or
  • if A does not exist, the result of some modification of M in the visible sequence of side effects with respect to B that is not memory_order_seq_cst.

Although it is not explicitly required that S include lock operations, it can always be extended to an order that does include lock and unlock operations, since the ordering between those is already included in the ‘‘happens before’’ ordering.

Atomic operations specifying memory_order_relaxed are relaxed only with respect to memory ordering. Implementations must still guarantee that any given atomic access to a particular atomic object be indivisible with respect to all other atomic accesses to that object.

For an atomic operation B that reads the value of an atomic object M, if there is a memory_order_seq_cst fence X sequenced before B, then B observes either the last memory_order_seq_cst modification of M preceding X in the total order S or a later modification of M in its modification order.

For atomic operations A and B on an atomic object M, where A modifies M and B takes its value, if there is a memory_order_seq_cst fence X such that A is sequenced before X and B follows X in S, then B observes either the effects of A or a later modification of M in its modification order.

For atomic operations A and B on an atomic object M, where A modifies M and B takes its value, if there are memory_order_seq_cst fences X and Y such that A is sequenced before X, Y is sequenced before B, and X precedes Y in S, then B observes either the effects of A or a later modification of M in its modification order.

Atomic read-modify-write operations shall always read the last value (in the modification order) stored before the write associated with the read-modify-write operation.

An atomic store shall only store a value that has been computed from constants and program input values by a finite sequence of program evaluations, such that each evaluation observes the values of variables as computed by the last prior assignment in the sequence.256) The ordering of evaluations in this sequence shall be such that

  • If an evaluation B observes a value computed by A in a different thread, then B does not happen before A.
  • If an evaluation A is included in the sequence, then all evaluations that assign to the same variable and happen before A are also included.

The second requirement disallows ‘‘out-of-thin-air’’, or ‘‘speculative’’ stores of atomics when
     relaxed atomics are used. Since unordered operations are involved, evaluations may appear in this
     sequence out of thread order. For example, with x and y initially zero,
               // Thread 1:
               r1 = atomic_load_explicit(&y, memory_order_relaxed);
               atomic_store_explicit(&x, r1, memory_order_relaxed);
               // Thread 2:
               r2 = atomic_load_explicit(&x, memory_order_relaxed);
               atomic_store_explicit(&y, 42, memory_order_relaxed);

is allowed to produce r1 == 42 && r2 == 42. The sequence of evaluations justifying this consists of:

               atomic_store_explicit(&y, 42, memory_order_relaxed);
               r1 = atomic_load_explicit(&y, memory_order_relaxed);
               atomic_store_explicit(&x, r1, memory_order_relaxed);
               r2 = atomic_load_explicit(&x, memory_order_relaxed);

On the other hand,

               // Thread 1:
               r1 = atomic_load_explicit(&y, memory_order_relaxed);
               atomic_store_explicit(&x, r1, memory_order_relaxed);
               // Thread 2:
               r2 = atomic_load_explicit(&x, memory_order_relaxed);
               atomic_store_explicit(&y, r2, memory_order_relaxed);

is not allowed to produce r1 == 42 && r2 = 42, since there is no sequence of evaluations that results in the computation of 42. In the absence of ‘‘relaxed’’ operations and read-modify-write operations with weaker than memory_order_acq_rel ordering, the second requirement has no impact.

Recommended practice

The requirements do not forbid r1 == 42 && r2 == 42 in the following example, with x and y initially zero:

             // Thread 1:
             r1 = atomic_load_explicit(&x, memory_order_relaxed);
             if (r1 == 42)
                  atomic_store_explicit(&y, r1, memory_order_relaxed);
             // Thread 2:
             r2 = atomic_load_explicit(&y, memory_order_relaxed);
             if (r2 == 42)
                  atomic_store_explicit(&x, 42, memory_order_relaxed);

However, this is not useful behavior, and implementations should not allow it.

Implementations should make atomic stores visible to atomic loads within a reasonable amount of time.

    #include <stdatomic.h>
           type kill_dependency(type y);

The kill_dependency macro terminates a dependency chain; the argument does not carry a dependency to the return value.

The kill_dependency macro returns the value of y.

This subclause introduces synchronization primitives called fences. Fences can have acquire semantics, release semantics, or both. A fence with acquire semantics is called an acquire fence; a fence with release semantics is called a release fence.

A release fence A synchronizes with an acquire fence B if there exist atomic operations X and Y , both operating on some atomic object M, such that A is sequenced before X, X modifies M, Y is sequenced before B, and Y reads the value written by X or a value written by any side effect in the hypothetical release sequence X would head if it were a release operation.

A release fence A synchronizes with an atomic operation B that performs an acquire operation on an atomic object M if there exists an atomic operation X such that A is sequenced before X, X modifies M, and B reads the value written by X or a value written by any side effect in the hypothetical release sequence X would head if it were a release operation.

An atomic operation A that is a release operation on an atomic object M synchronizes with an acquire fence B if there exists some atomic operation X on M such that X is sequenced before B and reads the value written by A or a value written by any side effect in the release sequence headed by A.

    #include <stdatomic.h>
           void atomic_thread_fence(memory_order order);

Depending on the value of order, this operation:

  • has no effects, if order == memory_order_relaxed;
  • is an acquire fence, if order == memory_order_acquire or order == memory_order_consume;
  • is a release fence, if order == memory_order_release;
  • is both an acquire fence and a release fence, if order == memory_order_acq_rel;
  • is a sequentially consistent acquire and release fence, if order == memory_order_seq_cst.

The atomic_thread_fence function returns no value.

    #include <stdatomic.h>
            void atomic_signal_fence(memory_order order);

Equivalent to atomic_thread_fence(order), except that the resulting ordering constraints are established only between a thread and a signal handler executed in the same thread.

The atomic_signal_fence function can be used to specify the order in which actions performed by the thread become visible to the signal handler.

Compiler optimizations and reorderings of loads and stores are inhibited in the same way as with atomic_thread_fence, but the hardware fence instructions that atomic_thread_fence would have inserted are not emitted.

The atomic_signal_fence function returns no value.

The atomic lock-free macros indicate the lock-free property of integer and address atomic types. A value of 0 indicates that the type is never lock-free; a value of 1 indicates that the type is sometimes lock-free; a value of 2 indicates that the type is always lock-free.

Operations that are lock-free should also be address-free. That is, atomic operations on the same memory location via two different addresses will communicate atomically. The implementation should not depend on any per-process state. This restriction enables communication via memory mapped into a process more than once and memory shared between two processes.

    #include <stdatomic.h>
             _Bool atomic_is_lock_free(const volatile A *obj);

The atomic_is_lock_free generic function indicates whether or not the object

    pointed to by obj is lock-free.                                              ∗

The atomic_is_lock_free generic function returns nonzero (true) if and only if the object’s operations are lock-free. The result of a lock-free query on one object cannot be inferred from the result of a lock-free query on another object.

For each line in the following table, [257] the atomic type name is declared as a type that has the same representation and alignment requirements as the corresponding direct type.258)

                  Atomic type name                        Direct type
              atomic_bool                        _Atomic _Bool
              atomic_char                        _Atomic char
              atomic_schar                       _Atomic signed char
              atomic_uchar                       _Atomic unsigned char
              atomic_short                       _Atomic short
              atomic_ushort                      _Atomic unsigned short
              atomic_int                         _Atomic int
              atomic_uint                        _Atomic unsigned int
              atomic_long                        _Atomic long
              atomic_ulong                       _Atomic unsigned long
              atomic_llong                       _Atomic long long
              atomic_ullong                      _Atomic unsigned long long
              atomic_char16_t                    _Atomic char16_t
              atomic_char32_t                    _Atomic char32_t
              atomic_wchar_t                     _Atomic wchar_t
              atomic_int_least8_t                _Atomic int_least8_t
              atomic_uint_least8_t               _Atomic uint_least8_t
              atomic_int_least16_t               _Atomic int_least16_t
              atomic_uint_least16_t              _Atomic uint_least16_t
              atomic_int_least32_t               _Atomic int_least32_t
              atomic_uint_least32_t              _Atomic uint_least32_t
              atomic_int_least64_t               _Atomic int_least64_t
              atomic_uint_least64_t              _Atomic uint_least64_t
              atomic_int_fast8_t                 _Atomic int_fast8_t
              atomic_uint_fast8_t                _Atomic uint_fast8_t
              atomic_int_fast16_t                _Atomic int_fast16_t
              atomic_uint_fast16_t               _Atomic uint_fast16_t
              atomic_int_fast32_t                _Atomic int_fast32_t
              atomic_uint_fast32_t               _Atomic uint_fast32_t
              atomic_int_fast64_t                _Atomic int_fast64_t
              atomic_uint_fast64_t               _Atomic uint_fast64_t
              atomic_intptr_t                    _Atomic intptr_t
              atomic_uintptr_t                   _Atomic uintptr_t
              atomic_size_t                      _Atomic size_t
              atomic_ptrdiff_t                   _Atomic ptrdiff_t
              atomic_intmax_t                    _Atomic intmax_t
              atomic_uintmax_t                   _Atomic uintmax_t

The semantics of the operations on these types are defined in 7.17.7. ∗

The representation of atomic integer types need not have the same size as their corresponding regular types. They should have the same size whenever possible, as it eases effort required to port existing code.

There are only a few kinds of operations on atomic types, though there are many instances of those kinds. This subclause specifies each general kind.

    #include <stdatomic.h>
             void atomic_store(volatile A *object, C desired);
             void atomic_store_explicit(volatile A *object,
                  C desired, memory_order order);

The order argument shall not be memory_order_acquire, memory_order_consume, nor memory_order_acq_rel. Atomically replace the value pointed to by object with the value of desired. Memory is affected according to the value of order.

The atomic_store generic functions return no value.

    #include <stdatomic.h>
             C atomic_load(volatile A *object);
             C atomic_load_explicit(volatile A *object,
                  memory_order order);

The order argument shall not be memory_order_release nor memory_order_acq_rel. Memory is affected according to the value of order.

Atomically returns the value pointed to by object.

    #include <stdatomic.h>
             C atomic_exchange(volatile A *object, C desired);
             C atomic_exchange_explicit(volatile A *object,
                  C desired, memory_order order);

Atomically replace the value pointed to by object with desired. Memory is affected according to the value of order. These operations are read-modify-write operations ( 5.1.2.4 ).

Atomically returns the value pointed to by object immediately before the effects.

    #include <stdatomic.h>
             _Bool atomic_compare_exchange_strong(volatile A *object,
                  C *expected, C desired);
             _Bool atomic_compare_exchange_strong_explicit(
                  volatile A *object, C *expected, C desired,
                  memory_order success, memory_order failure);
             _Bool atomic_compare_exchange_weak(volatile A *object,
                  C *expected, C desired);
             _Bool atomic_compare_exchange_weak_explicit(
                  volatile A *object, C *expected, C desired,
                  memory_order success, memory_order failure);

The failure argument shall not be memory_order_release nor memory_order_acq_rel. The failure argument shall be no stronger than the success argument. Atomically, compares the value pointed to by object for equality with that in expected, and if true, replaces the value pointed to by object with desired, and if false, updates the value in expected with the value pointed to by object. Further, if the comparison is true, memory is affected according to the value of success, and if the comparison is false, memory is affected according to the value of failure. These operations are atomic read-modify-write operations ( 5.1.2.4 ).

For example, the effect of atomic_compare_exchange_strong is
             if (memcmp(object, expected, sizeof (*object)) == 0)
                   memcpy(object, &desired, sizeof (*object));
             else
                   memcpy(expected, object, sizeof (*object));

A weak compare-and-exchange operation may fail spuriously. That is, even when the contents of memory referred to by expected and object are equal, it may return zero and store back to expected the same memory contents that were originally there.

This spurious failure enables implementation of compare-and-exchange on a broader class of machines, e.g. load-locked store-conditional machines.

A consequence of spurious failure is that nearly all uses of weak compare-and-exchange will be in a loop.

             exp = atomic_load(&cur);
             do {
                   des = function(exp);
             } while (!atomic_compare_exchange_weak(&cur, &exp, des));

When a compare-and-exchange is in a loop, the weak version will yield better performance on some platforms. When a weak compare-and-exchange would require a loop and a strong one would not, the strong one is preferable.

The result of the comparison.

The following operations perform arithmetic and bitwise computations. All of these operations are applicable to an object of any atomic integer type. None of these ∗ operations is applicable to atomic_bool. The key, operator, and computation correspondence is:

     key            op          computation
     add            +       addition
     sub            -       subtraction
     or             |       bitwise inclusive or
     xor            ˆ       bitwise exclusive or
     and            &       bitwise and

    #include <stdatomic.h>
             C atomic_fetch_key(volatile A *object, M operand);
             C atomic_fetch_key_explicit(volatile A *object,
                  M operand, memory_order order);

Atomically replaces the value pointed to by object with the result of the computation applied to the value pointed to by object and the given operand. Memory is affected according to the value of order. These operations are atomic read-modify-write operations ( 5.1.2.4 ). For signed integer types, arithmetic is defined to use two’s complement representation with silent wrap-around on overflow; there are no undefined results. For address types, the result may be an undefined address, but the operations otherwise have no undefined behavior.

Atomically, the value pointed to by object immediately before the effects.

The operation of the atomic_fetch and modify generic functions are nearly equivalent to the operation of the corresponding op= compound assignment operators. The only differences are that the compound assignment operators are not guaranteed to operate atomically, and the value yielded by a compound assignment operator is the updated value of the object, whereas the value returned by the atomic_fetch and modify generic functions is the previous value of the atomic object.

The atomic_flag type provides the classic test-and-set functionality. It has two states, set and clear.

Operations on an object of type atomic_flag shall be lock free.

Hence the operations should also be address-free. No other type requires lock-free operations, so the atomic_flag type is the minimum hardware-implemented type needed to conform to this International standard. The remaining types can be emulated with atomic_flag, though with less than ideal properties.

The macro ATOMIC_FLAG_INIT may be used to initialize an atomic_flag to the clear state. An atomic_flag that is not explicitly initialized with ATOMIC_FLAG_INIT is initially in an indeterminate state.

    #include <stdatomic.h>
            _Bool atomic_flag_test_and_set(
                 volatile atomic_flag *object);
            _Bool atomic_flag_test_and_set_explicit(
                 volatile atomic_flag *object, memory_order order);

Atomically sets the value pointed to by object to true. Memory is affected according to the value of order. These operations are atomic read-modify-write operations ( 5.1.2.4 ).

Atomically, the value of the object immediately before the effects.

    #include <stdatomic.h>
           void atomic_flag_clear(volatile atomic_flag *object);
           void atomic_flag_clear_explicit(
                volatile atomic_flag *object, memory_order order);

The order argument shall not be memory_order_acquire nor memory_order_acq_rel. Atomically sets the value pointed to by object to false. Memory is affected according to the value of order.

The atomic_flag_clear functions return no value.

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.259)

The header <stddef.h> defines the following macros and declares the following types. 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; max_align_t which is an object type whose alignment is as great as is supported by the implementation in all contexts; 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.                                               ∗

The header <stdint.h> declares sets of integer types having specified widths, and defines corresponding sets of macros.260) 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, [261] <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’’).

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).

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 such a signed integer type with a width of exactly 8 bits.

The typedef name uintN_t designates an unsigned integer type with width N and no padding bits. Thus, uint24_t denotes such 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.

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.

Each of the following types designates an integer type that is usually fastest [262] 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.

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.

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.

The following object-like macros specify the minimum and maximum limits of the types declared in <stdint.h>. Each macro name corresponds to a similar type name in 7.20.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.

  • 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

  • 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

  • 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

  • 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

  • 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

The following object-like macros 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.263)

  • 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.19 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.264 )

If wint_t (see 7.29 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.

The following function-like macros 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.20.1.2 Minimum-width integer types or 7.20.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.

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.

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)

The header <stdio.h> defines several macros, and declares three types and many functions for performing input and output.

The types declared are size_t (described in 7.19 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 a complete 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.19 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; [265] 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 minimum 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.21.3.

The input/output functions are given the following collective terms:

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.266)

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.)267)

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.

Each stream has an associated lock that is used to prevent data races when multiple threads of execution access a stream, and to restrict the interleaving of stream operations performed by multiple threads. Only one thread may hold this lock at a time. The lock is reentrant: a single thread may hold the lock multiple times at a given time.

All functions that read, write, position, or query the position of a stream lock the stream before accessing it. They release the lock associated with the stream when the access is complete. 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.21.5.4 The freopen function ), the fwide function ( 7.29.3.5 The fwide function ), mbstate_t ( 7.30.1 Introduction ), the fgetpos function ( 7.21.9.1 The fgetpos function ), the fsetpos function ( 7.21.9.3 The fsetpos function ).

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.21.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.268)

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.22.4.4 The exit function ), the fgetc function ( 7.21.7.1 The fgetc function ), the fopen function ( 7.21.5.3 The fopen function ), the fputc function ( 7.21.7.3 The fputc function ), the setbuf function ( 7.21.5.5 The setbuf function ), the setvbuf function ( 7.21.5.6 The setvbuf function ), the fgetwc function ( 7.29.3.1 The fgetwc function ), the fputwc function ( 7.29.3.3 The fputwc function ), conversion state ( 7.29.6 Extended multibyte/wide character conversion utilities ), the mbrtowc function ( 7.29.6.3.2 The mbrtowc function ), the wcrtomb function ( 7.29.6.3.3 The wcrtomb function ).

    #include <stdio.h>
            int remove(const char *filename);

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.

The remove function returns zero if the operation succeeds, nonzero if it fails.

    #include <stdio.h>
            int rename(const char *old, const char *new);

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.

The rename function returns zero if the operation succeeds, nonzero if it fails, [269] in which case if the file existed previously it is still known by its original name.

    #include <stdio.h>
            FILE *tmpfile(void);

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).

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.21.5.3 The fopen function ).

    #include <stdio.h>
            char *tmpnam(char *s);

The tmpnam function generates a string that is a valid file name and that is not the same as the name of an existing file.270) The function is potentially capable of generating at least 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.

Calls to the tmpnam function with a null pointer argument may introduce data races with each other. The implementation shall behave as if no library function calls the tmpnam function.

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.

    #include <stdio.h>
           int fclose(FILE *stream);

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).

The fclose function returns zero if the stream was successfully closed, or EOF if any errors were detected.

    #include <stdio.h>
            int fflush(FILE *stream);

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.

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.21.5.3 The fopen function ).

    #include <stdio.h>
            FILE *fopen(const char * restrict filename,
                 const char * restrict mode);

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.271)

    r                     open text file for reading
    w                     truncate to zero length or create text file for writing
    wx                    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
    wbx          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
    w+x          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

w+bx or wb+x 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 exclusive mode ('x' as the last character in the mode argument) fails if the file already exists or cannot be created. Otherwise, the file is created with exclusive (also known as non-shared) access to the extent that the underlying system supports exclusive access.

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.

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.21.9 File positioning functions ).

    #include <stdio.h>
            FILE *freopen(const char * restrict filename,
                 const char * restrict mode,
                 FILE * restrict stream);

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.272)

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.

The freopen function returns a null pointer if the open operation fails. Otherwise, freopen returns the value of stream.

    #include <stdio.h>
            void setbuf(FILE * restrict stream,
                 char * restrict buf);

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.

The setbuf function returns no value. Forward references: the setvbuf function ( 7.21.5.6 The setvbuf function ).

    #include <stdio.h>
            int setvbuf(FILE * restrict stream,
                 char * restrict buf,
                 int mode, size_t size);

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 [273] 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.

The setvbuf function returns zero on success, or nonzero if an invalid value is given for mode or if the request cannot be honored.

The formatted input/output functions shall behave as if there is a sequence point after the actions associated with each specifier.274)

    #include <stdio.h>
             int fprintf(FILE * restrict stream,
                  const char * restrict format, ...);

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.275)
  • 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.)276)
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:

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.
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.
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.
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.
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.
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.
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.
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.277) 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 [278] 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 [279] 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.280) 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.281) 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.282) 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.283) 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.

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));

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.29.6 Extended multibyte/wide character conversion utilities ), the wcrtomb function ( 7.29.6.3.3 The wcrtomb function ).

    #include <stdio.h>
            int fscanf(FILE * restrict stream,
                 const char * restrict format, ...);

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. When all directives have been executed, or 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. The directive never fails.

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.284)

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.285) 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:

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.
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.
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.
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.
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.
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.
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.
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:

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.
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.
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.
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.
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.
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.
Matches a sequence of characters of exactly the number specified by the field width (1 if no field width is present in the directive).286) 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.
Matches a sequence of non-white-space characters.286) 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).286) 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.
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.
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.287)

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.

The fscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. 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.

The call:

               #include <stdio.h>
               /* ... */
               int n, i;
               n = sscanf("foo %            bar    42", "foo%%bar%d", &i);

will assign to n the value 1 and to i the value 42 because input white-space characters are skipped for both the % and d conversion specifiers.

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.22.1.3 The strtod, strtof, and strtold functions ), the strtol, strtoll, strtoul, and strtoull functions ( 7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions ), conversion state ( 7.29.6 Extended multibyte/wide character conversion utilities ), the wcrtomb function ( 7.29.6.3.3 The wcrtomb function ).

    #include <stdio.h>
             int printf(const char * restrict format, ...);

The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf.

The printf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.

    #include <stdio.h>
            int scanf(const char * restrict format, ...);

The scanf function is equivalent to fscanf with the argument stdin interposed before the arguments to scanf.

The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. 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.

    #include <stdio.h>
            int snprintf(char * restrict s, size_t n,
                 const char * restrict format, ...);

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.

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.

    #include <stdio.h>
            int sprintf(char * restrict s,
                 const char * restrict format, ...);

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.

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.

    #include <stdio.h>
           int sscanf(const char * restrict s,
                const char * restrict format, ...);

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.

The sscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. 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.

    #include <stdarg.h>
           #include <stdio.h>
           int vfprintf(FILE * restrict stream,
                const char * restrict format,
                va_list arg);

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.288)

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);
            }

    #include <stdarg.h>
            #include <stdio.h>
            int vfscanf(FILE * restrict stream,
                 const char * restrict format,
                 va_list arg);

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.288)

The vfscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. 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.

    #include <stdarg.h>
           #include <stdio.h>
           int vprintf(const char * restrict format,
                va_list arg);

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.288)

The vprintf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.

    #include <stdarg.h>
           #include <stdio.h>
           int vscanf(const char * restrict format,
                va_list arg);

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.288)

The vscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. 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.

    #include <stdarg.h>
            #include <stdio.h>
            int vsnprintf(char * restrict s, size_t n,
                 const char * restrict format,
                 va_list arg);

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.288) If copying takes place between objects that overlap, the behavior is undefined.

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.

    #include <stdarg.h>
            #include <stdio.h>
            int vsprintf(char * restrict s,
                 const char * restrict format,
                 va_list arg);

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.288) If copying takes place between objects that overlap, the behavior is undefined.

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.

    #include <stdarg.h>
            #include <stdio.h>
            int vsscanf(const char * restrict s,
                 const char * restrict format,
                 va_list arg);

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.288)

The vsscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. 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.

    #include <stdio.h>
            int fgetc(FILE *stream);

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).

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.289)

    #include <stdio.h>
            char *fgets(char * restrict s, int n,
                 FILE * restrict stream);

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.

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.

    #include <stdio.h>
            int fputc(int c, FILE *stream);

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.

The fputc function returns the character written. If a write error occurs, the error indicator for the stream is set and fputc returns EOF.

    #include <stdio.h>
            int fputs(const char * restrict s,
                 FILE * restrict stream);

The fputs function writes the string pointed to by s to the stream pointed to by stream. The terminating null character is not written.

The fputs function returns EOF if a write error occurs; otherwise it returns a nonnegative value.

    #include <stdio.h>
           int getc(FILE *stream);

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.

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.

    #include <stdio.h>
           int getchar(void);

The getchar function is equivalent to getc with the argument stdin.

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.

    #include <stdio.h>
            int putc(int c, FILE *stream);

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.

The putc function returns the character written. If a write error occurs, the error indicator for the stream is set and putc returns EOF.

    #include <stdio.h>
            int putchar(int c);

The putchar function is equivalent to putc with the second argument stdout.

The putchar function returns the character written. If a write error occurs, the error indicator for the stream is set and putchar returns EOF.

    #include <stdio.h>
            int puts(const char *s);

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.

The puts function returns EOF if a write error occurs; otherwise it returns a nonnegative value.

    #include <stdio.h>
             int ungetc(int c, FILE *stream);

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.290)

The ungetc function returns the character pushed back after conversion, or EOF if the operation fails. Forward references: file positioning functions ( 7.21.9 File positioning functions ).

    #include <stdio.h>
            size_t fread(void * restrict ptr,
                 size_t size, size_t nmemb,
                 FILE * restrict stream);

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.

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.

    #include <stdio.h>
            size_t fwrite(const void * restrict ptr,
                 size_t size, size_t nmemb,
                 FILE * restrict stream);

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.

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.

    #include <stdio.h>
           int fgetpos(FILE * restrict stream,
                fpos_t * restrict pos);

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.

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.21.9.3 The fsetpos function ).

    #include <stdio.h>
           int fseek(FILE *stream, long int offset, int whence);

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.

The fseek function returns nonzero only for a request that cannot be satisfied. Forward references: the ftell function ( 7.21.9.4 The ftell function ).

    #include <stdio.h>
            int fsetpos(FILE *stream, const fpos_t *pos);

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.

If successful, the fsetpos function returns zero; on failure, the fsetpos function returns nonzero and stores an implementation-defined positive value in errno.

    #include <stdio.h>
            long int ftell(FILE *stream);

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.

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.

    #include <stdio.h>
           void rewind(FILE *stream);

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.

The rewind function returns no value.

    #include <stdio.h>
           void clearerr(FILE *stream);

The clearerr function clears the end-of-file and error indicators for the stream pointed to by stream.

The clearerr function returns no value.

    #include <stdio.h>
            int feof(FILE *stream);

The feof function tests the end-of-file indicator for the stream pointed to by stream.

The feof function returns nonzero if and only if the end-of-file indicator is set for stream.

    #include <stdio.h>
            int ferror(FILE *stream);

The ferror function tests the error indicator for the stream pointed to by stream.

The ferror function returns nonzero if and only if the error indicator is set for stream.

    #include <stdio.h>
            void perror(const char *s);

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.

The perror function returns no value. Forward references: the strerror function ( 7.24.6.2 The strerror function ).

The header <stdlib.h> declares five types and several functions of general utility, and defines several macros.291)

The types declared are size_t and wchar_t (both described in 7.19 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.19 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.

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.

    #include <stdlib.h>
            double atof(const char *nptr);

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)

The atof function returns the converted value. Forward references: the strtod, strtof, and strtold functions ( 7.22.1.3 The strtod, strtof, and strtold functions ).

    #include <stdlib.h>
            int atoi(const char *nptr);
            long int atol(const char *nptr);
            long long int atoll(const char *nptr);

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)

The atoi, atol, and atoll functions return the converted value. Forward references: the strtol, strtoll, strtoul, and strtoull functions ( 7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions ).

    #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);

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.292) 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 sequence is implementation-defined.293) 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.294)

The functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value overflows and default rounding is in effect ( 7.12.1 Treatment of error conditions ), 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.

    #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);

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.

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.

    #include <stdlib.h>
            int rand(void);

The rand function computes a sequence of pseudo-random integers in the range 0 to RAND_MAX.295)

The rand function is not required to avoid data races with other calls to pseudo-random sequence generation functions. The implementation shall behave as if no library function calls the rand function.

The rand function returns a pseudo-random integer. Environmental limits

The value of the RAND_MAX macro shall be at least 32767.

    #include <stdlib.h>
            void srand(unsigned int seed);

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 srand function is not required to avoid data races with other calls to pseudo-random sequence generation functions. The implementation shall behave as if no library function calls the srand function.

The srand function returns no value.

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;
            }

The order and contiguity of storage allocated by successive calls to the aligned_alloc, 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 with a fundamental alignment requirement 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.

For purposes of determining the existence of a data race, memory allocation functions behave as though they accessed only memory locations accessible through their arguments and not other static duration storage. These functions may, however, visibly modify the storage that they allocate or deallocate. A call to free or realloc that deallocates a region p of memory synchronizes with any allocation call that allocates all or part of the region p. This synchronization occurs after any access of p by the deallocating function, and before any such access by the allocating function.

    #include <stdlib.h>
            void *aligned_alloc(size_t alignment, size_t size);

The aligned_alloc function allocates space for an object whose alignment is specified by alignment, whose size is specified by size, and whose value is indeterminate. The value of alignment shall be a valid alignment supported by the implementation and the value of size shall be an integral multiple of alignment.

The aligned_alloc function returns either a null pointer or a pointer to the allocated space.

    #include <stdlib.h>
            void *calloc(size_t nmemb, size_t size);

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.296)

The calloc function returns either a null pointer or a pointer to the allocated space.

    #include <stdlib.h>
            void free(void *ptr);

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 a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

The free function returns no value.

    #include <stdlib.h>
            void *malloc(size_t size);

The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

The malloc function returns either a null pointer or a pointer to the allocated space.

    #include <stdlib.h>
            void *realloc(void *ptr, size_t size);

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 a memory management 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.

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.

    #include <stdlib.h>
           _Noreturn void abort(void);

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).

The abort function does not return to its caller.

    #include <stdlib.h>
           int atexit(void (*func)(void));

The atexit function registers the function pointed to by func, to be called without arguments at normal program termination.297) It is unspecified whether a call to the atexit function that does not happen before the exit function is called will succeed. Environmental limits

The implementation shall support the registration of at least 32 functions.

The atexit function returns zero if the registration succeeds, nonzero if it fails. Forward references: the at_quick_exit function ( 7.22.4.3 The at_quick_exit function ), the exit function ( 7.22.4.4 The exit function ).

    #include <stdlib.h>
            int at_quick_exit(void (*func)(void));

The at_quick_exit function registers the function pointed to by func, to be called without arguments should quick_exit be called.298) It is unspecified whether a call to the at_quick_exit function that does not happen before the quick_exit function is called will succeed. Environmental limits

The implementation shall support the registration of at least 32 functions.

The at_quick_exit function returns zero if the registration succeeds, nonzero if it fails. Forward references: the quick_exit function ( 7.22.4.7 The quick_exit function ).

    #include <stdlib.h>
            _Noreturn void exit(int status);

The exit function causes normal program termination to occur. No functions registered by the at_quick_exit function are called. If a program calls the exit function more than once, or calls the quick_exit function in addition to the exit function, the behavior is undefined.

First, all functions registered by the atexit function are called, in the reverse order of their registration, [299] 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.

The exit function cannot return to its caller.

    #include <stdlib.h>
            _Noreturn void _Exit(int status);

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, the at_quick_exit 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.22.4.4 The exit function ). Whether open streams with unwritten buffered data are flushed, open streams are closed, or temporary files are removed is implementation-defined.

The _Exit function cannot return to its caller.

    #include <stdlib.h>
            char *getenv(const char *name);

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 getenv function need not avoid data races with other threads of execution that modify the environment list.300)

The implementation shall behave as if no library function calls the getenv function.

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.

    #include <stdlib.h>
            _Noreturn void quick_exit(int status);

The quick_exit function causes normal program termination to occur. No functions registered by the atexit function or signal handlers registered by the signal function are called. If a program calls the quick_exit function more than once, or calls the exit function in addition to the quick_exit function, the behavior is undefined. If a signal is raised while the quick_exit function is executing, the behavior is undefined.

The quick_exit function first calls all functions registered by the at_quick_exit function, in the reverse order of their registration, [301] 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.

Then control is returned to the host environment by means of the function call _Exit(status).

The quick_exit function cannot return to its caller.

    #include <stdlib.h>
            int system(const char *string);

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.

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.

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.302) 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.

    #include <stdlib.h>
             void *bsearch(const void *key, const void *base,
                  size_t nmemb, size_t size,
                  int (*compar)(const void *, const void *));

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.303)

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.

    #include <stdlib.h>
             void qsort(void *base, size_t nmemb, size_t size,
                  int (*compar)(const void *, const void *));

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.

The qsort function returns no value.

    #include <stdlib.h>
            int abs(int j);
            long int labs(long int j);
            long long int llabs(long long int j);

The abs, labs, and llabs functions compute the absolute value of an integer j. If the result cannot be represented, the behavior is undefined.304)

The abs, labs, and llabs, functions return the absolute value.

    #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);

The div, ldiv, and lldiv, functions compute numer / denom and numer % denom in a single operation.

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.

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 at program startup and can be returned to that 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.305) Changing the LC_CTYPE category causes the conversion state of these functions to be indeterminate.

    #include <stdlib.h>
            int mblen(const char *s, size_t n);

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, (const char *)0, 0);
            mbtowc((wchar_t *)0, s, n);

The implementation shall behave as if no library function calls the mblen function.

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.22.7.2 The mbtowc function ).

    #include <stdlib.h>
           int mbtowc(wchar_t * restrict pwc,
                const char * restrict s,
                size_t n);

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.

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.

    #include <stdlib.h>
           int wctomb(char *s, wchar_t wc);

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.

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.

The behavior of the multibyte string functions is affected by the LC_CTYPE category of the current locale.

    #include <stdlib.h>
             size_t mbstowcs(wchar_t * restrict pwcs,
                  const char * restrict s,
                  size_t n);

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.

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.306)

    #include <stdlib.h>
           size_t wcstombs(char * restrict s,
                const wchar_t * restrict pwcs,
                size_t n);

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.

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.306)

The header <stdnoreturn.h> defines the macro noreturn which expands to _Noreturn.

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.307) The type is size_t and the macro is NULL (both described in 7.19 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).

    #include <string.h>
             void *memcpy(void * restrict s1,
                  const void * restrict s2,
                  size_t n);

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.

The memcpy function returns the value of s1.

    #include <string.h>
            void *memmove(void *s1, const void *s2, size_t n);

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.

The memmove function returns the value of s1.

    #include <string.h>
            char *strcpy(char * restrict s1,
                 const char * restrict s2);

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.

The strcpy function returns the value of s1.

    #include <string.h>
            char *strncpy(char * restrict s1,
                 const char * restrict s2,
                 size_t n);

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.308 ) 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.

The strncpy function returns the value of s1.

    #include <string.h>
             char *strcat(char * restrict s1,
                  const char * restrict s2);

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.

The strcat function returns the value of s1.

    #include <string.h>
             char *strncat(char * restrict s1,
                  const char * restrict s2,
                  size_t n);

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.309) If copying takes place between objects that overlap, the behavior is undefined.

The strncat function returns the value of s1. Forward references: the strlen function ( 7.24.6.3 The strlen function ).

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.

    #include <string.h>
            int memcmp(const void *s1, const void *s2, size_t n);

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.310 )

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.

    #include <string.h>
            int strcmp(const char *s1, const char *s2);

The strcmp function compares the string pointed to by s1 to the string pointed to by s2.

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.

    #include <string.h>
           int strcoll(const char *s1, const char *s2);

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.

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.

    #include <string.h>
           int strncmp(const char *s1, const char *s2, size_t n);

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.

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.

    #include <string.h>
           size_t strxfrm(char * restrict s1,
                const char * restrict s2,
                size_t n);

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.

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.

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)

    #include <string.h>
            void *memchr(const void *s, int c, size_t n);

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. The implementation shall behave as if it reads the characters sequentially and stops as soon as a matching character is found.

The memchr function returns a pointer to the located character, or a null pointer if the character does not occur in the object.

    #include <string.h>
            char *strchr(const char *s, int c);

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.

The strchr function returns a pointer to the located character, or a null pointer if the character does not occur in the string.

    #include <string.h>
           size_t strcspn(const char *s1, const char *s2);

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.

The strcspn function returns the length of the segment.

    #include <string.h>
           char *strpbrk(const char *s1, const char *s2);

The strpbrk function locates the first occurrence in the string pointed to by s1 of any character from the string pointed to by s2.

The strpbrk function returns a pointer to the character, or a null pointer if no character from s2 occurs in s1.

    #include <string.h>
           char *strrchr(const char *s, int c);

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.

The strrchr function returns a pointer to the character, or a null pointer if c does not occur in the string.

    #include <string.h>
            size_t strspn(const char *s1, const char *s2);

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.

The strspn function returns the length of the segment.

    #include <string.h>
            char *strstr(const char *s1, const char *s2);

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.

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.

    #include <string.h>
            char *strtok(char * restrict s1,
                 const char * restrict s2);

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 strtok function is not required to avoid data races with other calls to the strtok function.311) The implementation shall behave as if no library function calls the strtok function.

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

Forward references: The strtok_s function (K.3.7.3.1).

    #include <string.h>
            void *memset(void *s, int c, size_t n);

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.

The memset function returns the value of s.

    #include <string.h>
            char *strerror(int errnum);

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 strerror function is not required to avoid data races with other calls to the strerror function.312) The implementation shall behave as if no library function calls the strerror function.

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. Forward references: The strerror_s function (K.3.7.4.2).

    #include <string.h>
           size_t strlen(const char *s);

The strlen function computes the length of the string pointed to by s.

The strlen function returns the number of characters that precede the terminating null character.

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.313) 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.314)

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)

The header <threads.h> includes the header <time.h>, defines macros, and declares types, enumeration constants, and functions that support multiple threads of execution.315)

Implementations that define the macro _ _STDC_NO_THREADS_ _ need not provide this header nor support any of its facilities.

The macros are thread_local which expands to _Thread_local;

             ONCE_FLAG_INIT

which expands to a value that can be used to initialize an object of type once_flag; and

             TSS_DTOR_ITERATIONS

which expands to an integer constant expression representing the maximum number of times that destructors will be called when a thread terminates.

The types are cnd_t which is a complete object type that holds an identifier for a condition variable; thrd_t which is a complete object type that holds an identifier for a thread; tss_t which is a complete object type that holds an identifier for a thread-specific storage pointer; mtx_t which is a complete object type that holds an identifier for a mutex; tss_dtor_t which is the function pointer type void (*)(void*), used for a destructor for a thread-specific storage pointer; thrd_start_t which is the function pointer type int (*)(void*) that is passed to thrd_create to create a new thread; and once_flag which is a complete object type that holds a flag for use by call_once.

The enumeration constants are mtx_plain which is passed to mtx_init to create a mutex object that supports neither timeout nor test and return; mtx_recursive which is passed to mtx_init to create a mutex object that supports recursive locking; mtx_timed which is passed to mtx_init to create a mutex object that supports timeout; thrd_timedout which is returned by a timed wait function to indicate that the time specified in the call was reached without acquiring the requested resource; thrd_success which is returned by a function to indicate that the requested operation succeeded; thrd_busy which is returned by a function to indicate that the requested operation failed because a resource requested by a test and return function is already in use; thrd_error which is returned by a function to indicate that the requested operation failed; and thrd_nomem which is returned by a function to indicate that the requested operation failed because it was unable to allocate memory. Forward references: date and time ( 7.27 Date and time <time.h> ).

    #include <threads.h>
           void call_once(once_flag *flag, void (*func)(void));

The call_once function uses the once_flag pointed to by flag to ensure that func is called exactly once, the first time the call_once function is called with that value of flag. Completion of an effective call to the call_once function synchronizes with all subsequent calls to the call_once function with the same value of flag.

The call_once function returns no value.

    #include <threads.h>
           int cnd_broadcast(cnd_t *cond);

The cnd_broadcast function unblocks all of the threads that are blocked on the condition variable pointed to by cond at the time of the call. If no threads are blocked on the condition variable pointed to by cond at the time of the call, the function does nothing.

The cnd_broadcast function returns thrd_success on success, or thrd_error if the request could not be honored.

    #include <threads.h>
           void cnd_destroy(cnd_t *cond);

The cnd_destroy function releases all resources used by the condition variable pointed to by cond. The cnd_destroy function requires that no threads be blocked waiting for the condition variable pointed to by cond.

The cnd_destroy function returns no value.

    #include <threads.h>
            int cnd_init(cnd_t *cond);

The cnd_init function creates a condition variable. If it succeeds it sets the variable pointed to by cond to a value that uniquely identifies the newly created condition variable. A thread that calls cnd_wait on a newly created condition variable will block.

The cnd_init function returns thrd_success on success, or thrd_nomem if no memory could be allocated for the newly created condition, or thrd_error if the request could not be honored.

    #include <threads.h>
            int cnd_signal(cnd_t *cond);

The cnd_signal function unblocks one of the threads that are blocked on the condition variable pointed to by cond at the time of the call. If no threads are blocked on the condition variable at the time of the call, the function does nothing and return success.

The cnd_signal function returns thrd_success on success or thrd_error if the request could not be honored.

    #include <threads.h>
            int cnd_timedwait(cnd_t *restrict cond,
                 mtx_t *restrict mtx,
                 const struct timespec *restrict ts);

The cnd_timedwait function atomically unlocks the mutex pointed to by mtx and endeavors to block until the condition variable pointed to by cond is signaled by a call to cnd_signal or to cnd_broadcast, or until after the TIME_UTC-based calendar time pointed to by ts. When the calling thread becomes unblocked it locks the variable pointed to by mtx before it returns. The cnd_timedwait function requires that the mutex pointed to by mtx be locked by the calling thread.

The cnd_timedwait function returns thrd_success upon success, or thrd_timedout if the time specified in the call was reached without acquiring the requested resource, or thrd_error if the request could not be honored.

    #include <threads.h>
           int cnd_wait(cnd_t *cond, mtx_t *mtx);

The cnd_wait function atomically unlocks the mutex pointed to by mtx and endeavors to block until the condition variable pointed to by cond is signaled by a call to cnd_signal or to cnd_broadcast. When the calling thread becomes unblocked it locks the mutex pointed to by mtx before it returns. The cnd_wait function requires that the mutex pointed to by mtx be locked by the calling thread.

The cnd_wait function returns thrd_success on success or thrd_error if the request could not be honored.

    #include <threads.h>
           void mtx_destroy(mtx_t *mtx);

The mtx_destroy function releases any resources used by the mutex pointed to by mtx. No threads can be blocked waiting for the mutex pointed to by mtx.

The mtx_destroy function returns no value.

    #include <threads.h>
            int mtx_init(mtx_t *mtx, int type);

The mtx_init function creates a mutex object with properties indicated by type, which must have one of the six values: mtx_plain for a simple non-recursive mutex,

    mtx_timed for a non-recursive mutex that supports timeout,                      ∗

mtx_plain | mtx_recursive for a simple recursive mutex, or mtx_timed | mtx_recursive for a recursive mutex that supports timeout.

If the mtx_init function succeeds, it sets the mutex pointed to by mtx to a value that uniquely identifies the newly created mutex.

The mtx_init function returns thrd_success on success, or thrd_error if the request could not be honored.

    #include <threads.h>
            int mtx_lock(mtx_t *mtx);

The mtx_lock function blocks until it locks the mutex pointed to by mtx. If the mutex is non-recursive, it shall not be locked by the calling thread. Prior calls to mtx_unlock on the same mutex shall synchronize with this operation.

The mtx_lock function returns thrd_success on success, or thrd_error if the ∗ request could not be honored.

    #include <threads.h>
            int mtx_timedlock(mtx_t *restrict mtx,
                 const struct timespec *restrict ts);

The mtx_timedlock function endeavors to block until it locks the mutex pointed to by mtx or until after the TIME_UTC-based calendar time pointed to by ts. The specified mutex shall support timeout. If the operation succeeds, prior calls to mtx_unlock on the same mutex shall synchronize with this operation.

The mtx_timedlock function returns thrd_success on success, or thrd_timedout if the time specified was reached without acquiring the requested resource, or thrd_error if the request could not be honored.

    #include <threads.h>
           int mtx_trylock(mtx_t *mtx);

The mtx_trylock function endeavors to lock the mutex pointed to by mtx. If the ∗ mutex is already locked, the function returns without blocking. If the operation succeeds, prior calls to mtx_unlock on the same mutex shall synchronize with this operation.

The mtx_trylock function returns thrd_success on success, or thrd_busy if the resource requested is already in use, or thrd_error if the request could not be honored.

    #include <threads.h>
           int mtx_unlock(mtx_t *mtx);

The mtx_unlock function unlocks the mutex pointed to by mtx. The mutex pointed to by mtx shall be locked by the calling thread.

The mtx_unlock function returns thrd_success on success or thrd_error if the request could not be honored.

    #include <threads.h>
            int thrd_create(thrd_t *thr, thrd_start_t func,
                 void *arg);

The thrd_create function creates a new thread executing func(arg). If the thrd_create function succeeds, it sets the object pointed to by thr to the identifier of the newly created thread. (A thread’s identifier may be reused for a different thread once the original thread has exited and either been detached or joined to another thread.) The completion of the thrd_create function synchronizes with the beginning of the execution of the new thread.

The thrd_create function returns thrd_success on success, or thrd_nomem if no memory could be allocated for the thread requested, or thrd_error if the request could not be honored.

    #include <threads.h>
            thrd_t thrd_current(void);

The thrd_current function identifies the thread that called it.

The thrd_current function returns the identifier of the thread that called it.

    #include <threads.h>
            int thrd_detach(thrd_t thr);

The thrd_detach function tells the operating system to dispose of any resources allocated to the thread identified by thr when that thread terminates. The thread identified by thr shall not have been previously detached or joined with another thread.

The thrd_detach function returns thrd_success on success or thrd_error if the request could not be honored.

    #include <threads.h>
           int thrd_equal(thrd_t thr0, thrd_t thr[[FOOTNOTE:1]];

The thrd_equal function will determine whether the thread identified by thr0 refers to the thread identified by thr1.

The thrd_equal function returns zero if the thread thr0 and the thread thr1 refer to different threads. Otherwise the thrd_equal function returns a nonzero value.

    #include <threads.h>
           _Noreturn void thrd_exit(int res);

The thrd_exit function terminates execution of the calling thread and sets its result code to res.

The program shall terminate normally after the last thread has been terminated. The behavior shall be as if the program called the exit function with the status EXIT_SUCCESS at thread termination time.

The thrd_exit function returns no value.

    #include <threads.h>
           int thrd_join(thrd_t thr, int *res);

The thrd_join function joins the thread identified by thr with the current thread by blocking until the other thread has terminated. If the parameter res is not a null pointer, it stores the thread’s result code in the integer pointed to by res. The termination of the other thread synchronizes with the completion of the thrd_join function. The thread identified by thr shall not have been previously detached or joined with another thread.

The thrd_join function returns thrd_success on success or thrd_error if the request could not be honored.

    #include <threads.h>
            int thrd_sleep(const struct timespec *duration,
                 struct timespec *remaining);

The thrd_sleep function suspends execution of the calling thread until either the interval specified by duration has elapsed or a signal which is not being ignored is received. If interrupted by a signal and the remaining argument is not null, the amount of time remaining (the requested interval minus the time actually slept) is stored in the interval it points to. The duration and remaining arguments may point to the same object.

The suspension time may be longer than requested because the interval is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than that specified, as measured by the system clock TIME_UTC.

The thrd_sleep function returns zero if the requested time has elapsed, -1 if it has been interrupted by a signal, or a negative value if it fails.

    #include <threads.h>
            void thrd_yield(void);

The thrd_yield function endeavors to permit other threads to run, even if the current thread would ordinarily continue to run.

The thrd_yield function returns no value.

    #include <threads.h>
           int tss_create(tss_t *key, tss_dtor_t dtor);

The tss_create function creates a thread-specific storage pointer with destructor dtor, which may be null.

If the tss_create function is successful, it sets the thread-specific storage pointed to by key to a value that uniquely identifies the newly created pointer and returns thrd_success; otherwise, thrd_error is returned and the thread-specific storage pointed to by key is set to an undefined value.

    #include <threads.h>
           void tss_delete(tss_t key);

The tss_delete function releases any resources used by the thread-specific storage identified by key.

The tss_delete function returns no value.

    #include <threads.h>
           void *tss_get(tss_t key);

The tss_get function returns the value for the current thread held in the thread-specific storage identified by key.

The tss_get function returns the value for the current thread if successful, or zero if unsuccessful.

    #include <threads.h>
            int tss_set(tss_t key, void *val);

The tss_set function sets the value for the current thread held in the thread-specific storage identified by key to val.

The tss_set function returns thrd_success on success or thrd_error if the

    request could not be honored.                                             ∗

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.19 Common definitions <stddef.h> ); ∗

            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; and

            TIME_UTC

which expands to an integer constant greater than 0 that designates the UTC time base.316)

The types declared are size_t (described in 7.19 Common definitions <stddef.h> ); clock_t and time_t which are real types capable of representing times;

            struct timespec

which holds an interval specified in seconds and nanoseconds (which may represent a calendar time based on a particular epoch); 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 timespec structure shall contain at least the following members, in any order.317) time_t tv_sec; // whole seconds — ≥ 0

            long   tv_nsec; // nanoseconds — [0, 999999999]

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.318)

            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.

    #include <time.h>
            clock_t clock(void);

The clock function determines the processor time used.

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).319)

    #include <time.h>
            double difftime(time_t time1, time_t time0);

The difftime function computes the difference between two calendar times: time1 - time0.

The difftime function returns the difference expressed in seconds as a double.

    #include <time.h>
            time_t mktime(struct tm *timeptr);

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.320) 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.

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]);

    #include <time.h>
            time_t time(time_t *timer);

The time function determines the current calendar time. The encoding of the value is unspecified.

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.

    #include <time.h>
            int timespec_get(struct timespec *ts, int base);

The timespec_get function sets the interval pointed to by ts to hold the current calendar time based on the specified time base.

If base is TIME_UTC, the tv_sec member is set to the number of seconds since an implementation defined epoch, truncated to a whole value and the tv_nsec member is set to the integral number of nanoseconds, rounded to the resolution of the system clock.321)

If the timespec_get function is successful it returns the nonzero value base; otherwise, it returns zero.

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 and the functions are not required to avoid data races with each other.322) The implementation shall behave as if no other library functions call these functions.

    #include <time.h>
             char *asctime(const struct tm *timeptr);

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;

}

If any of the members of the broken-down time contain values that are outside their normal ranges, [323] the behavior of the asctime function is undefined. Likewise, if the calculated year exceeds four digits or is less than the year 1000, the behavior is undefined.

The asctime function returns a pointer to the string.

    #include <time.h>
            char *ctime(const time_t *timer);

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))

The ctime function returns the pointer returned by the asctime function with that broken-down time as argument. Forward references: the localtime function ( 7.27.3.4 The localtime function ).

    #include <time.h>
            struct tm *gmtime(const time_t *timer);

The gmtime function converts the calendar time pointed to by timer into a broken-down time, expressed as UTC.

The gmtime function returns a pointer to the broken-down time, or a null pointer if the specified time cannot be converted to UTC.

    #include <time.h>
           struct tm *localtime(const time_t *timer);

The localtime function converts the calendar time pointed to by timer into a broken-down time, expressed as local time.

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.

    #include <time.h>
           size_t strftime(char * restrict s,
                size_t maxsize,
                const char * restrict format,
                const struct tm * restrict timeptr);

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.27.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 (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.27.1]
    %X    is replaced by the locale’s appropriate time representation. [all specified in 7.27.1]
    %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 %.

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. %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.

%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.

If a conversion specifier is not one of the above, the behavior is undefined.

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.

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.

The header <uchar.h> declares types and functions for manipulating Unicode characters.

The types declared are mbstate_t (described in 7.30.1) and size_t (described in
    7.19);
           char16_t
    which is an unsigned integer type used for 16-bit characters and is the same type as
    uint_least16_t (described in 7.20.1.2); and
           char32_t
    which is an unsigned integer type used for 32-bit characters and is the same type as
    uint_least32_t (also described in 7.20.1.2).

These functions have a 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, which the functions alter as necessary. 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 functions are not required to avoid data races with other calls to the same function in this case. The implementation behaves as if no library function calls these functions with a null pointer for ps.

    #include <uchar.h>
           size_t mbrtoc16(char16_t * restrict pc16,
                const char * restrict s, size_t n,
                mbstate_t * restrict ps);

If s is a null pointer, the mbrtoc16 function is equivalent to the call:

                   mbrtoc16(NULL, "", 1, ps)

In this case, the values of the parameters pc16 and n are ignored.

If s is not a null pointer, the mbrtoc16 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 values of the corresponding wide characters and then, if pc16 is not a null pointer, stores the value of the first (or only) such character in the object pointed to by pc16. Subsequent calls will store successive wide characters without consuming any additional input until all the characters have been stored. If the corresponding wide character is the null wide character, the resulting state described is the initial conversion state.

The mbrtoc16 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)(-3) if the next character resulting from a previous call has been stored (no bytes from the input have been consumed by this call). (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).324) (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.

    #include <uchar.h>
            size_t c16rtomb(char * restrict s, char16_t c16,
                 mbstate_t * restrict ps);

If s is a null pointer, the c16rtomb function is equivalent to the call

                    c16rtomb(buf, L'\0', ps)

where buf is an internal buffer.

If s is not a null pointer, the c16rtomb function determines the number of bytes needed to represent the multibyte character that corresponds to the wide character given by c16 (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 c16 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.

The c16rtomb function returns the number of bytes stored in the array object (including any shift sequences). When c16 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.

    #include <uchar.h>
            size_t mbrtoc32(char32_t * restrict pc32,
                 const char * restrict s, size_t n,
                 mbstate_t * restrict ps);

If s is a null pointer, the mbrtoc32 function is equivalent to the call:

                    mbrtoc32(NULL, "", 1, ps)

In this case, the values of the parameters pc32 and n are ignored.

If s is not a null pointer, the mbrtoc32 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 values of the corresponding wide characters and then, if pc32 is not a null pointer, stores the value of the first (or only) such character in the object pointed to by pc32. Subsequent calls will store successive wide characters without consuming any additional input until all the characters have been stored. If the corresponding wide character is the null wide character, the resulting state described is the initial conversion state.

The mbrtoc32 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)(-3) if the next character resulting from a previous call has been stored (no bytes from the input have been consumed by this call). (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).325) (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.

    #include <uchar.h>
            size_t c32rtomb(char * restrict s, char32_t c32,
                 mbstate_t * restrict ps);

If s is a null pointer, the c32rtomb function is equivalent to the call

                    c32rtomb(buf, L'\0', ps)

where buf is an internal buffer.

If s is not a null pointer, the c32rtomb function determines the number of bytes needed to represent the multibyte character that corresponds to the wide character given by c32 (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 c32 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.

The c32rtomb function returns the number of bytes stored in the array object (including any shift sequences). When c32 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.

The header <wchar.h> defines four macros, and declares four data types, one tag, and many functions.326)

The types declared are wchar_t and size_t (both described in 7.19 Common definitions <stddef.h> ); mbstate_t which is a complete 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); [327] and

             struct tm

which is declared as an incomplete structure type (the contents are described in 7.27.1 Components of time ).

The macros defined are NULL (described in 7.19 Common definitions <stddef.h> ); WCHAR_MIN and WCHAR_MAX (described in 7.20.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.328) 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.

Arguments to the functions in this subclause may point to arrays containing wchar_t values that do not correspond to members of the extended character set. Such values shall be processed according to the specified semantics, except that it is unspecified whether an encoding error occurs if such a value appears in the format string for a function in 7.29.2 Formatted wide character input/output functions or 7.29.5 Wide character time conversion functions and the specified semantics do not require that value to be processed by wcrtomb.

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.

The formatted wide character input/output functions shall behave as if there is a sequence point after the actions associated with each specifier.329)

    #include <stdio.h>
            #include <wchar.h>
            int fwprintf(FILE * restrict stream,
                 const wchar_t * restrict format, ...);

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.330)
  • 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.)331)
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:

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.
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.
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.
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.
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.
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.
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.
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.332) 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 [333] 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 [334] 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.335) 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.336) 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.

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.29.6.1.1 The btowc function ), the mbrtowc function ( 7.29.6.3.2 The mbrtowc function ).

    #include <stdio.h>
             #include <wchar.h>
             int fwscanf(FILE * restrict stream,
                  const wchar_t * restrict format, ...);

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. When all directives have been executed, or 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. The directive never fails.

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.337)

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.338) 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:

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.
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.
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.
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.
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.
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.
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.
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:

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.
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.
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.
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.
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.
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.
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.
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.
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.
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.339)

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.

The fwscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. 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.29.4.1.1 The wcstod, wcstof, and wcstold functions ), the wcstol, wcstoll, wcstoul, and wcstoull functions ( 7.29.4.1.2 The wcstol, wcstoll, wcstoul, and wcstoull functions ), the wcrtomb function ( 7.29.6.3.3 The wcrtomb function ).

    #include <wchar.h>
              int swprintf(wchar_t * restrict s,
                   size_t n,
                   const wchar_t * restrict format, ...);

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).

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.

    #include <wchar.h>
            int swscanf(const wchar_t * restrict s,
                 const wchar_t * restrict format, ...);

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.

The swscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. 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.

    #include <stdarg.h>
            #include <stdio.h>
            #include <wchar.h>
            int vfwprintf(FILE * restrict stream,
                 const wchar_t * restrict format,
                 va_list arg);

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.340)

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);
           }

    #include <stdarg.h>
           #include <stdio.h>
           #include <wchar.h>
           int vfwscanf(FILE * restrict stream,
                const wchar_t * restrict format,
                va_list arg);

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.340)

The vfwscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. 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.

    #include <stdarg.h>
            #include <wchar.h>
            int vswprintf(wchar_t * restrict s,
                 size_t n,
                 const wchar_t * restrict format,
                 va_list arg);

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.340)

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.

    #include <stdarg.h>
            #include <wchar.h>
            int vswscanf(const wchar_t * restrict s,
                 const wchar_t * restrict format,
                 va_list arg);

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.340)

The vswscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. 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.

    #include <stdarg.h>
           #include <wchar.h>
           int vwprintf(const wchar_t * restrict format,
                va_list arg);

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.340)

The vwprintf function returns the number of wide characters transmitted, or a negative value if an output or encoding error occurred.

    #include <stdarg.h>
           #include <wchar.h>
           int vwscanf(const wchar_t * restrict format,
                va_list arg);

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.340)

The vwscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. 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.

    #include <wchar.h>
            int wprintf(const wchar_t * restrict format, ...);

The wprintf function is equivalent to fwprintf with the argument stdout interposed before the arguments to wprintf.

The wprintf function returns the number of wide characters transmitted, or a negative value if an output or encoding error occurred.

    #include <wchar.h>
            int wscanf(const wchar_t * restrict format, ...);

The wscanf function is equivalent to fwscanf with the argument stdin interposed before the arguments to wscanf.

The wscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. 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.

    #include <stdio.h>
            #include <wchar.h>
            wint_t fgetwc(FILE *stream);

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).

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.341)

    #include <stdio.h>
            #include <wchar.h>
            wchar_t *fgetws(wchar_t * restrict s,
                 int n, FILE * restrict stream);

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.

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.

    #include <stdio.h>
            #include <wchar.h>
            wint_t fputwc(wchar_t c, FILE *stream);

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.

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.

    #include <stdio.h>
            #include <wchar.h>
            int fputws(const wchar_t * restrict s,
                 FILE * restrict stream);

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.

The fputws function returns EOF if a write or encoding error occurs; otherwise, it returns a nonnegative value.

    #include <stdio.h>
            #include <wchar.h>
            int fwide(FILE *stream, int mode);

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.342) Otherwise, mode is zero and the function does not alter the orientation of the stream.

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.

    #include <stdio.h>
           #include <wchar.h>
           wint_t getwc(FILE *stream);

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.

The getwc function returns the next wide character from the input stream pointed to by stream, or WEOF.

    #include <wchar.h>
           wint_t getwchar(void);

The getwchar function is equivalent to getwc with the argument stdin.

The getwchar function returns the next wide character from the input stream pointed to by stdin, or WEOF.

    #include <stdio.h>
           #include <wchar.h>
           wint_t putwc(wchar_t c, FILE *stream);

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.

The putwc function returns the wide character written, or WEOF.

    #include <wchar.h>
            wint_t putwchar(wchar_t c);

The putwchar function is equivalent to putwc with the second argument stdout.

The putwchar function returns the character written, or WEOF.

    #include <stdio.h>
            #include <wchar.h>
            wint_t ungetwc(wint_t c, FILE *stream);

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.

The ungetwc function returns the wide character pushed back, or WEOF if the operation fails.

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.

    #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);

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.343) 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 sequence is implementation-defined.344) 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.345)

The functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value overflows and default rounding is in effect ( 7.12.1 Treatment of error conditions ), 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.

    #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);

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.

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.

    #include <wchar.h>
           wchar_t *wcscpy(wchar_t * restrict s1,
                const wchar_t * restrict s2);

The wcscpy function copies the wide string pointed to by s2 (including the terminating null wide character) into the array pointed to by s1.

The wcscpy function returns the value of s1.

    #include <wchar.h>
             wchar_t *wcsncpy(wchar_t * restrict s1,
                  const wchar_t * restrict s2,
                  size_t n);

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.346 )

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.

The wcsncpy function returns the value of s1.

    #include <wchar.h>
             wchar_t *wmemcpy(wchar_t * restrict s1,
                  const wchar_t * restrict s2,
                  size_t n);

The wmemcpy function copies n wide characters from the object pointed to by s2 to the object pointed to by s1.

The wmemcpy function returns the value of s1.

    #include <wchar.h>
           wchar_t *wmemmove(wchar_t *s1, const wchar_t *s2,
                size_t n);

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.

The wmemmove function returns the value of s1.

    #include <wchar.h>
           wchar_t *wcscat(wchar_t * restrict s1,
                const wchar_t * restrict s2);

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.

The wcscat function returns the value of s1.

    #include <wchar.h>
           wchar_t *wcsncat(wchar_t * restrict s1,
                const wchar_t * restrict s2,
                size_t n);

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.347)

The wcsncat function returns the value of s1.

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.

    #include <wchar.h>
            int wcscmp(const wchar_t *s1, const wchar_t *s2);

The wcscmp function compares the wide string pointed to by s1 to the wide string pointed to by s2.

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.

    #include <wchar.h>
            int wcscoll(const wchar_t *s1, const wchar_t *s2);

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.

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.

    #include <wchar.h>
           int wcsncmp(const wchar_t *s1, const wchar_t *s2,
                size_t n);

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.

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.

    #include <wchar.h>
           size_t wcsxfrm(wchar_t * restrict s1,
                const wchar_t * restrict s2,
                size_t n);

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.

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.

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)

    #include <wchar.h>
            int wmemcmp(const wchar_t *s1, const wchar_t *s2,
                 size_t n);

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.

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.

    #include <wchar.h>
            wchar_t *wcschr(const wchar_t *s, wchar_t c);

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.

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.

    #include <wchar.h>
            size_t wcscspn(const wchar_t *s1, const wchar_t *s2);

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.

The wcscspn function returns the length of the segment.

    #include <wchar.h>
           wchar_t *wcspbrk(const wchar_t *s1, const wchar_t *s2);

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.

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.

    #include <wchar.h>
           wchar_t *wcsrchr(const wchar_t *s, wchar_t c);

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.

The wcsrchr function returns a pointer to the wide character, or a null pointer if c does not occur in the wide string.

    #include <wchar.h>
           size_t wcsspn(const wchar_t *s1, const wchar_t *s2);

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.

The wcsspn function returns the length of the segment.

    #include <wchar.h>
            wchar_t *wcsstr(const wchar_t *s1, const wchar_t *s2);

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.

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.

    #include <wchar.h>
            wchar_t *wcstok(wchar_t * restrict s1,
                 const wchar_t * restrict s2,
                 wchar_t ** restrict ptr);

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).

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

    #include <wchar.h>
           wchar_t *wmemchr(const wchar_t *s, wchar_t c,
                size_t n);

The wmemchr function locates the first occurrence of c in the initial n wide characters of the object pointed to by s.

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.

    #include <wchar.h>
            size_t wcslen(const wchar_t *s);

The wcslen function computes the length of the wide string pointed to by s.

The wcslen function returns the number of wide characters that precede the terminating null wide character.

    #include <wchar.h>
            wchar_t *wmemset(wchar_t *s, wchar_t c, size_t n);

The wmemset function copies the value of c into each of the first n wide characters of the object pointed to by s.

The wmemset function returns the value of s.

    #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);

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.

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.

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.29.6.3 Restartable multibyte/wide character conversion functions and 7.29.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.348)

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 referenced object is altered as needed to track the shift state, and the position within a multibyte character, for the associated multibyte character sequence.

    #include <wchar.h>
            wint_t btowc(int c);

The btowc function determines whether c constitutes a valid single-byte character in the initial shift state.

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.

    #include <wchar.h>
            int wctob(wint_t c);

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.

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.

    #include <wchar.h>
            int mbsinit(const mbstate_t *ps);

If ps is not a null pointer, the mbsinit function determines whether the referenced mbstate_t object describes an initial conversion state.

The mbsinit function returns nonzero if ps is a null pointer or if the referenced object describes an initial conversion state; otherwise, it returns zero.

These functions differ from the corresponding multibyte character functions of 7.22.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 functions are not required to avoid data races with other calls to the same function in this case. 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.

    #include <wchar.h>
           size_t mbrlen(const char * restrict s,
                size_t n,
                mbstate_t * restrict ps);

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.

The mbrlen function returns a value between zero and n, inclusive, (size_t)(-2), or (size_t)(-1). Forward references: the mbrtowc function ( 7.29.6.3.2 The mbrtowc function ).

    #include <wchar.h>
            size_t mbrtowc(wchar_t * restrict pwc,
                 const char * restrict s,
                 size_t n,
                 mbstate_t * restrict ps);

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.

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).349) (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.

    #include <wchar.h>
            size_t wcrtomb(char * restrict s,
                 wchar_t wc,
                 mbstate_t * restrict ps);

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.

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.

These functions differ from the corresponding multibyte string functions of 7.22.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 functions are not required to avoid data races with other calls to the same function in this case. 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.

    #include <wchar.h>
             size_t mbsrtowcs(wchar_t * restrict dst,
                  const char ** restrict src,
                  size_t len,
                  mbstate_t * restrict ps);

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.350) 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.

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).

    #include <wchar.h>
            size_t wcsrtombs(char * restrict dst,
                 const wchar_t ** restrict src,
                 size_t len,
                 mbstate_t * restrict ps);

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.351)

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.

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).

The header <wctype.h> defines one macro, and declares three data types and many functions.352)

The types declared are wint_t described in 7.29.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.29.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.

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.

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.353) Forward references: the wctob function ( 7.29.6.1.2 The wctob function ).

    #include <wctype.h>
            int iswalnum(wint_t wc);

The iswalnum function tests for any wide character for which iswalpha or iswdigit is true.

    #include <wctype.h>
            int iswalpha(wint_t wc);

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.354)

    #include <wctype.h>
            int iswblank(wint_t wc);

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.

    #include <wctype.h>
            int iswcntrl(wint_t wc);

The iswcntrl function tests for any control wide character.

    #include <wctype.h>
            int iswdigit(wint_t wc);

The iswdigit function tests for any wide character that corresponds to a decimal-digit character (as defined in 5.2.1 ).

    #include <wctype.h>
            int iswgraph(wint_t wc);

The iswgraph function tests for any wide character for which iswprint is true and iswspace is false.355)

    #include <wctype.h>
            int iswlower(wint_t wc);

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.

    #include <wctype.h>
            int iswprint(wint_t wc);

The iswprint function tests for any printing wide character.

    #include <wctype.h>
            int iswpunct(wint_t wc);

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.355)

    #include <wctype.h>
            int iswspace(wint_t wc);

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.

    #include <wctype.h>
            int iswupper(wint_t wc);

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.

    #include <wctype.h>
            int iswxdigit(wint_t wc);

The iswxdigit function tests for any wide character that corresponds to a hexadecimal-digit character (as defined in 6.4.4.1 ).

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.30.2.1 Wide character classification functions ).

    #include <wctype.h>
            int iswctype(wint_t wc, wctype_t desc);

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.30.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)

The iswctype function returns nonzero (true) if and only if the value of the wide character wc has the property described by desc. If desc is zero, the iswctype function returns zero (false). Forward references: the wctype function ( 7.30.2.2.2 The wctype function ).

    #include <wctype.h>
           wctype_t wctype(const char *property);

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.

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.

The header <wctype.h> declares several functions useful for mapping wide characters.

    #include <wctype.h>
            wint_t towlower(wint_t wc);

The towlower function converts an uppercase letter to a corresponding lowercase letter.

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.

    #include <wctype.h>
            wint_t towupper(wint_t wc);

The towupper function converts a lowercase letter to a corresponding uppercase letter.

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.

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.30.3.1 Wide character case mapping functions ).

    #include <wctype.h>
           wint_t towctrans(wint_t wc, wctrans_t desc);

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.30.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)

The towctrans function returns the mapped value of wc using the mapping described by desc. If desc is zero, the towctrans function returns the value of wc.

    #include <wctype.h>
           wctrans_t wctrans(const char *property);

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.

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.

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.

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.

Function names that begin with either is or to, and a lowercase letter may be added to the declarations in the <ctype.h> header.

Macros that begin with E and a digit or E and an uppercase letter may be added to the macros defined in the <errno.h> header.

Macros that begin with FE_ and an uppercase letter may be added to the macros defined in the <fenv.h> header.

Macros that begin with either PRI or SCN, and either a lowercase letter or X may be added to the macros defined in the <inttypes.h> header.

Macros that begin with LC_ and an uppercase letter may be added to the macros defined in the <locale.h> header.

Macros that begin with either SIG and an uppercase letter or SIG_ and an uppercase letter may be added to the macros defined in the <signal.h> header.

Macros that begin with ATOMIC_ and an uppercase letter may be added to the macros defined in the <stdatomic.h> header. Typedef names that begin with either atomic_ or memory_, and a lowercase letter may be added to the declarations in the <stdatomic.h> header. Enumeration constants that begin with memory_order_ and a lowercase letter may be added to the definition of the memory_order type in the <stdatomic.h> header. Function names that begin with atomic_ and a lowercase letter may be added to the declarations in the <stdatomic.h> header.

The ability to undefine and perhaps then redefine the macros bool, true, and false is an obsolescent feature.

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.

Lowercase letters may be added to the conversion specifiers and length modifiers in fprintf and fscanf. Other characters may be used in extensions.

The use of ungetc on a binary stream where the file position indicator is zero prior to the call is an obsolescent feature.

Function names that begin with str and a lowercase letter may be added to the declarations in the <stdlib.h> header.

Function names that begin with str, mem, or wcs and a lowercase letter may be added to the declarations in the <string.h> header.

Macros beginning with TIME_ and an uppercase letter may be added to the macros in the <time.h> header.

Function names, type names, and enumeration constants that begin with either cnd_, mtx_, thrd_, or tss_, and a lowercase letter may be added to the declarations in the <threads.h> header.

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.

<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.

The functions that make use of the decimal-point character are the numeric conversion functions ( 7.22.1 Numeric conversion functions , 7.29.4.1 Wide string numeric conversion functions ) and the formatted input/output functions ( 7.21.6 Formatted input/output functions , 7.29.2 Formatted wide character input/output functions ).
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.
A header is not necessarily a source file, nor are the < and > delimited sequences in header names necessarily valid source file names.
The headers <complex.h>, <stdatomic.h>, and <threads.h> are conditional features that implementations need not support; see 6.10.8.3.
The list of reserved identifiers with external linkage includes math_errhandling, setjmp, va_copy, and va_end.
This means that an implementation shall provide an actual function for each library function, even if it also provides a macro for that function.
Such macros might not contain the sequence points that the corresponding function calls do.
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.
Thus, a signal handler cannot, in general, call standard library functions.
This means, for example, that an implementation is not permitted to use a static object for internal purposes without synchronization because it could cause a data race even in programs that do not explicitly share objects between threads. Similarly, an implementation of memcpy is not permitted to copy bytes beyond the specified length of the destination object and then restore the original values because it could cause a data race if the program shared those bytes between threads.
This allows implementations to parallelize operations if there are no visible side effects.
The message written might be of the form: Assertion failed: expression, function abc, file xyz, line nnn.
See ‘‘future library directions’’ ( 7.31.1 Complex arithmetic <complex.h> ).
The imaginary unit is a number i such that i 2 = −1.
A specification for imaginary types is in informative annex G.
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.
For a variable z of complex type, z == creal(z) + cimag(z)*I.
For a variable z of complex type, z == creal(z) + cimag(z)*I.
See ‘‘future library directions’’ ( 7.31.2 Character handling <ctype.h> ).
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).
The functions islower and isupper test true or false separately for each of these additional characters; all four combinations are possible.
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()).
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.
See ‘‘future library directions’’ ( 7.31.3 Errors <errno.h> ).
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. It is also designed to facilitate code portability among all systems.
A floating-point status flag is not an object and can be set more than once within an expression.
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.
The implementation supports a floating-point 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.
See ‘‘future library directions’’ ( 7.31.4 Floating-point environment <fenv.h> ).
The macros should be distinct powers of two.
See ‘‘future library directions’’ ( 7.31.4 Floating-point environment <fenv.h> ).
Even though the rounding direction macros may expand to constants corresponding to the values of FLT_ROUNDS, they are not required to do so.
See ‘‘future library directions’’ ( 7.31.4 Floating-point environment <fenv.h> ).
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.
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.
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.
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.8.6 is in the same spirit.
This mechanism allows testing several floating-point exceptions with just one function call.
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.
See ‘‘future library directions’’ ( 7.31.5 Format conversion of integer types <inttypes.h> ).
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.
The absolute value of the most negative number cannot be represented in two’s complement.
ISO/IEC 9945−2 specifies locale and charmap formats that may be used to specify locales for C.
See ‘‘future library directions’’ ( 7.31.6 Localization <locale.h> ).
The only functions in 7.4 Character handling <ctype.h> whose behavior is not affected by the current locale are isdigit and isxdigit.
The implementation shall arrange to encode in a string the various categories due to a heterogeneous locale when category has the value LC_ALL.
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.
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.
HUGE_VAL, HUGE_VALF, and HUGE_VALL can be positive infinities in an implementation that supports infinities.
In this case, using INFINITY will violate the constraint in 6.4.4 and thus require a diagnostic.
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.
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.
The term underflow here is intended to encompass both ‘‘gradual underflow’’ as in IEC 60559 and also ‘‘flush-to-zero’’ underflow.
Math errors are being indicated by the floating-point exception flags rather than by errno.
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.
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.
The signbit macro reports the sign of all values, including infinities, zeros, and NaNs. If zero is unsigned, it is treated as positive.
For small magnitude x, expm1(x) is expected to be more accurate than exp(x) - 1.
For small magnitude x, log1p(x) is expected to be more accurate than log(1 + x).
‘‘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. If r = 0, its sign shall be that of x.’’ This definition is applicable for all implementations.
The argument values are converted to the type of the function, even by a macro implementation of the function.
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.
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.10.9.2.
The fmin functions are analogous to the fmax functions in their treatment of NaNs.
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.
If any argument is of integer type, or any other type that is not a real floating type, the behavior is undefined.
Whether an argument represented in a format wider than its semantic type is converted to the semantic type is unspecified.
These functions are useful for dealing with unusual conditions encountered in a low-level function of a program.
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.
This includes, but is not limited to, the floating-point status flags and the state of open files.
See ‘‘future library directions’’ ( 7.31.7 Signal handling <signal.h> ). The names of the signal numbers reflect the following terms (respectively): abort, floating-point exception, illegal instruction, interrupt, segmentation violation, and termination.
This includes functions called indirectly via standard library functions (e.g., a SIGABRT handler called via the abort function).
If any signal is generated by an asynchronous signal handler, the behavior is undefined.
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.
See ‘‘future library directions’’ ( 7.31.8 Atomics <stdatomic.h> ).
See ‘‘future library directions’’ ( 7.31.8 Atomics <stdatomic.h> ).
Among other implications, atomic variables shall not decay.
See ‘‘future library directions’’ ( 7.31.8 Atomics <stdatomic.h> ).
The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.
See ‘‘future library directions’’ ( 7.31.9 Boolean type and values <stdbool.h> ).
See ‘‘future library directions’’ ( 7.31.10 Integer types <stdint.h> ).
Some of these types may denote implementation-defined extended integer types.
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.
A freestanding implementation need not provide all of these types.
The values WCHAR_MIN and WCHAR_MAX do not necessarily correspond to members of the extended character set.
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.
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.
The three predefined streams stdin, stdout, and stderr are unoriented at program startup.
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.
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.
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.
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.21.2 Streams ).
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.
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.
The fprintf functions perform writes to memory for the %n specifier.
Note that 0 is taken as a flag, not as the beginning of a field width.
The results of all floating conversions of a negative zero, and of negative values that round to zero, include a minus sign.
When applied to infinite and NaN values, the -, +, and space flag characters have their usual meaning; the # and 0 flag characters have no effect.
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.
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.
No special provisions are made for multibyte characters.
Redundant shift sequences may result if multibyte characters have a state-dependent encoding.
See ‘‘future library directions’’ ( 7.31.11 Input/output <stdio.h> ).
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.
These white-space characters are not counted against a specified field width.
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.
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.
See ‘‘future library directions’’ ( 7.31.11 Input/output <stdio.h> ).
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.
An end-of-file and a read error can be distinguished by use of the feof and ferror functions.
See ‘‘future library directions’’ ( 7.31.11 Input/output <stdio.h> ).
See ‘‘future library directions’’ ( 7.31.12 General utilities <stdlib.h> ).
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.
An implementation may use the n-char sequence to determine extra information to be represented in the NaN’s significand.
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.
There are no guarantees as to the quality of the random sequence produced and some implementations are known to produce sequences with distressingly non-random low-order bits. Applications with particular requirements should use a generator that is known to be sufficient for their needs.
Note that this need not be the same as the representation of floating-point zero or a null pointer constant.
The atexit function registrations are distinct from the at_quick_exit registrations, so applications may need to call both registration functions with the same argument.
The at_quick_exit function registrations are distinct from the atexit registrations, so applications may need to call both registration functions with the same argument.
Each function is called as many times as it was registered, and in the correct order with respect to other registered functions.
Many implementations provide non-standard functions that modify the environment list.
Each function is called as many times as it was registered, and in the correct order with respect to other registered functions.
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
In practice, the entire array is sorted according to the comparison function.
The absolute value of the most negative number cannot be represented in two’s complement.
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.
The array will not be null-terminated if the value returned is n.
See ‘‘future library directions’’ ( 7.31.13 String handling <string.h> ).
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.
Thus, the maximum number of characters that can end up in the array pointed to by s1 is strlen(s1)+n+1.
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.
The strtok_s function can be used instead to avoid data races.
The strerror_s function can be used instead to avoid data races.
Like other function-like macros in Standard libraries, each type-generic macro can be suppressed to make available the corresponding ordinary function.
If the type of the argument is not compatible with the type of the parameter for the selected function, the behavior is undefined.
See ‘‘future library directions’’ ( 7.31.15 Threads <threads.h> ).
Implementations may define additional time bases, but are only required to support a real time clock based on UTC.
The tv_sec member is a linear count of seconds and may not have the normal semantics of a time_t. The semantics of the members and their normal ranges are expressed in the comments.
The range [0, 60] for tm_sec allows for a positive leap second.
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.
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.
Although a struct timespec object describes times with nanosecond resolution, the available resolution is system dependent and may even be greater than 1 second.
Alternative time conversion functions that do avoid data races are specified in K.3.8.2.
See 7.27.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
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).
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).
See ‘‘future library directions’’ ( 7.31.16 Extended multibyte and wide character utilities <wchar.h> ).
wchar_t and wint_t can be the same integer type.
The value of the macro WEOF may differ from that of EOF and need not be negative.
The fwprintf functions perform writes to memory for the %n specifier.
Note that 0 is taken as a flag, not as the beginning of a field width.
The results of all floating conversions of a negative zero, and of negative values that round to zero, include a minus sign.
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.
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.
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.
See ‘‘future library directions’’ ( 7.31.16 Extended multibyte and wide character utilities <wchar.h> ).
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.
These white-space wide characters are not counted against a specified field width.
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.
See ‘‘future library directions’’ ( 7.31.16 Extended multibyte and wide character utilities <wchar.h> ).
As the functions vfwprintf, vswprintf, vfwscanf, vwprintf, vwscanf, and vswscanf invoke the va_arg macro, the value of arg after the return is indeterminate.
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.
If the orientation of the stream has already been determined, fwide does not change it.
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.
An implementation may use the n-wchar sequence to determine extra information to be represented in the NaN’s significand.
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.
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.
Thus, the maximum number of wide characters that can end up in the array pointed to by s1 is wcslen(s1)+n+1.
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.
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).
Thus, the value of len is ignored if dst is a null pointer.
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.
See ‘‘future library directions’’ ( 7.31.17 Wide character classification and mapping utilities ).
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.
The functions iswlower and iswupper test true or false separately for each of these additional wide characters; all four combinations are possible.
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 ' '.
Implementations that do not define _ _STDC_IEC_559_ _ are not required to conform to these specifications.
‘‘Extended’’ is IEC 60559’s double-extended data format. Extended refers to both the common 80-bit and quadruple 128-bit IEC 60559 formats.
A non-IEC 60559 long double type is required to provide infinity and NaNs, as its values include all double values.
Since NaNs created by IEC 60559 operations are always quiet, quiet NaNs (along with infinities) are sufficient for closure of the arithmetic.
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>.
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.)
Assignment removes any extra range and precision.
This specification does not require dynamic rounding precision nor trap enablement modes.
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.9).
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.
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 ;
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.
Strict support for signaling NaNs — not required by this specification — would invalidate these and other transformations that remove arithmetic operators.
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.
0 − 0 yields −0 instead of +0 just when the rounding direction is downward.
IEC 60559 allows different definitions of underflow. They all result in the same values, but differ on when the floating-point exception is raised.
It is intended that undeserved ‘‘underflow’’ and ‘‘inexact’’ floating-point exceptions are raised only if avoiding them would be too costly.
atan2(0, 0) does not raise the ‘‘invalid’’ floating-point exception, nor does atan2( y , 0) raise the ‘‘divide-by-zero’’ floating-point exception.
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.
Implementations that do not define _ _STDC_IEC_559_COMPLEX_ _ are not required to conform to these specifications.
See 6.3.1.2.
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’’).
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.
This allows cpow( z , c ) to be implemented as cexp(c clog( z )) without precluding implementations that treat special cases more carefully.
Implementations that do not define _ _STDC_LIB_EXT1_ _ are not required to conform to these specifications.
Future revisions of this International Standard may define meanings for other values of _ _STDC_WANT_LIB_EXT1_ _.
Subclause 7.1.3 Reserved identifiers reserves certain names and patterns of names that an implementation may use in headers. All other names are not reserved, and a conforming implementation is not permitted to use them. While some of the names defined in K.3 and its subclauses are reserved, others are not. If an unreserved name is defined in a header when _ _STDC_WANT_LIB_EXT1_ _ is defined as 0, the implementation is not conforming.
Although runtime-constraints replace many cases of undefined behavior, undefined behavior still exists in this annex. Implementations are free to detect any case of undefined behavior and treat it as a runtime-constraint violation by calling the runtime-constraint handler. This license comes directly from the definition of undefined behavior.
As a matter of programming style, errno_t may be used as the type of something that deals only with the values that might be found in errno. For example, a function which returns the value of errno might be declared as having the return type errno_t.
See the description of the RSIZE_MAX macro in <stdint.h>.
The macro RSIZE_MAX need not expand to a constant expression.
Files created using strings generated by the tmpnam_s 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. Implementations should take care in choosing the patterns used for names returned by tmpnam_s. For example, making a thread id part of the names avoids the race condition and possible conflict when multiple programs run simultaneously by the same user generate the same temporary file names.
An implementation may have tmpnam call tmpnam_s (perhaps so there is only one naming convention for temporary files), but this is not required.
These are the same permissions that the file would have been created with by fopen.
It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointed at by format when those characters are not a interpreted as a %n specifier. For example, if the entire format string was %%n.
Because an implementation may treat any undefined behavior as a runtime-constraint violation, an implementation may treat any unsupported specifiers in the string pointed to by format as a runtime-constraint violation.
Because an implementation may treat any undefined behavior as a runtime-constraint violation, an implementation may treat any unsupported specifiers in the string pointed to by format as a runtime-constraint violation.
If the format is known at translation time, an implementation may issue a diagnostic for any argument used to store the result from a c, s, or [ conversion specifier if that argument is not followed by an argument of a type compatible with rsize_t. A limited amount of checking may be done if even if the format is not known at translation time. For example, an implementation may issue a diagnostic for each argument after format that has of type pointer to one of char, signed char, unsigned char, or void that is not followed by an argument of a type compatible with rsize_t. The diagnostic could warn that unless the pointer is being used with a conversion specifier using the hh length modifier, a length argument must follow the pointer argument. Another useful diagnostic could flag any non-pointer argument following format that did not have a type compatible with rsize_t.
It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointed at by format when those characters are not a interpreted as a %n specifier. For example, if the entire format string was %%n.
It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointed at by format when those characters are not a interpreted as a %n specifier. For example, if the entire format string was %%n.
It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointed at by format when those characters are not a interpreted as a %n specifier. For example, if the entire format string was %%n.
It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointed at by format when those characters are not a interpreted as a %n specifier. For example, if the entire format string was %%n.
As the functions vfprintf_s, vfscanf_s, vprintf_s, vscanf_s, vsnprintf_s, vsprintf_s, and vsscanf_s invoke the va_arg macro, the value of arg after the return is indeterminate.
It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointed at by format when those characters are not a interpreted as a %n specifier. For example, if the entire format string was %%n.
As the functions vfprintf_s, vfscanf_s, vprintf_s, vscanf_s, vsnprintf_s, vsprintf_s, and vsscanf_s invoke the va_arg macro, the value of arg after the return is indeterminate.
It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointed at by format when those characters are not a interpreted as a %n specifier. For example, if the entire format string was %%n.
It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointed at by format when those characters are not a interpreted as a %n specifier. For example, if the entire format string was %%n.
As the functions vfprintf_s, vfscanf_s, vprintf_s, vscanf_s, vsnprintf_s, vsprintf_s, and vsscanf_s invoke the va_arg macro, the value of arg after the return is indeterminate.
The gets_s function, unlike the historical gets function, makes it a runtime-constraint violation for a line of input to overflow the buffer to store it. Unlike the fgets function, gets_s maintains a one-to-one relationship between input lines and successful calls to gets_s. Programs that use gets expect such a relationship.
If the previous handler was registered by calling set_constraint_handler_s with a null pointer argument, a pointer to the implementation default handler is returned (not NULL).
Many implementations invoke a debugger when the abort function is called.
If the runtime-constraint handler is set to the ignore_handler_s function, any library function in which a runtime-constraint violation occurs will return to its caller. The caller can determine whether a runtime-constraint violation occurred based on the library function’s specification (usually, the library function returns a nonzero errno_t).
Many implementations provide non-standard functions that modify the environment list.
That is, if the value passed is p, then the following expressions are always valid and nonzero: ((char *)p - (char *)base) % size == 0 (char *)p >= (char *)base (char *)p < (char *)base + nmemb * size
In practice, this means that the entire array has been sorted according to the comparison function.
The context argument is for the use of the comparison function in performing its duties. For example, it might specify a collating sequence used by the comparison function.
The context argument is for the use of the comparison function in performing its duties. For example, it might specify a collating sequence used by the comparison function.
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.
Thus, the value of len is ignored if dst is a null pointer.
This allows an implementation to attempt converting the multibyte string before discovering a terminating null character did not occur where required.
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. However, if the conversion stops before a terminating null wide character has been reached, the result will be null terminated, but might not end in the initial shift state.
When len is not less than dstmax, the implementation might fill the array before discovering a runtime-constraint violation.
This allows an implementation to copy characters from s2 to s1 while simultaneously checking if any of those characters are null. Such an approach might write a character to every element of s1 before discovering that the first element should be set to the null character.
A zero return value implies that all of the requested characters from the string pointed to by s2 fit within the array pointed to by s1 and that the result in s1 is null terminated.
This allows an implementation to copy characters from s2 to s1 while simultaneously checking if any of those characters are null. Such an approach might write a character to every element of s1 before discovering that the first element should be set to the null character.
A zero return value implies that all of the requested characters from the string pointed to by s2 fit within the array pointed to by s1 and that the result in s1 is null terminated.
Zero means that s1 was not null terminated upon entry to strcat_s.
This allows an implementation to append characters from s2 to s1 while simultaneously checking if any of those characters are null. Such an approach might write a character to every element of s1 before discovering that the first element should be set to the null character.
A zero return value implies that all of the requested characters from the string pointed to by s2 were appended to the string pointed to by s1 and that the result in s1 is null terminated.
Zero means that s1 was not null terminated upon entry to strncat_s.
This allows an implementation to append characters from s2 to s1 while simultaneously checking if any of those characters are null. Such an approach might write a character to every element of s1 before discovering that the first element should be set to the null character.
A zero return value implies that all of the requested characters from the string pointed to by s2 were appended to the string pointed to by s1 and that the result in s1 is null terminated.
Note that the strnlen_s function has no runtime-constraints. This lack of runtime-constraints along with the values returned for a null pointer or an unterminated string argument make strnlen_s useful in algorithms that gracefully handle such exceptional data.
The normal ranges are defined in 7.27.1.
It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was L"%%n".
If the format is known at translation time, an implementation may issue a diagnostic for any argument used to store the result from a c, s, or [ conversion specifier if that argument is not followed by an argument of a type compatible with rsize_t. A limited amount of checking may be done if even if the format is not known at translation time. For example, an implementation may issue a diagnostic for each argument after format that has of type pointer to one of char, signed char, unsigned char, or void that is not followed by an argument of a type compatible with rsize_t. The diagnostic could warn that unless the pointer is being used with a conversion specifier using the hh length modifier, a length argument must follow the pointer argument. Another useful diagnostic could flag any non-pointer argument following format that did not have a type compatible with rsize_t.
It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was L"%%n".
It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was L"%%n".
It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was L"%%n".
As the functions vfwscanf_s, vwscanf_s, and vswscanf_s invoke the va_arg macro, the value of arg after the return is indeterminate.
It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was L"%%n".
It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was L"%%n".
As the functions vfwscanf_s, vwscanf_s, and vswscanf_s invoke the va_arg macro, the value of arg after the return is indeterminate.
It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was L"%%n".
As the functions vfwscanf_s, vwscanf_s, and vswscanf_s invoke the va_arg macro, the value of arg after the return is indeterminate.
It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was L"%%n".
This allows an implementation to copy wide characters from s2 to s1 while simultaneously checking if any of those wide characters are null. Such an approach might write a wide character to every element of s1 before discovering that the first element should be set to the null wide character.
A zero return value implies that all of the requested wide characters from the string pointed to by s2 fit within the array pointed to by s1 and that the result in s1 is null terminated.
This allows an implementation to copy wide characters from s2 to s1 while simultaneously checking if any of those wide characters are null. Such an approach might write a wide character to every element of s1 before discovering that the first element should be set to the null wide character.
A zero return value implies that all of the requested wide characters from the string pointed to by s2 fit within the array pointed to by s1 and that the result in s1 is null terminated.
Zero means that s1 was not null terminated upon entry to wcscat_s.
This allows an implementation to append wide characters from s2 to s1 while simultaneously checking if any of those wide characters are null. Such an approach might write a wide character to every element of s1 before discovering that the first element should be set to the null wide character.
A zero return value implies that all of the requested wide characters from the wide string pointed to by s2 were appended to the wide string pointed to by s1 and that the result in s1 is null terminated.
Zero means that s1 was not null terminated upon entry to wcsncat_s.
This allows an implementation to append wide characters from s2 to s1 while simultaneously checking if any of those wide characters are null. Such an approach might write a wide character to every element of s1 before discovering that the first element should be set to the null wide character.
A zero return value implies that all of the requested wide characters from the wide string pointed to by s2 were appended to the wide string pointed to by s1 and that the result in s1 is null terminated.
Note that the wcsnlen_s function has no runtime-constraints. This lack of runtime-constraints along with the values returned for a null pointer or an unterminated wide string argument make wcsnlen_s useful in algorithms that gracefully handle such exceptional data.
Thus, the value of len is ignored if dst is a null pointer.
This allows an implementation to attempt converting the multibyte string before discovering a terminating null character did not occur where required.
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. However, if the conversion stops before a terminating null wide character has been reached, the result will be null terminated, but might not end in the initial shift state.
When len is not less than dstmax, the implementation might fill the array before discovering a runtime-constraint violation.
Implementations that do not define _ _STDC_ANALYZABLE_ _ are not required to conform to these specifications.
April 12, 2011 posix.fail