2 The wcstoimax and wcstoumax functions are equivalent to the wcstol, wcstoll,
wcstoul, and wcstoull functions except that the initial portion of the wide string is
converted to intmax_t and uintmax_t representation, respectively.
Returns
3 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
(<IP_ADDRESS>.2).
7.9 [Alternative spellings <iso646.h>]
1 The header <iso646.h> defines the following eleven macros (on the left) that expand
to the corresponding tokens (on the right):
and &&
and_eq &=
bitand &
bitor |
compl ~
not !
not_eq !=
or ||
or_eq |=
xor ^
xor_eq ^=
7.10 [Sizes of integer types <limits.h>]
1 The header <limits.h> defines several macros that expand to various limits and
parameters of the standard integer types.
2 The macros, their meanings, and the constraints (or restrictions) on their values are listed
in <IP_ADDRESS>.1.
7.11 [Localization <locale.h>]
1 The header <locale.h> declares two functions, one type, and defines several macros.
2 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 <IP_ADDRESS>. 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
3 The macros defined are NULL (described in 7.17); and
LC_ALL
LC_COLLATE
LC_CTYPE
LC_MONETARY
LC_NUMERIC
LC_TIME
which expand to integer constant expressions with distinct values, suitable for use as the
first argument to the setlocale function.[194] Additional macro definitions, beginning
with the characters LC_ and an uppercase letter,[195] may also be specified by the
implementation.
Footnote 194) ISO/IEC 9945−2 specifies locale and charmap formats that may be used to specify locales for C.
Footnote 195) See ‘‘future library directions’’ (7.26.5).
7.11.1 [Locale control]
<IP_ADDRESS> [The setlocale function]
1 Synopsis
#include <locale.h>
char *setlocale(int category, const char *locale);
Description
2 The setlocale function selects the appropriate portion of the program’s locale as
specified by the category and locale arguments. The setlocale function may be
used to change or query the program’s entire current locale or portions thereof. The value
LC_ALL for category names the program’s entire locale; the other values for
category name only a portion of the program’s locale. LC_COLLATE affects the
behavior of the strcoll and strxfrm functions. LC_CTYPE affects the behavior of
the character handling functions[196] and the multibyte and wide character functions.
LC_MONETARY affects the monetary formatting information returned by the
localeconv function. LC_NUMERIC affects the decimal-point character for the
formatted input/output functions and the string conversion functions, as well as the
nonmonetary formatting information returned by the localeconv function. LC_TIME
affects the behavior of the strftime and wcsftime functions.
Footnote 196) The only functions in 7.4 whose behavior is not affected by the current locale are isdigit and
isxdigit.
3 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.
4 At program startup, the equivalent of
setlocale(LC_ALL, "C");
is executed.
5 The implementation shall behave as if no library function calls the setlocale function.
Returns
6 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.
7 A null pointer for locale causes the setlocale function to return a pointer to the
string associated with the category for the program’s current locale; the program’s
locale is not changed.[197]
Footnote 197) The implementation shall arrange to encode in a string the various categories due to a heterogeneous
locale when category has the value LC_ALL.
8 The pointer to string returned by the setlocale function is such that a subsequent call
with that string value and its associated category will restore that part of the program’s
locale. The string pointed to shall not be modified by the program, but may be
overwritten by a subsequent call to the setlocale function.
Forward references: formatted input/output functions (7.19.6), multibyte/wide
character conversion functions (7.20.7), multibyte/wide string conversion functions
(7.20.8), numeric conversion functions (7.20.1), the strcoll function (<IP_ADDRESS>), the
strftime function (<IP_ADDRESS>), the strxfrm function (<IP_ADDRESS>).
7.11.2 [Numeric formatting convention inquiry]
<IP_ADDRESS> [The localeconv function]
1 Synopsis
#include <locale.h>
struct lconv *localeconv(void);
Description
2 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.
3 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.
4 The elements of grouping and mon_grouping are interpreted according to the
following:
CHAR_MAX No further grouping is to be performed.
0 The previous element is to be repeatedly used for the remainder of the
digits.
other The integer value is the number of digits that compose the current group.
The next element is examined to determine the size of the next group of
digits before the current group.
5 The values of p_sep_by_space, n_sep_by_space, int_p_sep_by_space,
and int_n_sep_by_space are interpreted according to the following:
0 No space separates the currency symbol and value.
1 If the currency symbol and sign string are adjacent, a space separates them from the
value; otherwise, a space separates the currency symbol from the value.
2 If the currency symbol and sign string are adjacent, a space separates them;
otherwise, a space separates the sign string from the value.
For int_p_sep_by_space and int_n_sep_by_space, the fourth character of
int_curr_symbol is used instead of a space.
6 The values of p_sign_posn, n_sign_posn, int_p_sign_posn, and
int_n_sign_posn are interpreted according to the following:
0 Parentheses surround the quantity and currency symbol.
1 The sign string precedes the quantity and currency symbol.
2 The sign string succeeds the quantity and currency symbol.
3 The sign string immediately precedes the currency symbol.
4 The sign string immediately succeeds the currency symbol.
7 The implementation shall behave as if no library function calls the localeconv
function.
Returns
8 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.
9 EXAMPLE 1 The following table illustrates rules which may well be used by four countries to format
monetary quantities.
Local format International format
Country Positive Negative Positive Negative
Country1 1.234,56 mk -1.234,56 mk FIM 1.234,56 FIM -1.234,56
Country2 L.1.234 -L.1.234 ITL 1.234 -ITL 1.234
Country3 ƒ 1.234,56 ƒ -1.234,56 NLG 1.234,56 NLG -1.234,56
Country4 SFrs.1,234.56 SFrs.1,234.56C CHF 1,234.56 CHF 1,234.56C
10 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."
 Most synopses specify a family of functions consisting of a principal
function with one or more double parameters, a double return value, or both; and
other functions with the same name but with f and l suffixes, which are corresponding
functions with float and long double parameters, return values, or both.[198]
Integer arithmetic functions and conversion functions are discussed later.
Footnote 198) Particularly on systems with wide expression evaluation, a <math.h> function might pass arguments
and return values in wider format than the synopsis prototype indicates.
2 The types
float_t
double_t
are floating types at least as wide as float and double, respectively, and such that
double_t is at least as wide as float_t. If FLT_EVAL_METHOD equals 0,
float_t and double_t are float and double, respectively; if
FLT_EVAL_METHOD equals 1, they are both double; if FLT_EVAL_METHOD equals
2, they are both long double; and for other values of FLT_EVAL_METHOD, they are
otherwise implementation-defined.[199]
Footnote 199) The types float_t and double_t are intended to be the implementation’s most efficient types at
least as wide as float and double, respectively. For FLT_EVAL_METHOD equal 0, 1, or 2, the
type float_t is the narrowest type used by the implementation to evaluate floating expressions.
3 The macro
HUGE_VAL
expands to a positive double constant expression, not necessarily representable as a
float. The macros
HUGE_VALF
HUGE_VALL
are respectively float and long double analogs of HUGE_VAL.[200]
Footnote 200) HUGE_VAL, HUGE_VALF, and HUGE_VALL can be positive infinities in an implementation that
supports infinities.
4 The macro
INFINITY
expands to a constant expression of type float representing positive or unsigned
infinity, if available; else to a positive constant of type float that overflows at
translation time.[201]
Footnote 201) In this case, using INFINITY will violate the constraint in 6.4.4 and thus require a diagnostic.
5 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.
6 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.
7 The macro
FP_FAST_FMA
is optionally defined. If defined, it indicates that the fma function generally executes
about as fast as, or faster than, a multiply and an add of double operands.[202] The
macros
FP_FAST_FMAF
FP_FAST_FMAL
are, respectively, float and long double analogs of FP_FAST_FMA. If defined,
these macros expand to the integer constant 1.
Footnote 202) Typically, the FP_FAST_FMA macro is defined if and only if the fma function is implemented
directly with a hardware multiply-add instruction. Software implementations are expected to be
substantially slower.
8 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.
9 The macros
MATH_ERRNO
MATH_ERREXCEPT
expand to the integer constants 1 and 2, respectively; the macro
math_errhandling
expands to an expression that has type int and the value MATH_ERRNO,
MATH_ERREXCEPT, or the bitwise OR of both. The value of math_errhandling is
constant for the duration of the program. It is unspecified whether
math_errhandling is a macro or an identifier with external linkage. If a macro
definition is suppressed or a program defines an identifier with the name
math_errhandling, the behavior is undefined. If the expression
math_errhandling & MATH_ERREXCEPT can be nonzero, the implementation
shall define the macros FE_DIVBYZERO, FE_INVALID, and FE_OVERFLOW in
<fenv.h>.
7.12.1 [Treatment of error conditions]
1 The behavior of each of the functions in <math.h> is specified for all representable
values of its input arguments, except where stated otherwise. Each function shall execute
as if it were a single operation without generating any externally visible exceptional
conditions.
2 For all functions, a domain error occurs if an input argument is outside the domain over
which the mathematical function is defined. The description of each function lists any
required domain errors; an implementation may define additional domain errors, provided
that such errors are consistent with the mathematical definition of the function.[203] On a
domain error, the function returns an implementation-defined value; if the integer
expression math_errhandling & MATH_ERRNO is nonzero, the integer expression
errno acquires the value EDOM; if the integer expression math_errhandling &
MATH_ERREXCEPT is nonzero, the ‘‘invalid’’ floating-point exception is raised.
Footnote 203) In an implementation that supports infinities, this allows an infinity as an argument to be a domain
error if the mathematical domain of the function does not include the infinity.
3 Similarly, a range error occurs if the mathematical result of the function cannot be
represented in an object of the specified type, due to extreme magnitude.
4 A floating result overflows if the magnitude of the mathematical result is finite but so
large that the mathematical result cannot be represented without extraordinary roundoff
error in an object of the specified type. If a floating result overflows and default rounding
is in effect, or if the mathematical result is an exact infinity from finite arguments (for
example log(0.0)), then the function returns the value of the macro HUGE_VAL,
HUGE_VALF, or HUGE_VALL according to the return type, with the same sign as the
correct value of the function; if the integer expression math_errhandling &
MATH_ERRNO is nonzero, the integer expression errno acquires the value ERANGE; if
the integer expression math_errhandling & MATH_ERREXCEPT is nonzero, the
‘‘divide-by-zero’’ floating-point exception is raised if the mathematical result is an exact
infinity and the ‘‘overflow’’ floating-point exception is raised otherwise.
5 The result underflows if the magnitude of the mathematical result is so small that the
mathematical result cannot be represented, without extraordinary roundoff error, in an
object of the specified type.[204] If the result underflows, the function returns an
implementation-defined value whose magnitude is no greater than the smallest
normalized positive number in the specified type; if the integer expression
math_errhandling & MATH_ERRNO is nonzero, whether errno acquires the
value ERANGE is implementation-defined; if the integer expression
math_errhandling & MATH_ERREXCEPT is nonzero, whether the ‘‘underflow’’
floating-point exception is raised is implementation-defined.
Footnote 204) The term underflow here is intended to encompass both ‘‘gradual underflow’’ as in IEC 60559 and
also ‘‘flush-to-zero’’ underflow.
7.12.2 [The FP_CONTRACT pragma]
1 Synopsis
#include <math.h>
#pragma STDC FP_CONTRACT on-off-switch
Description
2 The FP_CONTRACT pragma can be used to allow (if the state is ‘‘on’’) or disallow (if the
state is ‘‘off’’) the implementation to contract expressions (6.5). Each pragma can occur
either outside external declarations or preceding all explicit declarations and statements
inside a compound statement. When outside external declarations, the pragma takes
effect from its occurrence until another FP_CONTRACT pragma is encountered, or until
the end of the translation unit. When inside a compound statement, the pragma takes
effect from its occurrence until another FP_CONTRACT pragma is encountered
(including within a nested compound statement), or until the end of the compound
statement; at the end of a compound statement the state for the pragma is restored to its
condition just before the compound statement. If this pragma is used in any other
context, the behavior is undefined. The default state (‘‘on’’ or ‘‘off’’) for the pragma is
implementation-defined.
7.12.3 [Classification macros]
1 In the synopses in this subclause, real-floating indicates that the argument shall be an
expression of real floating type.
<IP_ADDRESS> [The fpclassify macro]
1 Synopsis
#include <math.h>
int fpclassify(real-floating x);
Description
2 The fpclassify macro classifies its argument value as NaN, infinite, normal,
subnormal, zero, or into another implementation-defined category. First, an argument
represented in a format wider than its semantic type is converted to its semantic type.
Then classification is based on the type of the argument.[205]
Returns
Footnote 205) Since an expression can be evaluated with more range and precision than its type has, it is important to
know the type that classification is based on. For example, a normal long double value might
become subnormal when converted to double, and zero when converted to float.
3 The fpclassify macro returns the value of the number classification macro
appropriate to the value of its argument.
4 EXAMPLE The fpclassify macro might be implemented in terms of ordinary functions as
#define fpclassify(x) \
((sizeof (x) == sizeof (float)) ? _ _fpclassifyf(x) : \
(sizeof (x) == sizeof (double)) ? _ _fpclassifyd(x) : \
_ _fpclassifyl(x))
<IP_ADDRESS> [The isfinite macro]
1 Synopsis
#include <math.h>
int isfinite(real-floating x);
Description
2 The isfinite macro determines whether its argument has a finite value (zero,
subnormal, or normal, and not infinite or NaN). First, an argument represented in a
format wider than its semantic type is converted to its semantic type. Then determination
is based on the type of the argument.
Returns
3 The isfinite macro returns a nonzero value if and only if its argument has a finite
value.
<IP_ADDRESS> [The isinf macro]
1 Synopsis
#include <math.h>
int isinf(real-floating x);
Description
2 The isinf macro determines whether its argument value is an infinity (positive or
negative). First, an argument represented in a format wider than its semantic type is
converted to its semantic type. Then determination is based on the type of the argument.
Returns
3 The isinf macro returns a nonzero value if and only if its argument has an infinite
value.
<IP_ADDRESS> [The isnan macro]
1 Synopsis
#include <math.h>
int isnan(real-floating x);
Description
2 The isnan macro determines whether its argument value is a NaN. First, an argument
represented in a format wider than its semantic type is converted to its semantic type.
Then determination is based on the type of the argument.[206]
Returns
Footnote 206) For the isnan macro, the type for determination does not matter unless the implementation supports
NaNs in the evaluation type but not in the semantic type.
3 The isnan macro returns a nonzero value if and only if its argument has a NaN value.
<IP_ADDRESS> [The isnormal macro]
1 Synopsis
#include <math.h>
int isnormal(real-floating x);
Description
2 The isnormal macro determines whether its argument value is normal (neither zero,
subnormal, infinite, nor NaN). First, an argument represented in a format wider than its
semantic type is converted to its semantic type. Then determination is based on the type
of the argument.
Returns
3 The isnormal macro returns a nonzero value if and only if its argument has a normal
value.
<IP_ADDRESS> [The signbit macro]
1 Synopsis
#include <math.h>
int signbit(real-floating x);
Description
2 The signbit macro determines whether the sign of its argument value is negative.[207]
Returns
Footnote 207) The signbit macro reports the sign of all values, including infinities, zeros, and NaNs. If zero is
unsigned, it is treated as positive.
3 The signbit macro returns a nonzero value if and only if the sign of its argument value
is negative.
7.12.4 [Trigonometric functions]
<IP_ADDRESS> [The acos functions]
1 Synopsis
#include <math.h>
double acos(double x);
float acosf(float x);
long double acosl(long double x);
Description
2 The acos functions compute the principal value of the arc cosine of x. A domain error
occurs for arguments not in the interval [−1, +1].
Returns
3 The acos functions return arccos x in the interval [0, π ] radians.
<IP_ADDRESS> [The asin functions]
1 Synopsis
#include <math.h>
double asin(double x);
float asinf(float x);
long double asinl(long double x);
Description
2 The asin functions compute the principal value of the arc sine of x. A domain error
occurs for arguments not in the interval [−1, +1].
Returns
3 The asin functions return arcsin x in the interval [−π /2, +π /2] radians.
<IP_ADDRESS> [The atan functions]
1 Synopsis
#include <math.h>
double atan(double x);
float atanf(float x);
long double atanl(long double x);
Description
2 The atan functions compute the principal value of the arc tangent of x.
Returns
3 The atan functions return arctan x in the interval [−π /2, +π /2] radians.
<IP_ADDRESS> [The atan2 functions]
1 Synopsis
#include <math.h>
double atan2(double y, double x);
float atan2f(float y, float x);
long double atan2l(long double y, long double x);
Description
2 The atan2 functions compute the value of the arc tangent of y/x, using the signs of both
arguments to determine the quadrant of the return value. A domain error may occur if
both arguments are zero.
Returns
3 The atan2 functions return arctan y/x in the interval [−π , +π ] radians.
<IP_ADDRESS> [The cos functions]
1 Synopsis
#include <math.h>
double cos(double x);
float cosf(float x);
long double cosl(long double x);
Description
2 The cos functions compute the cosine of x (measured in radians).
Returns
3 The cos functions return cos x.
<IP_ADDRESS> [The sin functions]
1 Synopsis
#include <math.h>
double sin(double x);
float sinf(float x);
long double sinl(long double x);
Description
2 The sin functions compute the sine of x (measured in radians).
Returns
3 The sin functions return sin x.
<IP_ADDRESS> [The tan functions]
1 Synopsis
#include <math.h>
double tan(double x);
float tanf(float x);
long double tanl(long double x);
Description
2 The tan functions return the tangent of x (measured in radians).
Returns
3 The tan functions return tan x.
7.12.5 [Hyperbolic functions]
<IP_ADDRESS> [The acosh functions]
1 Synopsis
#include <math.h>
double acosh(double x);
float acoshf(float x);
long double acoshl(long double x);
Description
2 The acosh functions compute the (nonnegative) arc hyperbolic cosine of x. A domain
error occurs for arguments less than 1.
Returns
3 The acosh functions return arcosh x in the interval [0, +∞].
<IP_ADDRESS> [The asinh functions]
1 Synopsis
#include <math.h>
double asinh(double x);
float asinhf(float x);
long double asinhl(long double x);
Description
2 The asinh functions compute the arc hyperbolic sine of x.
Returns
3 The asinh functions return arsinh x.
<IP_ADDRESS> [The atanh functions]
1 Synopsis
#include <math.h>
double atanh(double x);
float atanhf(float x);
long double atanhl(long double x);
Description
2 The atanh functions compute the arc hyperbolic tangent of x. A domain error occurs
for arguments not in the interval [−1, +1]. A range error may occur if the argument
equals −1 or +1.
Returns
3 The atanh functions return artanh x.
<IP_ADDRESS> [The cosh functions]
1 Synopsis
#include <math.h>
double cosh(double x);
float coshf(float x);
long double coshl(long double x);
Description
2 The cosh functions compute the hyperbolic cosine of x. A range error occurs if the
magnitude of x is too large.
Returns
3 The cosh functions return cosh x.
<IP_ADDRESS> [The sinh functions]
1 Synopsis
#include <math.h>
double sinh(double x);
float sinhf(float x);
long double sinhl(long double x);
Description
2 The sinh functions compute the hyperbolic sine of x. A range error occurs if the
magnitude of x is too large.
Returns
3 The sinh functions return sinh x.
<IP_ADDRESS> [The tanh functions]
1 Synopsis
#include <math.h>
double tanh(double x);
float tanhf(float x);
long double tanhl(long double x);
Description
2 The tanh functions compute the hyperbolic tangent of x.
Returns
3 The tanh functions return tanh x.
7.12.6 [Exponential and logarithmic functions]
<IP_ADDRESS> [The exp functions]
1 Synopsis
#include <math.h>
double exp(double x);
float expf(float x);
long double expl(long double x);
Description
2 The exp functions compute the base-e exponential of x. A range error occurs if the
magnitude of x is too large.
Returns
3 The exp functions return ex .
<IP_ADDRESS> [The exp2 functions]
1 Synopsis
#include <math.h>
double exp2(double x);
float exp2f(float x);
long double exp2l(long double x);
Description
2 The exp2 functions compute the base-2 exponential of x. A range error occurs if the
magnitude of x is too large.
Returns
3 The exp2 functions return 2x .
<IP_ADDRESS> [The expm1 functions]
1 Synopsis
#include <math.h>
double expm1(double x);
float expm1f(float x);
long double expm1l(long double x);
Description
2 The expm1 functions compute the base-e exponential of the argument, minus 1. A range
error occurs if x is too large.[208]
Returns
Footnote 208) For small magnitude x, expm1(x) is expected to be more accurate than exp(x) - 1.
3 The expm1 functions return ex − 1.
<IP_ADDRESS> [The frexp functions]
1 Synopsis
#include <math.h>
double frexp(double value, int *exp);
float frexpf(float value, int *exp);
long double frexpl(long double value, int *exp);
Description
2 The frexp functions break a floating-point number into a normalized fraction and an
integral power of 2. They store the integer in the int object pointed to by exp.
Returns
3 If value is not a floating-point number, the results are unspecified. Otherwise, the
frexp functions return the value x, such that x has a magnitude in the interval [1/2, [1] or
zero, and value equals x × 2*exp . If value is zero, both parts of the result are zero.
Footnote 1) This International Standard is designed to promote the portability of C programs among a variety of
data-processing systems. It is intended for use by implementors and programmers.
<IP_ADDRESS> [The ilogb functions]
1 Synopsis
#include <math.h>
int ilogb(double x);
int ilogbf(float x);
int ilogbl(long double x);
Description
2 The ilogb functions extract the exponent of x as a signed int value. If x is zero they
compute the value FP_ILOGB0; if x is infinite they compute the value INT_MAX; if x is
a NaN they compute the value FP_ILOGBNAN; otherwise, they are equivalent to calling
the corresponding logb function and casting the returned value to type int. A domain
error or range error may occur if x is zero, infinite, or NaN. If the correct value is outside
the range of the return type, the numeric result is unspecified.
Returns
3 The ilogb functions return the exponent of x as a signed int value.
Forward references: the logb functions (<IP_ADDRESS>).
<IP_ADDRESS> [The ldexp functions]
1 Synopsis
#include <math.h>
double ldexp(double x, int exp);
float ldexpf(float x, int exp);
long double ldexpl(long double x, int exp);
Description
2 The ldexp functions multiply a floating-point number by an integral power of 2. A
range error may occur.
Returns
3 The ldexp functions return x × 2exp .
<IP_ADDRESS> [The log functions]
1 Synopsis
#include <math.h>
double log(double x);
float logf(float x);
long double logl(long double x);
Description
2 The log functions compute the base-e (natural) logarithm of x. A domain error occurs if
the argument is negative. A range error may occur if the argument is zero.
Returns
3 The log functions return loge x.
<IP_ADDRESS> [The log10 functions]
1 Synopsis
#include <math.h>
double log10(double x);
float log10f(float x);
long double log10l(long double x);
Description
2 The log10 functions compute the base-10 (common) logarithm of x. A domain error
occurs if the argument is negative. A range error may occur if the argument is zero.
Returns
3 The log10 functions return log10 x.
<IP_ADDRESS> [The log1p functions]
1 Synopsis
#include <math.h>
double log1p(double x);
float log1pf(float x);
long double log1pl(long double x);
Description
2 The log1p functions compute the base-e (natural) logarithm of 1 plus the argument.[209]
A domain error occurs if the argument is less than −1. A range error may occur if the
argument equals −1.
Returns
Footnote 209) For small magnitude x, log1p(x) is expected to be more accurate than log(1 + x).
3 The log1p functions return loge (1 + x).
<IP_ADDRESS> [The log2 functions]
1 Synopsis
#include <math.h>
double log2(double x);
float log2f(float x);
long double log2l(long double x);
Description
2 The log2 functions compute the base-2 logarithm of x. A domain error occurs if the
argument is less than zero. A range error may occur if the argument is zero.
Returns
3 The log2 functions return log2 x.
<IP_ADDRESS> [The logb functions]
1 Synopsis
#include <math.h>
double logb(double x);
float logbf(float x);
long double logbl(long double x);
Description
2 The logb functions extract the exponent of x, as a signed integer value in floating-point
format. If x is subnormal it is treated as though it were normalized; thus, for positive
finite x,
1 ≤ x × FLT_RADIX−logb(x) < FLT_RADIX
A domain error or range error may occur if the argument is zero.
Returns
3 The logb functions return the signed exponent of x.
<IP_ADDRESS> [The modf functions]
1 Synopsis
#include <math.h>
double modf(double value, double *iptr);
float modff(float value, float *iptr);
long double modfl(long double value, long double *iptr);
Description
2 The modf functions break the argument value into integral and fractional parts, each of
which has the same type and sign as the argument. They store the integral part (in
floating-point format) in the object pointed to by iptr.
Returns
3 The modf functions return the signed fractional part of value.
<IP_ADDRESS> [The scalbn and scalbln functions]
1 Synopsis
#include <math.h>
double scalbn(double x, int n);
float scalbnf(float x, int n);
long double scalbnl(long double x, int n);
double scalbln(double x, long int n);
float scalblnf(float x, long int n);
long double scalblnl(long double x, long int n);
Description
2 The scalbn and scalbln functions compute x × FLT_RADIXn efficiently, not
normally by computing FLT_RADIXn explicitly. A range error may occur.
Returns
3 The scalbn and scalbln functions return x × FLT_RADIXn .
7.12.7 [Power and absolute-value functions]
<IP_ADDRESS> [The cbrt functions]
1 Synopsis
#include <math.h>
double cbrt(double x);
float cbrtf(float x);
long double cbrtl(long double x);
Description
2 The cbrt functions compute the real cube root of x.
Returns
3 The cbrt functions return x1/3 .
<IP_ADDRESS> [The fabs functions]
1 Synopsis
#include <math.h>
double fabs(double x);
float fabsf(float x);
long double fabsl(long double x);
Description
2 The fabs functions compute the absolute value of a floating-point number x.
Returns
3 The fabs functions return | x |.
<IP_ADDRESS> [The hypot functions]
1 Synopsis
#include <math.h>
double hypot(double x, double y);
float hypotf(float x, float y);
long double hypotl(long double x, long double y);
Description
2 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.
3 Returns
4 The hypot functions return √
x2 + y2 .
<IP_ADDRESS> [The pow functions]
1 Synopsis
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
Description
2 The pow functions compute x raised to the power y. A domain error occurs if x is finite
and negative and y is finite and not an integer value. A range error may occur. A domain
error may occur if x is zero and y is zero. A domain error or range error may occur if x
is zero and y is less than zero.
Returns
3 The pow functions return xy .
<IP_ADDRESS> [The sqrt functions]
1 Synopsis
#include <math.h>
double sqrt(double x);
float sqrtf(float x);
long double sqrtl(long double x);
Description
2 The sqrt functions compute the nonnegative square root of x. A domain error occurs if
the argument is less than zero.
Returns
3 The sqrt functions return √
x.
7.12.8 [Error and gamma functions]
<IP_ADDRESS> [The erf functions]
1 Synopsis
#include <math.h>
double erf(double x);
float erff(float x);
long double erfl(long double x);
Description
2 The erf functions compute the error function of x.
Returns
2 x
π ∫
3 −t 2
The erf functions return erf x = e dt.
√ 0
<IP_ADDRESS> [The erfc functions]
1 Synopsis
#include <math.h>
double erfc(double x);
float erfcf(float x);
long double erfcl(long double x);
Description
2 The erfc functions compute the complementary error function of x. A range error
occurs if x is too large.
Returns
2 ∞
π ∫
3 −t 2
The erfc functions return erfc x = 1 − erf x = e dt.
√ x
<IP_ADDRESS> [The lgamma functions]
1 Synopsis
#include <math.h>
double lgamma(double x);
float lgammaf(float x);
long double lgammal(long double x);
Description
2 The lgamma functions compute the natural logarithm of the absolute value of gamma of
x. A range error occurs if x is too large. A range error may occur if x is a negative
integer or zero.
Returns
3 The lgamma functions return loge | Γ(x) |.
<IP_ADDRESS> [The tgamma functions]
1 Synopsis
#include <math.h>
double tgamma(double x);
float tgammaf(float x);
long double tgammal(long double x);
Description
2 The tgamma functions compute the gamma function of x. A domain error or range error
may occur if x is a negative integer or zero. A range error may occur if the magnitude of
x is too large or too small.
Returns
3 The tgamma functions return Γ(x).
7.12.9 [Nearest integer functions]
<IP_ADDRESS> [The ceil functions]
1 Synopsis
#include <math.h>
double ceil(double x);
float ceilf(float x);
long double ceill(long double x);
Description
2 The ceil functions compute the smallest integer value not less than x.
Returns
3 The ceil functions return x, expressed as a floating-point number.
<IP_ADDRESS> [The floor functions]
1 Synopsis
#include <math.h>
double floor(double x);
float floorf(float x);
long double floorl(long double x);
Description
2 The floor functions compute the largest integer value not greater than x.
Returns
3 The floor functions return x, expressed as a floating-point number.
<IP_ADDRESS> [The nearbyint functions]
1 Synopsis
#include <math.h>
double nearbyint(double x);
float nearbyintf(float x);
long double nearbyintl(long double x);
Description
2 The nearbyint functions round their argument to an integer value in floating-point
format, using the current rounding direction and without raising the ‘‘inexact’’ floating-
point exception.
Returns
3 The nearbyint functions return the rounded integer value.
<IP_ADDRESS> [The rint functions]
1 Synopsis
#include <math.h>
double rint(double x);
float rintf(float x);
long double rintl(long double x);
Description
2 The rint functions differ from the nearbyint functions (<IP_ADDRESS>) only in that the
rint functions may raise the ‘‘inexact’’ floating-point exception if the result differs in
Returns
3 The rint functions return the rounded integer value.
<IP_ADDRESS> [The lrint and llrint functions]
1 Synopsis
#include <math.h>
long int lrint(double x);
long int lrintf(float x);
long int lrintl(long double x);
long long int llrint(double x);
long long int llrintf(float x);
long long int llrintl(long double x);
Description
2 The lrint and llrint functions round their argument to the nearest integer value,
rounding according to the current rounding direction. If the rounded value is outside the
range of the return type, the numeric result is unspecified and a domain error or range
error may occur. ∗
Returns
3 The lrint and llrint functions return the rounded integer value.
<IP_ADDRESS> [The round functions]
1 Synopsis
#include <math.h>
double round(double x);
float roundf(float x);
long double roundl(long double x);
Description
2 The round functions round their argument to the nearest integer value in floating-point
format, rounding halfway cases away from zero, regardless of the current rounding
direction.
Returns
3 The round functions return the rounded integer value.
<IP_ADDRESS> [The lround and llround functions]
1 Synopsis
#include <math.h>
long int lround(double x);
long int lroundf(float x);
long int lroundl(long double x);
long long int llround(double x);
long long int llroundf(float x);
long long int llroundl(long double x);
Description
2 The lround and llround functions round their argument to the nearest integer value,
rounding halfway cases away from zero, regardless of the current rounding direction. If
the rounded value is outside the range of the return type, the numeric result is unspecified
and a domain error or range error may occur.
Returns
3 The lround and llround functions return the rounded integer value.
<IP_ADDRESS> [The trunc functions]
1 Synopsis
#include <math.h>
double trunc(double x);
float truncf(float x);
long double truncl(long double x);
Description
2 The trunc functions round their argument to the integer value, in floating format,
nearest to but no larger in magnitude than the argument.
Returns
3 The trunc functions return the truncated integer value.
7.12.10 [Remainder functions]
<IP_ADDRESS> [The fmod functions]
1 Synopsis
#include <math.h>
double fmod(double x, double y);
float fmodf(float x, float y);
long double fmodl(long double x, long double y);
Description
2 The fmod functions compute the floating-point remainder of x/y.
Returns
3 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.
<IP_ADDRESS> [The remainder functions]
1 Synopsis
#include <math.h>
double remainder(double x, double y);
float remainderf(float x, float y);
long double remainderl(long double x, long double y);
Description
2 The remainder functions compute the remainder x REM y required by IEC 60559.[210]
Returns
Footnote 210) ‘‘When y ≠ 0, the remainder r = x REM y is defined regardless of the rounding mode by the
mathematical relation r = x − ny, where n is the integer nearest the exact value of x/y; whenever
| n − x/y | = 1/2, then n is even. Thus, the remainder is always exact. If r = 0, its sign shall be that of
x.’’ This definition is applicable for all implementations.
3 The remainder functions return x REM y. If y is zero, whether a domain error occurs
or the functions return zero is implementation defined.
<IP_ADDRESS> [The remquo functions]
1 Synopsis
#include <math.h>
double remquo(double x, double y, int *quo);
float remquof(float x, float y, int *quo);
long double remquol(long double x, long double y,
int *quo);
Description
2 The remquo functions compute the same remainder as the remainder functions. In
the object pointed to by quo they store a value whose sign is the sign of x/y and whose
magnitude is congruent modulo 2n to the magnitude of the integral quotient of x/y, where
n is an implementation-defined integer greater than or equal to 3.
Returns
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.
7.12.11 [Manipulation functions]
<IP_ADDRESS> [The copysign functions]
1 Synopsis
#include <math.h>
double copysign(double x, double y);
float copysignf(float x, float y);
long double copysignl(long double x, long double y);
Description
2 The copysign functions produce a value with the magnitude of x and the sign of y.
They produce a NaN (with the sign of y) if x is a NaN. On implementations that
represent a signed zero but do not treat negative zero consistently in arithmetic
operations, the copysign functions regard the sign of zero as positive.
Returns
3 The copysign functions return a value with the magnitude of x and the sign of y.
<IP_ADDRESS> [The nan functions]
1 Synopsis
#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);
Description
2 The call nan("n-char-sequence") is equivalent to strtod("NAN(n-char-
sequence)", (char**) NULL); the call nan("") is equivalent to
strtod("NAN()", (char**) NULL). If tagp does not point to an n-char
sequence or an empty string, the call is equivalent to strtod("NAN", (char**)
NULL). Calls to nanf and nanl are equivalent to the corresponding calls to strtof
and strtold.
Returns
3 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 (<IP_ADDRESS>).
<IP_ADDRESS> [The nextafter functions]
1 Synopsis
#include <math.h>
double nextafter(double x, double y);
float nextafterf(float x, float y);
long double nextafterl(long double x, long double y);
Description
2 The nextafter functions determine the next representable value, in the type of the
function, after x in the direction of y, where x and y are first converted to the type of the
function.[211] The nextafter functions return y if x equals y. A range error may occur
if the magnitude of x is the largest finite value representable in the type and the result is
infinite or not representable in the type.
Returns
Footnote 211) The argument values are converted to the type of the function, even by a macro implementation of the
function.
3 The nextafter functions return the next representable value in the specified format
after x in the direction of y.
<IP_ADDRESS> [The nexttoward functions]
1 Synopsis
#include <math.h>
double nexttoward(double x, long double y);
float nexttowardf(float x, long double y);
long double nexttowardl(long double x, long double y);
Description
2 The nexttoward functions are equivalent to the nextafter functions except that the
second parameter has type long double and the functions return y converted to the
type of the function if x equals y.[212]
Footnote 212) The result of the nexttoward functions is determined in the type of the function, without loss of
range or precision in a floating second argument.
7.12.12 [Maximum, minimum, and positive difference functions]
<IP_ADDRESS> [The fdim functions]
1 Synopsis
#include <math.h>
double fdim(double x, double y);
float fdimf(float x, float y);
long double fdiml(long double x, long double y);
Description
2 The fdim functions determine the positive difference between their arguments:
x − y if x > y
+0 if x ≤ y
A range error may occur.
Returns
3 The fdim functions return the positive difference value.
<IP_ADDRESS> [The fmax functions]
1 Synopsis
#include <math.h>
double fmax(double x, double y);
float fmaxf(float x, float y);
long double fmaxl(long double x, long double y);
Description
2 The fmax functions determine the maximum numeric value of their arguments.[213]
Returns
Footnote 213) NaN arguments are treated as missing data: if one argument is a NaN and the other numeric, then the
fmax functions choose the numeric value. See F.9.9.2.
3 The fmax functions return the maximum numeric value of their arguments.
<IP_ADDRESS> [The fmin functions]
1 Synopsis
#include <math.h>
double fmin(double x, double y);
float fminf(float x, float y);
long double fminl(long double x, long double y);
Description
2 The fmin functions determine the minimum numeric value of their arguments.[214]
Returns
Footnote 214) The fmin functions are analogous to the fmax functions in their treatment of NaNs.
3 The fmin functions return the minimum numeric value of their arguments.
7.12.13 [Floating multiply-add]
<IP_ADDRESS> [The fma functions]
1 Synopsis
#include <math.h>
double fma(double x, double y, double z);
float fmaf(float x, float y, float z);
long double fmal(long double x, long double y,
long double z);
Description
2 The fma functions compute (x × y) + z, rounded as one ternary operation: they compute
the value (as if) to infinite precision and round once to the result format, according to the
current rounding mode. A range error may occur.
Returns
3 The fma functions return (x × y) + z, rounded as one ternary operation.
7.12.14 [Comparison macros]
1 The relational and equality operators support the usual mathematical relationships
between numeric values. For any ordered pair of numeric values exactly one of the
relationships — less, greater, and equal — is true. Relational operators may raise the
‘‘invalid’’ floating-point exception when argument values are NaNs. For a NaN and a
numeric value, or for two NaNs, just the unordered relationship is true.[215] The following
subclauses provide macros that are quiet (non floating-point exception raising) versions
of the relational operators, and other comparison macros that facilitate writing efficient
code that accounts for NaNs without suffering the ‘‘invalid’’ floating-point exception. In
the synopses in this subclause, real-floating indicates that the argument shall be an
expression of real floating type.
Footnote 215) IEC 60559 requires that the built-in relational operators raise the ‘‘invalid’’ floating-point exception if
the operands compare unordered, as an error indicator for programs written without consideration of
NaNs; the result in these cases is false.
<IP_ADDRESS> [The isgreater macro]
1 Synopsis
#include <math.h>
int isgreater(real-floating x, real-floating y);
Description
2 The isgreater macro determines whether its first argument is greater than its second
argument. The value of isgreater(x, y) is always equal to (x) > (y); however,
unlike (x) > (y), isgreater(x, y) does not raise the ‘‘invalid’’ floating-point
exception when x and y are unordered.
Returns
3 The isgreater macro returns the value of (x) > (y).
<IP_ADDRESS> [The isgreaterequal macro]
1 Synopsis
#include <math.h>
int isgreaterequal(real-floating x, real-floating y);
Description
2 The isgreaterequal macro determines whether its first argument is greater than or
equal to its second argument. The value of isgreaterequal(x, y) is always equal
to (x) >= (y); however, unlike (x) >= (y), isgreaterequal(x, y) does
not raise the ‘‘invalid’’ floating-point exception when x and y are unordered.
Returns
3 The isgreaterequal macro returns the value of (x) >= (y).
<IP_ADDRESS> [The isless macro]
1 Synopsis
#include <math.h>
int isless(real-floating x, real-floating y);
Description
2 The isless macro determines whether its first argument is less than its second
argument. The value of isless(x, y) is always equal to (x) < (y); however,
unlike (x) < (y), isless(x, y) does not raise the ‘‘invalid’’ floating-point
exception when x and y are unordered.
Returns
3 The isless macro returns the value of (x) < (y).
<IP_ADDRESS> [The islessequal macro]
1 Synopsis
#include <math.h>
int islessequal(real-floating x, real-floating y);
Description
2 The islessequal macro determines whether its first argument is less than or equal to
its second argument. The value of islessequal(x, y) is always equal to
(x) <= (y); however, unlike (x) <= (y), islessequal(x, y) does not raise
the ‘‘invalid’’ floating-point exception when x and y are unordered.
Returns
3 The islessequal macro returns the value of (x) <= (y).
<IP_ADDRESS> [The islessgreater macro]
1 Synopsis
#include <math.h>
int islessgreater(real-floating x, real-floating y);
Description
2 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
Returns
3 The islessgreater macro returns the value of (x) < (y) || (x) > (y).
<IP_ADDRESS> [The isunordered macro]
1 Synopsis
#include <math.h>
int isunordered(real-floating x, real-floating y);
Description
2 The isunordered macro determines whether its arguments are unordered.
Returns
3 The isunordered macro returns 1 if its arguments are unordered and 0 otherwise.
7.13 [Nonlocal jumps <setjmp.h>]
1 The header <setjmp.h> defines the macro setjmp, and declares one function and
one type, for bypassing the normal function call and return discipline.[216]
Footnote 216) These functions are useful for dealing with unusual conditions encountered in a low-level function of
a program.
2 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.
3 It is unspecified whether setjmp is a macro or an identifier declared with external
linkage. If a macro definition is suppressed in order to access an actual function, or a
program defines an external identifier with the name setjmp, the behavior is undefined.
7.13.1 [Save calling environment]
<IP_ADDRESS> [The setjmp macro]
1 Synopsis
#include <setjmp.h>
int setjmp(jmp_buf env);
Description
2 The setjmp macro saves its calling environment in its jmp_buf argument for later use
by the longjmp function.
Returns
3 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
4 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).
5 If the invocation appears in any other context, the behavior is undefined.
7.13.2 [Restore calling environment]
<IP_ADDRESS> [The longjmp function]
1 Synopsis
#include <setjmp.h>
void longjmp(jmp_buf env, int val);
Description
2 The longjmp function restores the environment saved by the most recent invocation of
the setjmp macro in the same invocation of the program with the corresponding
jmp_buf argument. If there has been no such invocation, or if the function containing
the invocation of the setjmp macro has terminated execution[217] in the interim, or if the
invocation of the setjmp macro was within the scope of an identifier with variably
modified type and execution has left that scope in the interim, the behavior is undefined.
Footnote 217) For example, by executing a return statement or because another longjmp call has caused a
transfer to a setjmp invocation in a function earlier in the set of nested calls.
3 All accessible objects have values, and all other components of the abstract machine[218]
have state, as of the time the longjmp function was called, except that the values of
objects of automatic storage duration that are local to the function containing the
invocation of the corresponding setjmp macro that do not have volatile-qualified type
and have been changed between the setjmp invocation and longjmp call are
indeterminate.
Returns
Footnote 218) This includes, but is not limited to, the floating-point status flags and the state of open files.
4 After longjmp is completed, program execution continues as if the corresponding
invocation of the setjmp macro had just returned the value specified by val. The
longjmp function cannot cause the setjmp macro to return the value 0; if val is 0,
the setjmp macro returns the value 1.
5 EXAMPLE The longjmp function that returns control back to the point of the setjmp invocation
might cause memory associated with a variable length array object to be squandered.
#include <setjmp.h>
jmp_buf buf;
void g(int n);
void h(int n);
int n = 6;
void f(void)
{
int x[n]; // valid: f is not terminated
setjmp(buf);
g(n);
}
void g(int n)
{
int a[n]; // a may remain allocated
h(n);
}
void h(int n)
{
int b[n]; // b may remain allocated
longjmp(buf, 2); // might cause memory loss
}
7.14 [Signal handling <signal.h>]
1 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).
2 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.
3 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
4 An implementation need not generate any of these signals, except as a result of explicit
calls to the raise function. Additional signals and pointers to undeclarable functions,
with macro definitions beginning, respectively, with the letters SIG and an uppercase
letter or with SIG_ and an uppercase letter,[219] may also be specified by the
implementation. The complete set of signals, their semantics, and their default handling
is implementation-defined; all signal numbers shall be positive.
Footnote 219) See ‘‘future library directions’’ (7.26.9). The names of the signal numbers reflect the following terms
(respectively): abort, floating-point exception, illegal instruction, interrupt, segmentation violation,
and termination.
7.14.1 [Specify signal handling]
<IP_ADDRESS> [The signal function]
1 Synopsis
#include <signal.h>
void (*signal(int sig, void (*func)(int)))(int);
Description
2 The signal function chooses one of three ways in which receipt of the signal number
sig is to be subsequently handled. If the value of func is SIG_DFL, default handling
for that signal will occur. If the value of func is SIG_IGN, the signal will be ignored.
Otherwise, func shall point to a function to be called when that signal occurs. An
invocation of such a function because of a signal, or (recursively) of any further functions
called by that invocation (other than functions in the standard library), is called a signal
handler.
3 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.
4 If the signal occurs as the result of calling the abort or raise function, the signal
handler shall not call the raise function.
5 If the signal occurs other than as the result of calling the abort or raise function, the
behavior is undefined if the signal handler refers to any object with static storage duration
other than by assigning a value to an object declared as volatile sig_atomic_t, or
the signal handler calls any function in the standard library other than the abort
function, the _Exit function, or the signal function with the first argument equal to
the signal number corresponding to the signal that caused the invocation of the handler.
Furthermore, if such a call to the signal function results in a SIG_ERR return, the
value of errno is indeterminate.[220]
Footnote 220) If any signal is generated by an asynchronous signal handler, the behavior is undefined.
6 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.
7 The implementation shall behave as if no library function calls the signal function.
Returns
8 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 (<IP_ADDRESS>), the exit function (<IP_ADDRESS>), the
_Exit function (<IP_ADDRESS>).
7.14.2 [Send signal]
<IP_ADDRESS> [The raise function]
1 Synopsis
#include <signal.h>
int raise(int sig);
Description
2 The raise function carries out the actions described in <IP_ADDRESS> for the signal sig. If a
signal handler is called, the raise function shall not return until after the signal handler
does.
Returns
3 The raise function returns zero if successful, nonzero if unsuccessful.
7.15 [Variable arguments <stdarg.h>]
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.
2 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.
3 The type declared is
va_list
which is an object type suitable for holding information needed by the macros
va_start, va_arg, va_end, and va_copy. If access to the varying arguments is
desired, the called function shall declare an object (generally referred to as ap in this
subclause) having type va_list. The object ap may be passed as an argument to
another function; if that function invokes the va_arg macro with parameter ap, the
value of ap in the calling function is indeterminate and shall be passed to the va_end
macro prior to any further reference to ap.[221]
Footnote 221) It is permitted to create a pointer to a va_list and pass that pointer to another function, in which
case the original function may make further use of the original list after the other function returns.
7.15.1 [Variable argument list access macros]
1 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.
<IP_ADDRESS> [The va_arg macro]
1 Synopsis
#include <stdarg.h>
type va_arg(va_list ap, type);
Description
2 The va_arg macro expands to an expression that has the specified type and the value of
the next argument in the call. The parameter ap shall have been initialized by the
va_start or va_copy macro (without an intervening invocation of the va_end
macro for the same ap). Each invocation of the va_arg macro modifies ap so that the
values of successive arguments are returned in turn. The parameter type shall be a type
name specified such that the type of a pointer to an object that has the specified type can
be obtained simply by postfixing a * to type. If there is no actual next argument, or if
type is not compatible with the type of the actual next argument (as promoted according
to the default argument promotions), the behavior is undefined, except for the following
cases:
— one type is a signed integer type, the other type is the corresponding unsigned integer
type, and the value is representable in both types;
— one type is pointer to void and the other is a pointer to a character type.
Returns
3 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.
<IP_ADDRESS> [The va_copy macro]
1 Synopsis
#include <stdarg.h>
void va_copy(va_list dest, va_list src);
Description
2 The va_copy macro initializes dest as a copy of src, as if the va_start macro had
been applied to dest followed by the same sequence of uses of the va_arg macro as
had previously been used to reach the present state of src. Neither the va_copy nor
va_start macro shall be invoked to reinitialize dest without an intervening
invocation of the va_end macro for the same dest.
Returns
3 The va_copy macro returns no value.
<IP_ADDRESS> [The va_end macro]
1 Synopsis
#include <stdarg.h>
void va_end(va_list ap);
Description
2 The va_end macro facilitates a normal return from the function whose variable
argument list was referred to by the expansion of the va_start macro, or the function
containing the expansion of the va_copy macro, that initialized the va_list ap. The
va_end macro may modify ap so that it is no longer usable (without being reinitialized
by the va_start or va_copy macro). If there is no corresponding invocation of the
va_start or va_copy macro, or if the va_end macro is not invoked before the
return, the behavior is undefined.
Returns
3 The va_end macro returns no value.
<IP_ADDRESS> [The va_start macro]
1 Synopsis
#include <stdarg.h>
void va_start(va_list ap, parmN);
Description
2 The va_start macro shall be invoked before any access to the unnamed arguments.
3 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.
4 The parameter parmN is the identifier of the rightmost parameter in the variable
parameter list in the function definition (the one just before the , ...). If the parameter
parmN is declared with the register storage class, with a function or array type, or
with a type that is not compatible with the type that results after application of the default
argument promotions, the behavior is undefined.
Returns
5 The va_start macro returns no value.
6 EXAMPLE 1 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, ...);
7 EXAMPLE 2 The function f3 is similar, but saves the status of the variable argument list after the
indicated number of arguments; after f2 has been called once with the whole list, the trailing part of the list
is gathered again and passed to function f4.
#include <stdarg.h>
#define MAXARGS 31
void f3(int n_ptrs, int f4_after, ...)
{
va_list ap, ap_save;
char *array[MAXARGS];
int ptr_no = 0;
if (n_ptrs > MAXARGS)
n_ptrs = MAXARGS;
va_start(ap, f4_after);
while (ptr_no < n_ptrs) {
array[ptr_no++] = va_arg(ap, char *);
if (ptr_no == f4_after)
va_copy(ap_save, ap);
}
va_end(ap);
f2(n_ptrs, array);
// Now process the saved copy.
n_ptrs -= f4_after;
ptr_no = 0;
while (ptr_no < n_ptrs)
array[ptr_no++] = va_arg(ap_save, char *);
va_end(ap_save);
f4(n_ptrs, array);
}
7.16 [Boolean type and values <stdbool.h>]
1 The header <stdbool.h> defines four macros.
2 The macro
bool
expands to _Bool.
3 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.
4 Notwithstanding the provisions of 7.1.3, a program may undefine and perhaps then
redefine the macros bool, true, and false.[222]
Footnote 222) See ‘‘future library directions’’ (7.26.7).
7.17 [Common definitions <stddef.h>]
1 The following types and macros are defined in the standard header <stddef.h>. Some
are also defined in other headers, as noted in their respective subclauses.
2 The types are
ptrdiff_t
which is the signed integer type of the result of subtracting two pointers;
size_t
which is the unsigned integer type of the result of the sizeof operator; and
wchar_t
which is an integer type whose range of values can represent distinct codes for all
members of the largest extended character set specified among the supported locales; the
null character shall have the code value zero. Each member of the basic character set
shall have a code value equal to its value when used as the lone character in an integer
character constant if an implementation does not define
_ _STDC_MB_MIGHT_NEQ_WC_ _.
3 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
4 The types used for size_t and ptrdiff_t should not have an integer conversion rank
greater than that of signed long int unless the implementation supports objects
large enough to make this necessary.
Forward references: localization (7.11).
7.18 [Integer types <stdint.h>]
1 The header <stdint.h> declares sets of integer types having specified widths, and
defines corresponding sets of macros.[223] It also defines macros that specify limits of
integer types corresponding to types defined in other standard headers.
Footnote 223) See ‘‘future library directions’’ (7.26.8).
2 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.)
3 Corresponding macros specify limits of the declared types and construct suitable
constants.
4 For each type described herein that the implementation provides,[224] <stdint.h> shall
declare that typedef name and define the associated macros. Conversely, for each type
described herein that the implementation does not provide, <stdint.h> shall not
declare that typedef name nor shall it define the associated macros. An implementation
shall provide those types described as ‘‘required’’, but need not provide any of the others
(described as ‘‘optional’’).
Footnote 224) Some of these types may denote implementation-defined extended integer types.
7.18.1 [Integer types]
1 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.
2 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).
<IP_ADDRESS> [Exact-width integer types]
1 The typedef name intN_t designates a signed integer type with width N , no padding
bits, and a two’s complement representation. Thus, int8_t denotes a signed integer
type with a width of exactly 8 bits.
2 The typedef name uintN_t designates an unsigned integer type with width N . Thus,
uint24_t denotes an unsigned integer type with a width of exactly 24 bits.
3 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.
<IP_ADDRESS> [Minimum-width integer types]
1 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.
2 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.
3 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.
<IP_ADDRESS> [Fastest minimum-width integer types]
1 Each of the following types designates an integer type that is usually fastest[225] to operate
with among all integer types that have at least the specified width.
Footnote 225) The designated type is not guaranteed to be fastest for all purposes; if the implementation has no clear
grounds for choosing one type over another, it will simply pick some integer type satisfying the
signedness and width requirements.
2 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 .
3 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.
<IP_ADDRESS> [Integer types capable of holding object pointers]
1 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.
<IP_ADDRESS> [Greatest-width integer types]
1 The following type designates a signed integer type capable of representing any value of
any signed integer type:
intmax_t
The following type designates an unsigned integer type capable of representing any value
of any unsigned integer type:
uintmax_t
These types are required.
7.18.2 [Limits of specified-width integer types]
1 The following object-like macros[226] specify the minimum and maximum limits of the
types declared in <stdint.h>. Each macro name corresponds to a similar type name in
7.18.1.
Footnote 226) C++ implementations should define these macros only when _ _STDC_LIMIT_MACROS is defined
before <stdint.h> is included.
2 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.
<IP_ADDRESS> [Limits of exact-width integer types]
1 — 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
<IP_ADDRESS> [Limits of minimum-width integer types]
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
<IP_ADDRESS> [Limits of fastest minimum-width integer types]
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
<IP_ADDRESS> [Limits of integer types capable of holding object pointers]
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
<IP_ADDRESS> [Limits of greatest-width integer types]
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
7.18.3 [Limits of other integer types]
1 The following object-like macros[227] specify the minimum and maximum limits of
integer types corresponding to types defined in other standard headers.
Footnote 227) C++ implementations should define these macros only when _ _STDC_LIMIT_MACROS is defined
before <stdint.h> is included.
2 Each instance of these macros shall be replaced by a constant expression suitable for use
in #if preprocessing directives, and this expression shall have the same type as would an
expression that is an object of the corresponding type converted according to the integer
promotions. Its implementation-defined value shall be equal to or greater in magnitude
(absolute value) than the corresponding value given below, with the same sign. An
implementation shall define only the macros corresponding to those typedef names it
actually provides.[228]
— limits of ptrdiff_t
PTRDIFF_MIN −65535
PTRDIFF_MAX +65535
— limits of sig_atomic_t
SIG_ATOMIC_MIN see below
SIG_ATOMIC_MAX see below
— limit of size_t
SIZE_MAX 65535
— limits of wchar_t
WCHAR_MIN see below
WCHAR_MAX see below
— limits of wint_t
WINT_MIN see below
WINT_MAX see below
Footnote 228) A freestanding implementation need not provide all of these types.
3 If sig_atomic_t (see 7.14) 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.
4 If wchar_t (see 7.17) is defined as a signed integer type, the value of WCHAR_MIN
shall be no greater than −127 and the value of WCHAR_MAX shall be no less than 127;
otherwise, wchar_t is defined as an unsigned integer type, and the value of
WCHAR_MIN shall be 0 and the value of WCHAR_MAX shall be no less than 255.[229]
Footnote 229) The values WCHAR_MIN and WCHAR_MAX do not necessarily correspond to members of the extended
character set.
5 If wint_t (see 7.24) is defined as a signed integer type, the value of WINT_MIN shall
be no greater than −32767 and the value of WINT_MAX shall be no less than 32767;
otherwise, wint_t is defined as an unsigned integer type, and the value of WINT_MIN
shall be 0 and the value of WINT_MAX shall be no less than 65535.
7.18.4 [Macros for integer constants]
1 The following function-like macros[230] expand to integer constants suitable for
initializing objects that have integer types corresponding to types defined in
<stdint.h>. Each macro name corresponds to a similar type name in <IP_ADDRESS> or
<IP_ADDRESS>.
Footnote 230) C++ implementations should define these macros only when _ _STDC_CONSTANT_MACROS is
defined before <stdint.h> is included.
2 The argument in any instance of these macros shall be an unsuffixed integer constant (as
defined in <IP_ADDRESS>) with a value that does not exceed the limits for the corresponding type.
3 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.
<IP_ADDRESS> [Macros for minimum-width integer constants]
1 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.
<IP_ADDRESS> [Macros for greatest-width integer constants]
1 The following macro expands to an integer constant expression having the value specified
by its argument and the type intmax_t:
INTMAX_C(value)
The following macro expands to an integer constant expression having the value specified
by its argument and the type uintmax_t:
UINTMAX_C(value)
7.19 [Input/output <stdio.h>]
7.19.1 [Introduction]
1 The header <stdio.h> declares three types, several macros, and many functions for
performing input and output.
2 The types declared are size_t (described in 7.17);
FILE
which is an object type capable of recording all the information needed to control a
stream, including its file position indicator, a pointer to its associated buffer (if any), an
error indicator that records whether a read/write error has occurred, and an end-of-file
indicator that records whether the end of the file has been reached; and
fpos_t
which is an object type other than an array type capable of recording all the information
needed to specify uniquely every position within a file.
3 The macros are NULL (described in 7.17);
_IOFBF
_IOLBF
_IONBF
which expand to integer constant expressions with distinct values, suitable for use as the
third argument to the setvbuf function;
BUFSIZ
which expands to an integer constant expression that is the size of the buffer used by the
setbuf function;
EOF
which expands to an integer constant expression, with type int and a negative value, that
is returned by several functions to indicate end-of-file, that is, no more input from a
stream;
FOPEN_MAX
which expands to an integer constant expression that is the minimum number of files that
the implementation guarantees can be open simultaneously;
FILENAME_MAX
which expands to an integer constant expression that is the size needed for an array of
char large enough to hold the longest file name string that the implementation
guarantees can be opened;[231]
L_tmpnam
which expands to an integer constant expression that is the size needed for an array of
char large enough to hold a temporary file name string generated by the tmpnam
function;
SEEK_CUR
SEEK_END
SEEK_SET
which expand to integer constant expressions with distinct values, suitable for use as the
third argument to the fseek function;
TMP_MAX
which expands to an integer constant expression that is the maximum number of unique
file names that can be generated by the tmpnam function;
stderr
stdin
stdout
which are expressions of type ‘‘pointer to FILE’’ that point to the FILE objects
associated, respectively, with the standard error, input, and output streams.
Footnote 231) If the implementation imposes no practical limit on the length of file name strings, the value of
FILENAME_MAX should instead be the recommended size of an array intended to hold a file name
string. Of course, file name string contents are subject to other system-specific constraints; therefore
all possible strings of length FILENAME_MAX cannot be expected to be opened successfully.
4 The header <wchar.h> declares a number of functions useful for wide character input
and output. The wide character input/output functions described in that subclause
provide operations analogous to most of those described here, except that the
fundamental units internal to the program are wide characters. The external
representation (in the file) is a sequence of ‘‘generalized’’ multibyte characters, as
described further in 7.19.3.
5 The input/output functions are given the following collective terms:
— The wide character input functions — those functions described in 7.24 that perform
input into wide characters and wide strings: fgetwc, fgetws, getwc, getwchar,
fwscanf, wscanf, vfwscanf, and vwscanf.
— The wide character output functions — those functions described in 7.24 that perform
output from wide characters and wide strings: fputwc, fputws, putwc,
putwchar, fwprintf, wprintf, vfwprintf, and vwprintf.
— The wide character input/output functions — the union of the ungetwc function, the
wide character input functions, and the wide character output functions.
— The byte input/output functions — those functions described in this subclause that
perform input/output: fgetc, fgets, fprintf, fputc, fputs, fread,
fscanf, fwrite, getc, getchar, gets, printf, putc, putchar, puts,
scanf, ungetc, vfprintf, vfscanf, vprintf, and vscanf.
Forward references: files (7.19.3), the fseek function (<IP_ADDRESS>), streams (7.19.2), the
tmpnam function (<IP_ADDRESS>), <wchar.h> (7.24).
7.19.2 [Streams]
1 Input and output, whether to or from physical devices such as terminals and tape drives,
or whether to or from files supported on structured storage devices, are mapped into
logical data streams, whose properties are more uniform than their various inputs and
outputs. Two forms of mapping are supported, for text streams and for binary
streams.[232]
Footnote 232) An implementation need not distinguish between text streams and binary streams. In such an
implementation, there need be no new-line characters in a text stream nor any limit to the length of a
line.
2 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.
3 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.
4 Each stream has an orientation. After a stream is associated with an external file, but
before any operations are performed on it, the stream is without orientation. Once a wide
character input/output function has been applied to a stream without orientation, the
stream becomes a wide-oriented stream. Similarly, once a byte input/output function has
been applied to a stream without orientation, the stream becomes a byte-oriented stream.
Only a call to the freopen function or the fwide function can otherwise alter the
orientation of a stream. (A successful call to freopen removes any orientation.)[233]
Footnote 233) The three predefined streams stdin, stdout, and stderr are unoriented at program startup.
5 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.
6 Each wide-oriented stream has an associated mbstate_t object that stores the current
parse state of the stream. A successful call to fgetpos stores a representation of the
value of this mbstate_t object as part of the value of the fpos_t object. A later
successful call to fsetpos using the same stored fpos_t value restores the value of
the associated mbstate_t object as well as the position within the controlled stream.
Environmental limits
7 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 (<IP_ADDRESS>), the fwide function (<IP_ADDRESS>),
mbstate_t (7.25.1), the fgetpos function (<IP_ADDRESS>), the fsetpos function
(<IP_ADDRESS>).
7.19.3 [Files]
1 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.
2 Binary files are not truncated, except as defined in <IP_ADDRESS>. Whether a write on a text
stream causes the associated file to be truncated beyond that point is implementation-
defined.
3 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.
4 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.
5 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.
6 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.
7 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.
8 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.
9 Although both text and binary wide-oriented streams are conceptually sequences of wide
characters, the external file associated with a wide-oriented stream is a sequence of
multibyte characters, generalized as follows:
— Multibyte encodings within files may contain embedded null bytes (unlike multibyte
encodings valid for use internal to the program).
— A file need not begin nor end in the initial shift state.[234]
Footnote 234) Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has
undefined behavior for a binary stream (because of possible trailing null characters) or for any stream
with state-dependent encoding that does not assuredly end in the initial shift state.
10 Moreover, the encodings used for multibyte characters may differ among files. Both the
nature and choice of such encodings are implementation-defined.
11 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.
12 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.
13 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.
14 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
15 The value of FOPEN_MAX shall be at least eight, including the three standard text
streams.
Forward references: the exit function (<IP_ADDRESS>), the fgetc function (<IP_ADDRESS>), the
fopen function (<IP_ADDRESS>), the fputc function (<IP_ADDRESS>), the setbuf function
(<IP_ADDRESS>), the setvbuf function (<IP_ADDRESS>), the fgetwc function (<IP_ADDRESS>), the
fputwc function (<IP_ADDRESS>), conversion state (7.24.6), the mbrtowc function
(<IP_ADDRESS>.2), the wcrtomb function (<IP_ADDRESS>.3).
7.19.4 [Operations on files]
<IP_ADDRESS> [The remove function]
1 Synopsis
#include <stdio.h>
int remove(const char *filename);
Description
2 The remove function causes the file whose name is the string pointed to by filename
to be no longer accessible by that name. A subsequent attempt to open that file using that
name will fail, unless it is created anew. If the file is open, the behavior of the remove
function is implementation-defined.
Returns
3 The remove function returns zero if the operation succeeds, nonzero if it fails.
<IP_ADDRESS> [The rename function]
1 Synopsis
#include <stdio.h>
int rename(const char *old, const char *new);
Description
2 The rename function causes the file whose name is the string pointed to by old to be
henceforth known by the name given by the string pointed to by new. The file named
old is no longer accessible by that name. If a file named by the string pointed to by new
exists prior to the call to the rename function, the behavior is implementation-defined.
Returns
3 The rename function returns zero if the operation succeeds, nonzero if it fails,[235] in
which case if the file existed previously it is still known by its original name.
Footnote 235) Among the reasons the implementation may cause the rename function to fail are that the file is open
or that it is necessary to copy its contents to effectuate its renaming.
<IP_ADDRESS> [The tmpfile function]
1 Synopsis
#include <stdio.h>
FILE *tmpfile(void);
Description
2 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
3 It should be possible to open at least TMP_MAX temporary files during the lifetime of the
program (this limit may be shared with tmpnam) and there should be no limit on the
number simultaneously open other than this limit and any limit on the number of open
files (FOPEN_MAX).
Returns
4 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 (<IP_ADDRESS>).
<IP_ADDRESS> [The tmpnam function]
1 Synopsis
#include <stdio.h>
char *tmpnam(char *s);
Description
2 The tmpnam function generates a string that is a valid file name and that is not the same
as the name of an existing file.[236] The function is potentially capable of generating
TMP_MAX different strings, but any or all of them may already be in use by existing files
and thus not be suitable return values.
Footnote 236) Files created using strings generated by the tmpnam function are temporary only in the sense that
their names should not collide with those generated by conventional naming rules for the
implementation. It is still necessary to use the remove function to remove such files when their use
is ended, and before program termination.
3 The tmpnam function generates a different string each time it is called.
4 The implementation shall behave as if no library function calls the tmpnam function.
Returns
5 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
6 The value of the macro TMP_MAX shall be at least 25.
7.19.5 [File access functions]
<IP_ADDRESS> [The fclose function]
1 Synopsis
#include <stdio.h>
int fclose(FILE *stream);
Description
2 A successful call to the fclose function causes the stream pointed to by stream to be
flushed and the associated file to be closed. Any unwritten buffered data for the stream
are delivered to the host environment to be written to the file; any unread buffered data
are discarded. Whether or not the call succeeds, the stream is disassociated from the file
and any buffer set by the setbuf or setvbuf function is disassociated from the stream
(and deallocated if it was automatically allocated).
Returns
3 The fclose function returns zero if the stream was successfully closed, or EOF if any
errors were detected.
<IP_ADDRESS> [The fflush function]
1 Synopsis
#include <stdio.h>
int fflush(FILE *stream);
Description
2 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.
3 If stream is a null pointer, the fflush function performs this flushing action on all
streams for which the behavior is defined above.
Returns
4 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 (<IP_ADDRESS>).
<IP_ADDRESS> [The fopen function]
1 Synopsis
#include <stdio.h>
FILE *fopen(const char * restrict filename,
const char * restrict mode);
Description
2 The fopen function opens the file whose name is the string pointed to by filename,
and associates a stream with it.
3 The argument mode points to a string. If the string is one of the following, the file is
open in the indicated mode. Otherwise, the behavior is undefined.[237]
r open text file for reading
w truncate to zero length or create text file for writing
a append; open or create text file for writing at end-of-file
rb open binary file for reading
wb truncate to zero length or create binary file for writing
ab append; open or create binary file for writing at end-of-file
r+ open text file for update (reading and writing)
w+ truncate to zero length or create text file for update
a+ append; open or create text file for update, writing at end-of-file
r+b or rb+ open binary file for update (reading and writing)
w+b or wb+ truncate to zero length or create binary file for update
a+b or ab+ append; open or create binary file for update, writing at end-of-file
Footnote 237) If the string begins with one of the above sequences, the implementation might choose to ignore the
remaining characters, or it might use them to select different kinds of a file (some of which might not
conform to the properties in 7.19.2).
4 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.
5 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.
6 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.
7 When opened, a stream is fully buffered if and only if it can be determined not to refer to
an interactive device. The error and end-of-file indicators for the stream are cleared.
Returns
8 The fopen function returns a pointer to the object controlling the stream. If the open
operation fails, fopen returns a null pointer.
Forward references: file positioning functions (7.19.9).
<IP_ADDRESS> [The freopen function]
1 Synopsis
#include <stdio.h>
FILE *freopen(const char * restrict filename,
const char * restrict mode,
FILE * restrict stream);
Description
2 The freopen function opens the file whose name is the string pointed to by filename
and associates the stream pointed to by stream with it. The mode argument is used just
as in the fopen function.[238]
Footnote 238) The primary use of the freopen function is to change the file associated with a standard text stream
(stderr, stdin, or stdout), as those identifiers need not be modifiable lvalues to which the value
returned by the fopen function may be assigned.
3 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.
4 The freopen function first attempts to close any file that is associated with the specified
stream. Failure to close the file is ignored. The error and end-of-file indicators for the
stream are cleared.
Returns
5 The freopen function returns a null pointer if the open operation fails. Otherwise,
freopen returns the value of stream.
<IP_ADDRESS> [The setbuf function]
1 Synopsis
#include <stdio.h>
void setbuf(FILE * restrict stream,
char * restrict buf);
Description
2 Except that it returns no value, the setbuf function is equivalent to the setvbuf
function invoked with the values _IOFBF for mode and BUFSIZ for size, or (if buf
is a null pointer), with the value _IONBF for mode.
Returns
3 The setbuf function returns no value.
Forward references: the setvbuf function (<IP_ADDRESS>).
<IP_ADDRESS> [The setvbuf function]
1 Synopsis
#include <stdio.h>
int setvbuf(FILE * restrict stream,
char * restrict buf,
int mode, size_t size);
Description
2 The setvbuf function may be used only after the stream pointed to by stream has
been associated with an open file and before any other operation (other than an
unsuccessful call to setvbuf) is performed on the stream. The argument mode
determines how stream will be buffered, as follows: _IOFBF causes input/output to be
fully buffered; _IOLBF causes input/output to be line buffered; _IONBF causes
input/output to be unbuffered. If buf is not a null pointer, the array it points to may be
used instead of a buffer allocated by the setvbuf function[239] and the argument size
specifies the size of the array; otherwise, size may determine the size of a buffer
allocated by the setvbuf function. The contents of the array at any time are
indeterminate.
Returns
Footnote 239) The buffer has to have a lifetime at least as great as the open stream, so the stream should be closed
before a buffer that has automatic storage duration is deallocated upon block exit.
3 The setvbuf function returns zero on success, or nonzero if an invalid value is given
for mode or if the request cannot be honored.
7.19.6 [Formatted input/output functions]
1 The formatted input/output functions shall behave as if there is a sequence point after the
actions associated with each specifier.[240]
Footnote 240) The fprintf functions perform writes to memory for the %n specifier.
<IP_ADDRESS> [The fprintf function]
1 Synopsis
#include <stdio.h>
int fprintf(FILE * restrict stream,
const char * restrict format, ...);
Description
2 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.
3 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.
4 Each conversion specification is introduced by the character %. After the %, the following
appear in sequence:
— Zero or more flags (in any order) that modify the meaning of the conversion
specification.
— An optional minimum field width. If the converted value has fewer characters than the
field width, it is padded with spaces (by default) on the left (or right, if the left
adjustment flag, described later, has been given) to the field width. The field width
takes the form of an asterisk * (described later) or a nonnegative decimal integer.[241]
— An optional precision that gives the minimum number of digits to appear for the d, i,
o, u, x, and X conversions, the number of digits to appear after the decimal-point
character for a, A, e, E, f, and F conversions, the maximum number of significant
digits for the g and G conversions, or the maximum number of bytes to be written for
s conversions. The precision takes the form of a period (.) followed either by an
asterisk * (described later) or by an optional decimal integer; if only the period is
specified, the precision is taken as zero. If a precision appears with any other
conversion specifier, the behavior is undefined.
— An optional length modifier that specifies the size of the argument.
— A conversion specifier character that specifies the type of conversion to be applied.
Footnote 241) Note that 0 is taken as a flag, not as the beginning of a field width.
5 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.
6 The flag characters and their meanings are:
- The result of the conversion is left-justified within the field. (It is right-justified if
this flag is not specified.)
+ The result of a signed conversion always begins with a plus or minus sign. (It
begins with a sign only when a negative value is converted if this flag is not
specified.)[242]
space If the first character of a signed conversion is not a sign, or if a signed conversion
results in no characters, a space is prefixed to the result. If the space and + flags
both appear, the space flag is ignored.
# The result is converted to an ‘‘alternative form’’. For o conversion, it increases
the precision, if and only if necessary, to force the first digit of the result to be a
zero (if the value and precision are both 0, a single 0 is printed). For x (or X)
conversion, a nonzero result has 0x (or 0X) prefixed to it. For a, A, e, E, f, F, g,
and G conversions, the result of converting a floating-point number always
contains a decimal-point character, even if no digits follow it. (Normally, a
decimal-point character appears in the result of these conversions only if a digit
follows it.) For g and G conversions, trailing zeros are not removed from the
result. For other conversions, the behavior is undefined.
0 For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, leading zeros
(following any indication of sign or base) are used to pad to the field width rather
than performing space padding, except when converting an infinity or NaN. If the
0 and - flags both appear, the 0 flag is ignored. For d, i, o, u, x, and X
conversions, if a precision is specified, the 0 flag is ignored. For other
conversions, the behavior is undefined.
Footnote 242) The results of all floating conversions of a negative zero, and of negative values that round to zero,
include a minus sign.
7 The length modifiers and their meanings are:
hh Specifies that a following d, i, o, u, x, or X conversion specifier applies to a
signed char or unsigned char argument (the argument will have
been promoted according to the integer promotions, but its value shall be
converted to signed char or unsigned char before printing); or that
a following n conversion specifier applies to a pointer to a signed char
argument.
h Specifies that a following d, i, o, u, x, or X conversion specifier applies to a
short int or unsigned short int argument (the argument will
have been promoted according to the integer promotions, but its value shall
be converted to short int or unsigned short int before printing);
or that a following n conversion specifier applies to a pointer to a short
int argument.
l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a
long int or unsigned long int argument; that a following n
conversion specifier applies to a pointer to a long int argument; that a
following c conversion specifier applies to a wint_t argument; that a
following s conversion specifier applies to a pointer to a wchar_t
argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion
specifier.
ll (ell-ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a
long long int or unsigned long long int argument; or that a
following n conversion specifier applies to a pointer to a long long int
argument.
j Specifies that a following d, i, o, u, x, or X conversion specifier applies to
an intmax_t or uintmax_t argument; or that a following n conversion
specifier applies to a pointer to an intmax_t argument.
z Specifies that a following d, i, o, u, x, or X conversion specifier applies to a
size_t or the corresponding signed integer type argument; or that a
following n conversion specifier applies to a pointer to a signed integer type
corresponding to size_t argument.
t Specifies that a following d, i, o, u, x, or X conversion specifier applies to a
ptrdiff_t or the corresponding unsigned integer type argument; or that a
following n conversion specifier applies to a pointer to a ptrdiff_t
argument.
L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier
applies to a long double argument.
If a length modifier appears with any conversion specifier other than as specified above,
the behavior is undefined.
8 The conversion specifiers and their meanings are:
d,i The int argument is converted to signed decimal in the style [−]dddd. The
precision specifies the minimum number of digits to appear; if the value
being converted can be represented in fewer digits, it is expanded with
leading zeros. The default precision is 1. The result of converting a zero
value with a precision of zero is no characters.
o,u,x,X The unsigned int argument is converted to unsigned octal (o), unsigned
decimal (u), or unsigned hexadecimal notation (x or X) in the style dddd; the
letters abcdef are used for x conversion and the letters ABCDEF for X
conversion. The precision specifies the minimum number of digits to appear;
if the value being converted can be represented in fewer digits, it is expanded
with leading zeros. The default precision is 1. The result of converting a
zero value with a precision of zero is no characters.
f,F A double argument representing a floating-point number is converted to
decimal notation in the style [−]ddd.ddd, where the number of digits after
the decimal-point character is equal to the precision specification. If the
precision is missing, it is taken as 6; if the precision is zero and the # flag is
not specified, no decimal-point character appears. If a decimal-point
character appears, at least one digit appears before it. The value is rounded to
the appropriate number of digits.
A double argument representing an infinity is converted in one of the styles
[-]inf or [-]infinity — which style is implementation-defined. A
double argument representing a NaN is converted in one of the styles
[-]nan or [-]nan(n-char-sequence) — which style, and the meaning of
any n-char-sequence, is implementation-defined. The F conversion specifier
produces INF, INFINITY, or NAN instead of inf, infinity, or nan,
respectively.[243]
e,E A double argument representing a floating-point number is converted in the
style [−]d.ddd e±dd, where there is one digit (which is nonzero if the
argument is nonzero) before the decimal-point character and the number of
digits after it is equal to the precision; if the precision is missing, it is taken as
6; if the precision is zero and the # flag is not specified, no decimal-point
character appears. The value is rounded to the appropriate number of digits.
The E conversion specifier produces a number with E instead of e
introducing the exponent. The exponent always contains at least two digits,
and only as many more digits as necessary to represent the exponent. If the
value is zero, the exponent is zero.
A double argument representing an infinity or NaN is converted in the style
of an f or F conversion specifier.
g,G A double argument representing a floating-point number is converted in
style f or e (or in style F or E in the case of a G conversion specifier),
depending on the value converted and the precision. Let P equal the
precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero.
Then, if a conversion with style E would have an exponent of X :
— if P > X ≥ −4, the conversion is with style f (or F) and precision
P − (X + 1).
— otherwise, the conversion is with style e (or E) and precision P − 1.
Finally, unless the # flag is used, any trailing zeros are removed from the
fractional portion of the result and the decimal-point character is removed if
there is no fractional portion remaining.
A double argument representing an infinity or NaN is converted in the style
of an f or F conversion specifier.
a,A A double argument representing a floating-point number is converted in the
style [−]0xh.hhhh p±d, where there is one hexadecimal digit (which is
nonzero if the argument is a normalized floating-point number and is
otherwise unspecified) before the decimal-point character[244] and the number
of hexadecimal digits after it is equal to the precision; if the precision is
missing and FLT_RADIX is a power of 2, then the precision is sufficient for
an exact representation of the value; if the precision is missing and
FLT_RADIX is not a power of 2, then the precision is sufficient to
distinguish[245] values of type double, except that trailing zeros may be
omitted; if the precision is zero and the # flag is not specified, no decimal-
point character appears. The letters abcdef are used for a conversion and
the letters ABCDEF for A conversion. The A conversion specifier produces a
number with X and P instead of x and p. The exponent always contains at
least one digit, and only as many more digits as necessary to represent the
decimal exponent of 2. If the value is zero, the exponent is zero.
A double argument representing an infinity or NaN is converted in the style
of an f or F conversion specifier.
c If no l length modifier is present, the int argument is converted to an
unsigned char, and the resulting character is written.
If an l length modifier is present, the wint_t argument is converted as if by
an ls conversion specification with no precision and an argument that points
to the initial element of a two-element array of wchar_t, the first element
containing the wint_t argument to the lc conversion specification and the
second a null wide character.
s If no l length modifier is present, the argument shall be a pointer to the initial
element of an array of character type.[246] Characters from the array are
written up to (but not including) the terminating null character. If the
precision is specified, no more than that many bytes are written. If the
precision is not specified or is greater than the size of the array, the array shall
contain a null character.
If an l length modifier is present, the argument shall be a pointer to the initial
element of an array of wchar_t type. Wide characters from the array are
converted to multibyte characters (each as if by a call to the wcrtomb
function, with the conversion state described by an mbstate_t object
initialized to zero before the first wide character is converted) up to and
including a terminating null wide character. The resulting multibyte
characters are written up to (but not including) the terminating null character
(byte). If no precision is specified, the array shall contain a null wide
character. If a precision is specified, no more than that many bytes are
written (including shift sequences, if any), and the array shall contain a null
wide character if, to equal the multibyte character sequence length given by
the precision, the function would need to access a wide character one past the
end of the array. In no case is a partial multibyte character written.[247]
p The argument shall be a pointer to void. The value of the pointer is
converted to a sequence of printing characters, in an implementation-defined
manner.
n The argument shall be a pointer to signed integer into which is written the
number of characters written to the output stream so far by this call to
fprintf. No argument is converted, but one is consumed. If the conversion
specification includes any flags, a field width, or a precision, the behavior is
undefined.
% A % character is written. No argument is converted. The complete
conversion specification shall be %%.
Footnote 243) When applied to infinite and NaN values, the -, +, and space flag characters have their usual meaning;
the # and 0 flag characters have no effect.
Footnote 244) Binary implementations can choose the hexadecimal digit to the left of the decimal-point character so
that subsequent digits align to nibble (4-bit) boundaries.
Footnote 245) The precision p is sufficient to distinguish values of the source type if 16 p−1 > b n where b is
FLT_RADIX and n is the number of base-b digits in the significand of the source type. A smaller p
might suffice depending on the implementation’s scheme for determining the digit to the left of the
decimal-point character.
Footnote 246) No special provisions are made for multibyte characters.
Footnote 247) Redundant shift sequences may result if multibyte characters have a state-dependent encoding.
9 If a conversion specification is invalid, the behavior is undefined.[248] If any argument is
not the correct type for the corresponding conversion specification, the behavior is
undefined.
Footnote 248) See ‘‘future library directions’’ (7.26.9).
10 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.
11 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
12 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.
13 For e, E, f, F, g, and G conversions, if the number of significant decimal digits is at most
DECIMAL_DIG, then the result should be correctly rounded.[249] If the number of
significant decimal digits is more than DECIMAL_DIG but the source value is exactly
representable with DECIMAL_DIG digits, then the result should be an exact
representation with trailing zeros. Otherwise, the source value is bounded by two
adjacent decimal strings L < U, both having DECIMAL_DIG significant digits; the value
of the resultant decimal string D should satisfy L ≤ D ≤ U, with the extra stipulation that
the error should have a correct sign for the current rounding direction.
Returns
Footnote 249) For binary-to-decimal conversion, the result format’s values are the numbers representable with the
given format specifier. The number of significant digits is determined by the format specifier, and in
the case of fixed-point conversion by the source value as well.
14 The fprintf function returns the number of characters transmitted, or a negative value
if an output or encoding error occurred.
Environmental limits
15 The number of characters that can be produced by any single conversion shall be at least
4095.
16 EXAMPLE 1 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));
17 EXAMPLE 2 In this example, multibyte characters do not have a state-dependent encoding, and the
members of the extended character set that consist of more than one byte each consist of exactly two bytes,
the first of which is denoted here by a and the second by an uppercase letter.
18 Given the following wide string with length seven,