type_ident is defined as a typedef name with the type specified by the declaration
specifiers in T (known as T ), and the identifier in D has the type ‘‘derived-declarator-
type-list T ’’ where the derived-declarator-type-list is specified by the declarators of D. A
typedef name shares the same name space as other identifiers declared in ordinary
declarators.
4 EXAMPLE 1 After
typedef int MILES, KLICKSP();
typedef struct { double hi, lo; } range;
the constructions
MILES distance;
extern KLICKSP *metricp;
range x;
range z, *zp;
are all valid declarations. The type of distance is int, that of metricp is ‘‘pointer to function with no
parameter specification returning int’’, and that of x and z is the specified structure; zp is a pointer to
such a structure. The object distance has a type compatible with any other int object.
5 EXAMPLE 2 After the declarations
typedef struct s1 { int x; } t1, *tp1;
typedef struct s2 { int x; } t2, *tp2;
type t1 and the type pointed to by tp1 are compatible. Type t1 is also compatible with type struct
s1, but not compatible with the types struct s2, t2, the type pointed to by tp2, or int.
6 EXAMPLE 3 The following obscure constructions
typedef signed int t;
typedef int plain;
struct tag {
unsigned t:4;
const t:5;
plain r:5;
};
declare a typedef name t with type signed int, a typedef name plain with type int, and a structure
with three bit-field members, one named t that contains values in the range [0, 15], an unnamed const-
qualified bit-field which (if it could be accessed) would contain values in either the range [−15, +15] or
[−16, +15], and one named r that contains values in one of the ranges [0, 31], [−15, +15], or [−16, +15].
(The choice of range is implementation-defined.) The first two bit-field declarations differ in that
unsigned is a type specifier (which forces t to be the name of a structure member), while const is a
type qualifier (which modifies t which is still visible as a typedef name). If these declarations are followed
in an inner scope by
t f(t (t));
long t;
then a function f is declared with type ‘‘function returning signed int with one unnamed parameter
with type pointer to function returning signed int with one unnamed parameter with type signed
int’’, and an identifier t with type long int.
7 EXAMPLE 4 On the other hand, typedef names can be used to improve code readability. All three of the
following declarations of the signal function specify exactly the same type, the first without making use
of any typedef names.
typedef void fv(int), (*pfv)(int);
void (*signal(int, void (*)(int)))(int);
fv *signal(int, fv *);
pfv signal(int, pfv);
8 EXAMPLE 5 If a typedef name denotes a variable length array type, the length of the array is fixed at the
time the typedef name is defined, not each time it is used:
void copyt(int n)
{
typedef int B[n]; // B is n ints, n evaluated now
n += 1;
B a; // a is n ints, n without += 1
int b[n]; // a and b are different sizes
for (int i = 1; i < n; i++)
a[i-1] = b[i];
}
6.7.8 [Initialization]
1 Syntax
initializer:
assignment-expression
{ initializer-list }
{ initializer-list , }
initializer-list:
designationopt initializer
initializer-list , designationopt initializer
designation:
designator-list =
designator-list:
designator
designator-list designator
designator:
[ constant-expression ]
. identifier
Constraints
2 No initializer shall attempt to provide a value for an object not contained within the entity
being initialized.
3 The type of the entity to be initialized shall be an array of unknown size or an object type
that is not a variable length array type.
4 All the expressions in an initializer for an object that has static storage duration shall be
constant expressions or string literals.
5 If the declaration of an identifier has block scope, and the identifier has external or
internal linkage, the declaration shall have no initializer for the identifier.
6 If a designator has the form
[ constant-expression ]
then the current object (defined below) shall have array type and the expression shall be
an integer constant expression. If the array is of unknown size, any nonnegative value is
valid.
7 If a designator has the form
. identifier
then the current object (defined below) shall have structure or union type and the
Semantics
8 An initializer specifies the initial value stored in an object.
9 Except where explicitly stated otherwise, for the purposes of this subclause unnamed
members of objects of structure and union type do not participate in initialization.
Unnamed members of structure objects have indeterminate value even after initialization.
10 If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate. If an object that has static storage duration is not initialized explicitly,
then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these
rules.
11 The initializer for a scalar shall be a single expression, optionally enclosed in braces. The
initial value of the object is that of the expression (after conversion); the same type
constraints and conversions as for simple assignment apply, taking the type of the scalar
to be the unqualified version of its declared type.
12 The rest of this subclause deals with initializers for objects that have aggregate or union
type.
13 The initializer for a structure or union object that has automatic storage duration shall be
either an initializer list as described below, or a single expression that has compatible
structure or union type. In the latter case, the initial value of the object, including
unnamed members, is that of the expression.
14 An array of character type may be initialized by a character string literal, optionally
enclosed in braces. Successive characters of the character string literal (including the
terminating null character if there is room or if the array is of unknown size) initialize the
elements of the array.
15 An array with element type compatible with wchar_t may be initialized by a wide
string literal, optionally enclosed in braces. Successive wide characters of the wide string
literal (including the terminating null wide character if there is room or if the array is of
unknown size) initialize the elements of the array.
16 Otherwise, the initializer for an object that has aggregate or union type shall be a brace-
enclosed list of initializers for the elements or named members.
17 Each brace-enclosed initializer list has an associated current object. When no
designations are present, subobjects of the current object are initialized in order according
members in declaration order, and the first named member of a union.[129] In contrast, a
designation causes the following initializer to begin initialization of the subobject
described by the designator. Initialization then continues forward in order, beginning
with the next subobject after that described by the designator.[130]
Footnote 129) If the initializer list for a subaggregate or contained union does not begin with a left brace, its
subobjects are initialized as usual, but the subaggregate or contained union does not become the
current object: current objects are associated only with brace-enclosed initializer lists.
Footnote 130) After a union member is initialized, the next object is not the next member of the union; instead, it is
the next subobject of an object containing the union.
18 Each designator list begins its description with the current object associated with the
closest surrounding brace pair. Each item in the designator list (in order) specifies a
particular member of its current object and changes the current object for the next
designator (if any) to be that member.[131] The current object that results at the end of the
designator list is the subobject to be initialized by the following initializer.
Footnote 131) Thus, a designator can only specify a strict subobject of the aggregate or union that is associated with
the surrounding brace pair. Note, too, that each separate designator list is independent.
19 The initialization shall occur in initializer list order, each initializer provided for a
particular subobject overriding any previously listed initializer for the same subobject;[132]
all subobjects that are not initialized explicitly shall be initialized implicitly the same as
objects that have static storage duration.
Footnote 132) Any initializer for the subobject which is overridden and so not used to initialize that subobject might
not be evaluated at all.
20 If the aggregate or union contains elements or members that are aggregates or unions,
these rules apply recursively to the subaggregates or contained unions. If the initializer of
a subaggregate or contained union begins with a left brace, the initializers enclosed by
that brace and its matching right brace initialize the elements or members of the
subaggregate or the contained union. Otherwise, only enough initializers from the list are
taken to account for the elements or members of the subaggregate or the first member of
the contained union; any remaining initializers are left to initialize the next element or
member of the aggregate of which the current subaggregate or contained union is a part.
21 If there are fewer initializers in a brace-enclosed list than there are elements or members
of an aggregate, or fewer characters in a string literal used to initialize an array of known
size than there are elements in the array, the remainder of the aggregate shall be
initialized implicitly the same as objects that have static storage duration.
22 If an array of unknown size is initialized, its size is determined by the largest indexed
element with an explicit initializer. At the end of its initializer list, the array no longer
has incomplete type.
23 The order in which any side effects occur among the initialization list expressions is
unspecified.[133]
Footnote 133) In particular, the evaluation order need not be the same as the order of subobject initialization.
24 EXAMPLE 1 Provided that <complex.h> has been #included, the declarations
int i = 3.5;
double complex c = 5 + 3 * I;
define and initialize i with the value 3 and c with the value 5. 0 + i3. 0.
25 EXAMPLE 2 The declaration
int x[] = { 1, 3, 5 };
defines and initializes x as a one-dimensional array object that has three elements, as no size was specified
and there are three initializers.
26 EXAMPLE 3 The declaration
int y[4][3] = {
{ 1, 3, 5 },
{ 2, 4, 6 },
{ 3, 5, 7 },
};
is a definition with a fully bracketed initialization: 1, 3, and 5 initialize the first row of y (the array object
y[0]), namely y[0][0], y[0][1], and y[0][2]. Likewise the next two lines initialize y[1] and
y[2]. The initializer ends early, so y[3] is initialized with zeros. Precisely the same effect could have
been achieved by
int y[4][3] = {
1, 3, 5, 2, 4, 6, 3, 5, 7
};
The initializer for y[0] does not begin with a left brace, so three items from the list are used. Likewise the
next three are taken successively for y[1] and y[2].
27 EXAMPLE 4 The declaration
int z[4][3] = {
{ 1 }, { 2 }, { 3 }, { 4 }
};
initializes the first column of z as specified and initializes the rest with zeros.
28 EXAMPLE 5 The declaration
struct { int a[3], b; } w[] = { { 1 }, 2 };
is a definition with an inconsistently bracketed initialization. It defines an array with two element
structures: w[0].a[0] is 1 and w[1].a[0] is 2; all the other elements are zero.
29 EXAMPLE 6 The declaration
short q[4][3][2] = {
{ 1 },
{ 2, 3 },
{ 4, 5, 6 }
};
contains an incompletely but consistently bracketed initialization. It defines a three-dimensional array
object: q[0][0][0] is 1, q[1][0][0] is 2, q[1][0][1] is 3, and 4, 5, and 6 initialize
q[2][0][0], q[2][0][1], and q[2][1][0], respectively; all the rest are zero. The initializer for
q[0][0] does not begin with a left brace, so up to six items from the current list may be used. There is
only one, so the values for the remaining five elements are initialized with zero. Likewise, the initializers
for q[1][0] and q[2][0] do not begin with a left brace, so each uses up to six items, initializing their
respective two-dimensional subaggregates. If there had been more than six items in any of the lists, a
diagnostic message would have been issued. The same initialization result could have been achieved by:
short q[4][3][2] = {
1, 0, 0, 0, 0, 0,
2, 3, 0, 0, 0, 0,
4, 5, 6
};
or by:
short q[4][3][2] = {
{
{ 1 },
},
{
{ 2, 3 },
},
{
{ 4, 5 },
{ 6 },
}
};
in a fully bracketed form.
30 Note that the fully bracketed and minimally bracketed forms of initialization are, in general, less likely to
cause confusion.
31 EXAMPLE 7 One form of initialization that completes array types involves typedef names. Given the
declaration
typedef int A[]; // OK - declared with block scope
the declaration
A a = { 1, 2 }, b = { 3, 4, 5 };
is identical to
int a[] = { 1, 2 }, b[] = { 3, 4, 5 };
due to the rules for incomplete types.
32 EXAMPLE 8 The declaration
char s[] = "abc", t[3] = "abc";
defines ‘‘plain’’ char array objects s and t whose elements are initialized with character string literals.
This declaration is identical to
char s[] = { 'a', 'b', 'c', '\0' },
t[] = { 'a', 'b', 'c' };
The contents of the arrays are modifiable. On the other hand, the declaration
char *p = "abc";
defines p with type ‘‘pointer to char’’ and initializes it to point to an object with type ‘‘array of char’’
with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to
modify the contents of the array, the behavior is undefined.
33 EXAMPLE 9 Arrays can be initialized to correspond to the elements of an enumeration by using
designators:
enum { member_one, member_two };
const char *nm[] = {
[member_two] = "member two",
[member_one] = "member one",
};
34 EXAMPLE 10 Structure members can be initialized to nonzero values without depending on their order:
div_t answer = { .quot = 2, .rem = -1 };
35 EXAMPLE 11 Designators can be used to provide explicit initialization when unadorned initializer lists
might be misunderstood:
struct { int a[3], b; } w[] =
{ [0].a = {1}, [1].a[0] = 2 };
36 EXAMPLE 12 Space can be ‘‘allocated’’ from both ends of an array by using a single designator:
int a[MAX] = {
1, 3, 5, 7, 9, [MAX-5] = 8, 6, 4, 2, 0
};
37 In the above, if MAX is greater than ten, there will be some zero-valued elements in the middle; if it is less
than ten, some of the values provided by the first five initializers will be overridden by the second five.
38 EXAMPLE 13 Any member of a union can be initialized:
union { /* ... */ } u = { .any_member = 42 };
Forward references: common definitions <stddef.h> (7.17).
6.8 [Statements and blocks]
1 Syntax
statement:
labeled-statement
compound-statement
expression-statement
selection-statement
iteration-statement
jump-statement
Semantics
2 A statement specifies an action to be performed. Except as indicated, statements are
executed in sequence.
3 A block allows a set of declarations and statements to be grouped into one syntactic unit.
The initializers of objects that have automatic storage duration, and the variable length
array declarators of ordinary identifiers with block scope, are evaluated and the values are
stored in the objects (including storing an indeterminate value in objects without an
initializer) each time the declaration is reached in the order of execution, as if it were a
statement, and within each declaration in the order that declarators appear.
4 A full expression is an expression that is not part of another expression or of a declarator.
Each of the following is a full expression: an initializer; the expression in an expression
statement; the controlling expression of a selection statement (if or switch); the
controlling expression of a while or do statement; each of the (optional) expressions of
a for statement; the (optional) expression in a return statement. The end of a full
expression is a sequence point.
Forward references: expression and null statements (6.8.3), selection statements
(6.8.4), iteration statements (6.8.5), the return statement (<IP_ADDRESS>).
6.8.1 [Labeled statements]
1 Syntax
labeled-statement:
identifier : statement
case constant-expression : statement
default : statement
Constraints
2 A case or default label shall appear only in a switch statement. Further
constraints on such labels are discussed under the switch statement.
3 Label names shall be unique within a function.
Semantics
4 Any statement may be preceded by a prefix that declares an identifier as a label name.
Labels in themselves do not alter the flow of control, which continues unimpeded across
them.
Forward references: the goto statement (<IP_ADDRESS>), the switch statement (<IP_ADDRESS>).
6.8.2 [Compound statement]
1 Syntax
compound-statement:
{ block-item-listopt }
block-item-list:
block-item
block-item-list block-item
block-item:
declaration
statement
Semantics
2 A compound statement is a block.
6.8.3 [Expression and null statements]
1 Syntax
expression-statement:
expressionopt ;
Semantics
2 The expression in an expression statement is evaluated as a void expression for its side
effects.[134]
Footnote 134) Such as assignments, and function calls which have side effects.
3 A null statement (consisting of just a semicolon) performs no operations.
4 EXAMPLE 1 If a function call is evaluated as an expression statement for its side effects only, the
discarding of its value may be made explicit by converting the expression to a void expression by means of
a cast:
int p(int);
/* ... */
(void)p(0);
5 EXAMPLE 2 In the program fragment
char *s;
/* ... */
while (*s++ != '\0')
;
a null statement is used to supply an empty loop body to the iteration statement.
6 EXAMPLE 3 A null statement may also be used to carry a label just before the closing } of a compound
statement.
while (loop1) {
/* ... */
while (loop2) {
/* ... */
if (want_out)
goto end_loop1;
/* ... */
}
/* ... */
end_loop1: ;
}
Forward references: iteration statements (6.8.5).
6.8.4 [Selection statements]
1 Syntax
selection-statement:
if ( expression ) statement
if ( expression ) statement else statement
switch ( expression ) statement
Semantics
2 A selection statement selects among a set of statements depending on the value of a
controlling expression.
3 A selection statement is a block whose scope is a strict subset of the scope of its
enclosing block. Each associated substatement is also a block whose scope is a strict
subset of the scope of the selection statement.
<IP_ADDRESS> [The if statement]
1 Constraints
The controlling expression of an if statement shall have scalar type.
Semantics
2 In both forms, the first substatement is executed if the expression compares unequal to 0.
In the else form, the second substatement is executed if the expression compares equal
to 0. If the first substatement is reached via a label, the second substatement is not
executed.
3 An else is associated with the lexically nearest preceding if that is allowed by the
syntax.
<IP_ADDRESS> [The switch statement]
1 Constraints
The controlling expression of a switch statement shall have integer type.
2 If a switch statement has an associated case or default label within the scope of an
identifier with a variably modified type, the entire switch statement shall be within the
scope of that identifier.[135]
Footnote 135) That is, the declaration either precedes the switch statement, or it follows the last case or
default label associated with the switch that is in the block containing the declaration.
3 The expression of each case label shall be an integer constant expression and no two of
the case constant expressions in the same switch statement shall have the same value
after conversion. There may be at most one default label in a switch statement.
(Any enclosed switch statement may have a default label or case constant
expressions with values that duplicate case constant expressions in the enclosing
switch statement.)
Semantics
4 A switch statement causes control to jump to, into, or past the statement that is the
switch body, depending on the value of a controlling expression, and on the presence of a
default label and the values of any case labels on or in the switch body. A case or
default label is accessible only within the closest enclosing switch statement.
5 The integer promotions are performed on the controlling expression. The constant
expression in each case label is converted to the promoted type of the controlling
expression. If a converted value matches that of the promoted controlling expression,
control jumps to the statement following the matched case label. Otherwise, if there is
a default label, control jumps to the labeled statement. If no converted case constant
expression matches and there is no default label, no part of the switch body is
executed.
Implementation limits
6 As discussed in <IP_ADDRESS>, the implementation may limit the number of case values in a
switch statement.
7 EXAMPLE In the artificial program fragment
switch (expr)
{
int i = 4;
f(i);
case 0:
i = 17;
/* falls through into default code */
default:
printf("%d\n", i);
}
the object whose identifier is i exists with automatic storage duration (within the block) but is never
initialized, and thus if the controlling expression has a nonzero value, the call to the printf function will
access an indeterminate value. Similarly, the call to the function f cannot be reached.
6.8.5 [Iteration statements]
1 Syntax
iteration-statement:
while ( expression ) statement
do statement while ( expression ) ;
for ( expressionopt ; expressionopt ; expressionopt ) statement
for ( declaration expressionopt ; expressionopt ) statement
Constraints
2 The controlling expression of an iteration statement shall have scalar type.
3 The declaration part of a for statement shall only declare identifiers for objects having
storage class auto or register.
Semantics
4 An iteration statement causes a statement called the loop body to be executed repeatedly
until the controlling expression compares equal to 0. The repetition occurs regardless of
whether the loop body is entered from the iteration statement or by a jump.[136]
Footnote 136) Code jumped over is not executed. In particular, the controlling expression of a for or while
statement is not evaluated before entering the loop body, nor is clause-1 of a for statement.
5 An iteration statement is a block whose scope is a strict subset of the scope of its
enclosing block. The loop body is also a block whose scope is a strict subset of the scope
of the iteration statement.
<IP_ADDRESS> [The while statement]
1 The evaluation of the controlling expression takes place before each execution of the loop
body.
<IP_ADDRESS> [The do statement]
1 The evaluation of the controlling expression takes place after each execution of the loop
body.
<IP_ADDRESS> [The for statement]
1 The statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The expression expression-2 is the controlling expression that is
evaluated before each execution of the loop body. The expression expression-3 is
evaluated as a void expression after each execution of the loop body. If clause-1 is a
declaration, the scope of any identifiers it declares is the remainder of the declaration and
the entire loop, including the other two expressions; it is reached in the order of execution
before the first evaluation of the controlling expression. If clause-1 is an expression, it is
evaluated as a void expression before the first evaluation of the controlling expression.[137]
Footnote 137) Thus, clause-1 specifies initialization for the loop, possibly declaring one or more variables for use in
the loop; the controlling expression, expression-2, specifies an evaluation made before each iteration,
such that execution of the loop continues until the expression compares equal to 0; and expression-3
specifies an operation (such as incrementing) that is performed after each iteration.
2 Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a
nonzero constant.
6.8.6 [Jump statements]
1 Syntax
jump-statement:
goto identifier ;
continue ;
break ;
return expressionopt ;
Semantics
2 A jump statement causes an unconditional jump to another place.
<IP_ADDRESS> [The goto statement]
1 Constraints
The identifier in a goto statement shall name a label located somewhere in the enclosing
function. A goto statement shall not jump from outside the scope of an identifier having
a variably modified type to inside the scope of that identifier.
Semantics
2 A goto statement causes an unconditional jump to the statement prefixed by the named
label in the enclosing function.
3 EXAMPLE 1 It is sometimes convenient to jump into the middle of a complicated set of statements. The
following outline presents one possible approach to a problem based on these three assumptions:
1. The general initialization code accesses objects only visible to the current function.
2. The general initialization code is too large to warrant duplication.
3. The code to determine the next operation is at the head of the loop. (To allow it to be reached by
continue statements, for example.)
/* ... */
goto first_time;
for (;;) {
// determine next operation
/* ... */
if (need to reinitialize) {
// reinitialize-only code
/* ... */
first_time:
// general initialization code
/* ... */
continue;
}
// handle other operations
/* ... */
}
4 EXAMPLE 2 A goto statement is not allowed to jump past any declarations of objects with variably
modified types. A jump within the scope, however, is permitted.
goto lab3; // invalid: going INTO scope of VLA.
{
double a[n];
a[j] = 4.4;
lab3:
a[j] = 3.3;
goto lab4; // valid: going WITHIN scope of VLA.
a[j] = 5.5;
lab4:
a[j] = 6.6;
}
goto lab4; // invalid: going INTO scope of VLA.
<IP_ADDRESS> [The continue statement]
1 Constraints
A continue statement shall appear only in or as a loop body.
Semantics
2 A continue statement causes a jump to the loop-continuation portion of the smallest
enclosing iteration statement; that is, to the end of the loop body. More precisely, in each
of the statements
while (/* ... */) { do { for (/* ... */) {
/* ... */ /* ... */ /* ... */
continue; continue; continue;
/* ... */ /* ... */ /* ... */
contin: ; contin: ; contin: ;
} } while (/* ... */); }
unless the continue statement shown is in an enclosed iteration statement (in which
case it is interpreted within that statement), it is equivalent to goto contin;.[138]
Footnote 138) Following the contin: label is a null statement.
<IP_ADDRESS> [The break statement]
1 Constraints
A break statement shall appear only in or as a switch body or loop body.
Semantics
2 A break statement terminates execution of the smallest enclosing switch or iteration
statement.
<IP_ADDRESS> [The return statement]
1 Constraints
A return statement with an expression shall not appear in a function whose return type
is void. A return statement without an expression shall only appear in a function
whose return type is void.
Semantics
2 A return statement terminates execution of the current function and returns control to
its caller. A function may have any number of return statements.
3 If a return statement with an expression is executed, the value of the expression is
returned to the caller as the value of the function call expression. If the expression has a
type different from the return type of the function in which it appears, the value is
converted as if by assignment to an object having the return type of the function.[139]
Footnote 139) The return statement is not an assignment. The overlap restriction of subclause <IP_ADDRESS> does not
apply to the case of function return. The representation of floating-point values may have wider range
or precision and is determined by FLT_EVAL_METHOD. A cast may be used to remove this extra
range and precision.
4 EXAMPLE In:
struct s { double i; } f(void);
union {
struct {
int f1;
struct s f2;
} u1;
struct {
struct s f3;
int f4;
} u2;
} g;
struct s f(void)
{
return g.u1.f2;
}
/* ... */
g.u2.f3 = f();
there is no undefined behavior, although there would be if the assignment were done directly (without using
a function call to fetch the value).
6.9 [External definitions]
1 Syntax
translation-unit:
external-declaration
translation-unit external-declaration
external-declaration:
function-definition
declaration
Constraints
2 The storage-class specifiers auto and register shall not appear in the declaration
specifiers in an external declaration.
3 There shall be no more than one external definition for each identifier declared with
internal linkage in a translation unit. Moreover, if an identifier declared with internal
linkage is used in an expression (other than as a part of the operand of a sizeof
operator whose result is an integer constant), there shall be exactly one external definition
for the identifier in the translation unit.
Semantics
4 As discussed in <IP_ADDRESS>, the unit of program text after preprocessing is a translation unit,
which consists of a sequence of external declarations. These are described as ‘‘external’’
because they appear outside any function (and hence have file scope). As discussed in
6.7, a declaration that also causes storage to be reserved for an object or a function named
by the identifier is a definition.
5 An external definition is an external declaration that is also a definition of a function
(other than an inline definition) or an object. If an identifier declared with external
linkage is used in an expression (other than as part of the operand of a sizeof operator
whose result is an integer constant), somewhere in the entire program there shall be
exactly one external definition for the identifier; otherwise, there shall be no more than
one.[140]
Footnote 140) Thus, if an identifier declared with external linkage is not used in an expression, there need be no
external definition for it.
6.9.1 [Function definitions]
1 Syntax
function-definition:
declaration-specifiers declarator declaration-listopt compound-statement
declaration-list:
declaration
declaration-list declaration
Constraints
2 The identifier declared in a function definition (which is the name of the function) shall
have a function type, as specified by the declarator portion of the function definition.[141]
Footnote 141) The intent is that the type category in a function definition cannot be inherited from a typedef:
typedef int F(void); // type F is ‘‘function with no parameters
// returning int’’
F f, g; // f and g both have type compatible with F
F f { /* ... */ } // WRONG: syntax/constraint error
F g() { /* ... */ } // WRONG: declares that g returns a function
int f(void) { /* ... */ } // RIGHT: f has type compatible with F
int g() { /* ... */ } // RIGHT: g has type compatible with F
F *e(void) { /* ... */ } // e returns a pointer to a function
F *((e))(void) { /* ... */ } // same: parentheses irrelevant
int (*fp)(void); // fp points to a function that has type F
F *Fp; // Fp points to a function that has type F
3 The return type of a function shall be void or an object type other than array type.
4 The storage-class specifier, if any, in the declaration specifiers shall be either extern or
static.
5 If the declarator includes a parameter type list, the declaration of each parameter shall
include an identifier, except for the special case of a parameter list consisting of a single
parameter of type void, in which case there shall not be an identifier. No declaration list
shall follow.
6 If the declarator includes an identifier list, each declaration in the declaration list shall
have at least one declarator, those declarators shall declare only identifiers from the
identifier list, and every identifier in the identifier list shall be declared. An identifier
declared as a typedef name shall not be redeclared as a parameter. The declarations in the
declaration list shall contain no storage-class specifier other than register and no
initializations.
Semantics
7 The declarator in a function definition specifies the name of the function being defined
and the identifiers of its parameters. If the declarator includes a parameter type list, the
list also specifies the types of all the parameters; such a declarator also serves as a
function prototype for later calls to the same function in the same translation unit. If the
declarator includes an identifier list,[142] the types of the parameters shall be declared in a
following declaration list. In either case, the type of each parameter is adjusted as
described in <IP_ADDRESS> for a parameter type list; the resulting type shall be an object type.
Footnote 142) See ‘‘future language directions’’ (6.11.7).
8 If a function that accepts a variable number of arguments is defined without a parameter
type list that ends with the ellipsis notation, the behavior is undefined.
9 Each parameter has automatic storage duration. Its identifier is an lvalue, which is in
effect declared at the head of the compound statement that constitutes the function body
(and therefore cannot be redeclared in the function body except in an enclosed block).
The layout of the storage for parameters is unspecified.
10 On entry to the function, the size expressions of each variably modified parameter are
evaluated and the value of each argument expression is converted to the type of the
corresponding parameter as if by assignment. (Array expressions and function
designators as arguments were converted to pointers before the call.)
11 After all parameters have been assigned, the compound statement that constitutes the
body of the function definition is executed.
12 If the } that terminates a function is reached, and the value of the function call is used by
the caller, the behavior is undefined.
13 EXAMPLE 1 In the following:
extern int max(int a, int b)
{
return a > b ? a : b;
}
extern is the storage-class specifier and int is the type specifier; max(int a, int b) is the
function declarator; and
{ return a > b ? a : b; }
is the function body. The following similar definition uses the identifier-list form for the parameter
declarations:
extern int max(a, b)
int a, b;
{
return a > b ? a : b;
}
Here int a, b; is the declaration list for the parameters. The difference between these two definitions is
that the first form acts as a prototype declaration that forces conversion of the arguments of subsequent calls
to the function, whereas the second form does not.
14 EXAMPLE 2 To pass one function to another, one might say
int f(void);
/* ... */
g(f);
Then the definition of g might read
void g(int (*funcp)(void))
{
/* ... */
(*funcp)(); /* or funcp(); ... */
}
or, equivalently,
void g(int func(void))
{
/* ... */
func(); /* or (*func)(); ... */
}
6.9.2 [External object definitions]
1 Semantics
If the declaration of an identifier for an object has file scope and an initializer, the
declaration is an external definition for the identifier.
2 A declaration of an identifier for an object that has file scope without an initializer, and
without a storage-class specifier or with the storage-class specifier static, constitutes a
tentative definition. If a translation unit contains one or more tentative definitions for an
identifier, and the translation unit contains no external definition for that identifier, then
the behavior is exactly as if the translation unit contains a file scope declaration of that
identifier, with the composite type as of the end of the translation unit, with an initializer
equal to 0.
3 If the declaration of an identifier for an object is a tentative definition and has internal
linkage, the declared type shall not be an incomplete type.
4 EXAMPLE 1
int i1 = 1; // definition, external linkage
static int i2 = 2; // definition, internal linkage
extern int i3 = 3; // definition, external linkage
int i4; // tentative definition, external linkage
static int i5; // tentative definition, internal linkage
int i1; // valid tentative definition, refers to previous
int i2; // 6.2.2 renders undefined, linkage disagreement
int i3; // valid tentative definition, refers to previous
int i4; // valid tentative definition, refers to previous
int i5; // 6.2.2 renders undefined, linkage disagreement
extern int i1; // refers to previous, whose linkage is external
extern int i2; // refers to previous, whose linkage is internal
extern int i3; // refers to previous, whose linkage is external
extern int i4; // refers to previous, whose linkage is external
extern int i5; // refers to previous, whose linkage is internal
5 EXAMPLE 2 If at the end of the translation unit containing
int i[];
the array i still has incomplete type, the implicit initializer causes it to have one element, which is set to
zero on program startup.
6.10 [Preprocessing directives]
1 Syntax
preprocessing-file:
groupopt
group:
group-part
group group-part
group-part:
if-section
control-line
text-line
# non-directive
if-section:
if-group elif-groupsopt else-groupopt endif-line
if-group:
# if constant-expression new-line groupopt
# ifdef identifier new-line groupopt
# ifndef identifier new-line groupopt
elif-groups:
elif-group
elif-groups elif-group
elif-group:
# elif constant-expression new-line groupopt
else-group:
# else new-line groupopt
endif-line:
# endif new-line
control-line:
# include pp-tokens new-line
# define identifier replacement-list new-line
# define identifier lparen identifier-listopt )
replacement-list new-line
# define identifier lparen ... ) replacement-list new-line
# define identifier lparen identifier-list , ... )
replacement-list new-line
# undef identifier new-line
# line pp-tokens new-line
# error pp-tokensopt new-line
# pragma pp-tokensopt new-line
# new-line
text-line:
pp-tokensopt new-line
non-directive:
pp-tokens new-line
lparen:
a ( character not immediately preceded by white-space
replacement-list:
pp-tokensopt
pp-tokens:
preprocessing-token
pp-tokens preprocessing-token
new-line:
the new-line character
Description
2 A preprocessing directive consists of a sequence of preprocessing tokens that satisfies the
following constraints: The first token in the sequence is a # preprocessing token that (at
the start of translation phase 4) is either the first character in the source file (optionally
after white space containing no new-line characters) or that follows white space
containing at least one new-line character. The last token in the sequence is the first new-
line character that follows the first token in the sequence.[143] A new-line character ends
the preprocessing directive even if it occurs within what would otherwise be an
invocation of a function-like macro.
Footnote 143) Thus, preprocessing directives are commonly called ‘‘lines’’. These ‘‘lines’’ have no other syntactic
significance, as all white space is equivalent except in certain situations during preprocessing (see the
# character string literal creation operator in <IP_ADDRESS>, for example).
3 A text line shall not begin with a # preprocessing token. A non-directive shall not begin
with any of the directive names appearing in the syntax.
4 When in a group that is skipped (6.10.1), the directive syntax is relaxed to allow any
sequence of preprocessing tokens to occur between the directive name and the following
new-line character.
Constraints
5 The only white-space characters that shall appear between preprocessing tokens within a
preprocessing directive (from just after the introducing # preprocessing token through
just before the terminating new-line character) are space and horizontal-tab (including
spaces that have replaced comments or possibly other white-space characters in
translation phase 3).
Semantics
6 The implementation can process and skip sections of source files conditionally, include
other source files, and replace macros. These capabilities are called preprocessing,
because conceptually they occur before translation of the resulting translation unit.
7 The preprocessing tokens within a preprocessing directive are not subject to macro
expansion unless otherwise stated.
8 EXAMPLE In:
#define EMPTY
EMPTY # include <file.h>
the sequence of preprocessing tokens on the second line is not a preprocessing directive, because it does not
begin with a # at the start of translation phase 4, even though it will do so after the macro EMPTY has been
replaced.
6.10.1 [Conditional inclusion]
1 Constraints
The expression that controls conditional inclusion shall be an integer constant expression
except that: it shall not contain a cast; identifiers (including those lexically identical to
keywords) are interpreted as described below;[144] and it may contain unary operator
expressions of the form
defined identifier
or
defined ( identifier )
which evaluate to 1 if the identifier is currently defined as a macro name (that is, if it is
predefined or if it has been the subject of a #define preprocessing directive without an
intervening #undef directive with the same subject identifier), 0 if it is not.
Footnote 144) Because the controlling constant expression is evaluated during translation phase 4, all identifiers
either are or are not macro names — there simply are no keywords, enumeration constants, etc.
2 Each preprocessing token that remains (in the list of preprocessing tokens that will
become the controlling expression) after all macro replacements have occurred shall be in
the lexical form of a token (6.4).
Semantics
3 Preprocessing directives of the forms
# if constant-expression new-line groupopt
# elif constant-expression new-line groupopt
check whether the controlling constant expression evaluates to nonzero.
4 Prior to evaluation, macro invocations in the list of preprocessing tokens that will become
the controlling constant expression are replaced (except for those macro names modified
by the defined unary operator), just as in normal text. If the token defined is
generated as a result of this replacement process or use of the defined unary operator
does not match one of the two specified forms prior to macro replacement, the behavior is
undefined. After all replacements due to macro expansion and the defined unary
operator have been performed, all remaining identifiers (including those lexically
identical to keywords) are replaced with the pp-number 0, and then each preprocessing
token is converted into a token. The resulting tokens compose the controlling constant
expression which is evaluated according to the rules of 6.6. For the purposes of this
token conversion and evaluation, all signed integer types and all unsigned integer types
act as if they have the same representation as, respectively, the types intmax_t and
uintmax_t defined in the header <stdint.h>.[145] This includes interpreting
character constants, which may involve converting escape sequences into execution
character set members. Whether the numeric value for these character constants matches
the value obtained when an identical character constant occurs in an expression (other
than within a #if or #elif directive) is implementation-defined.[146] Also, whether a
single-character character constant may have a negative value is implementation-defined.
Footnote 145) Thus, on an implementation where INT_MAX is 0x7FFF and UINT_MAX is 0xFFFF, the constant
0x8000 is signed and positive within a #if expression even though it would be unsigned in
translation phase 7.
Footnote 146) Thus, the constant expression in the following #if directive and if statement is not guaranteed to
evaluate to the same value in these two contexts.
#if 'z' - 'a' == 25
if ('z' - 'a' == 25)
5 Preprocessing directives of the forms
# ifdef identifier new-line groupopt
# ifndef identifier new-line groupopt
check whether the identifier is or is not currently defined as a macro name. Their
conditions are equivalent to #if defined identifier and #if !defined identifier
respectively.
6 Each directive’s condition is checked in order. If it evaluates to false (zero), the group
that it controls is skipped: directives are processed only through the name that determines
the directive in order to keep track of the level of nested conditionals; the rest of the
directives’ preprocessing tokens are ignored, as are the other preprocessing tokens in the
group. Only the first group whose control condition evaluates to true (nonzero) is
processed. If none of the conditions evaluates to true, and there is a #else directive, the
group controlled by the #else is processed; lacking a #else directive, all the groups
until the #endif are skipped.[147]
Forward references: macro replacement (6.10.3), source file inclusion (6.10.2), largest
integer types (<IP_ADDRESS>).
Footnote 147) As indicated by the syntax, a preprocessing token shall not follow a #else or #endif directive
before the terminating new-line character. However, comments may appear anywhere in a source file,
including within a preprocessing directive.
6.10.2 [Source file inclusion]
1 Constraints
A #include directive shall identify a header or source file that can be processed by the
implementation.
Semantics
2 A preprocessing directive of the form
# include <h-char-sequence> new-line
searches a sequence of implementation-defined places for a header identified uniquely by
the specified sequence between the < and > delimiters, and causes the replacement of that
directive by the entire contents of the header. How the places are specified or the header
identified is implementation-defined.
3 A preprocessing directive of the form
# include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified
by the specified sequence between the " delimiters. The named source file is searched
for in an implementation-defined manner. If this search is not supported, or if the search
fails, the directive is reprocessed as if it read
# include <h-char-sequence> new-line
with the identical contained sequence (including > characters, if any) from the original
directive.
4 A preprocessing directive of the form
# include pp-tokens new-line
(that does not match one of the two previous forms) is permitted. The preprocessing
tokens after include in the directive are processed just as in normal text. (Each
identifier currently defined as a macro name is replaced by its replacement list of
preprocessing tokens.) The directive resulting after all replacements shall match one of
the two previous forms.[148] The method by which a sequence of preprocessing tokens
between a < and a > preprocessing token pair or a pair of " characters is combined into a
single header name preprocessing token is implementation-defined.
Footnote 148) Note that adjacent string literals are not concatenated into a single string literal (see the translation
phases in <IP_ADDRESS>); thus, an expansion that results in two string literals is an invalid directive.
5 The implementation shall provide unique mappings for sequences consisting of one or
more nondigits or digits (<IP_ADDRESS>) followed by a period (.) and a single nondigit. The
first character shall not be a digit. The implementation may ignore distinctions of
alphabetical case and restrict the mapping to eight significant characters before the
period.
6 A #include preprocessing directive may appear in a source file that has been read
because of a #include directive in another file, up to an implementation-defined
nesting limit (see <IP_ADDRESS>).
7 EXAMPLE 1 The most common uses of #include preprocessing directives are as in the following:
#include <stdio.h>
#include "myprog.h"
8 EXAMPLE 2 This illustrates macro-replaced #include directives:
#if VERSION == 1
#define INCFILE "vers1.h"
#elif VERSION == 2
#define INCFILE "vers2.h" // and so on
#else
#define INCFILE "versN.h"
#endif
#include INCFILE
Forward references: macro replacement (6.10.3).
6.10.3 [Macro replacement]
1 Constraints
Two replacement lists are identical if and only if the preprocessing tokens in both have
the same number, ordering, spelling, and white-space separation, where all white-space
separations are considered identical.
2 An identifier currently defined as an object-like macro shall not be redefined by another
#define preprocessing directive unless the second definition is an object-like macro
definition and the two replacement lists are identical. Likewise, an identifier currently
defined as a function-like macro shall not be redefined by another #define
preprocessing directive unless the second definition is a function-like macro definition
that has the same number and spelling of parameters, and the two replacement lists are
identical.
3 There shall be white-space between the identifier and the replacement list in the definition
of an object-like macro.
4 If the identifier-list in the macro definition does not end with an ellipsis, the number of
arguments (including those arguments consisting of no preprocessing tokens) in an
invocation of a function-like macro shall equal the number of parameters in the macro
definition. Otherwise, there shall be more arguments in the invocation than there are
parameters in the macro definition (excluding the ...). There shall exist a )
preprocessing token that terminates the invocation.
5 The identifier _ _VA_ARGS_ _ shall occur only in the replacement-list of a function-like
macro that uses the ellipsis notation in the parameters.
6 A parameter identifier in a function-like macro shall be uniquely declared within its
scope.
Semantics
7 The identifier immediately following the define is called the macro name. There is one
name space for macro names. Any white-space characters preceding or following the
replacement list of preprocessing tokens are not considered part of the replacement list
for either form of macro.
8 If a # preprocessing token, followed by an identifier, occurs lexically at the point at which
a preprocessing directive could begin, the identifier is not subject to macro replacement.
9 A preprocessing directive of the form
# define identifier replacement-list new-line
defines an object-like macro that causes each subsequent instance of the macro name[149]
to be replaced by the replacement list of preprocessing tokens that constitute the
remainder of the directive. The replacement list is then rescanned for more macro names
as specified below.
Footnote 149) Since, by macro-replacement time, all character constants and string literals are preprocessing tokens,
not sequences possibly containing identifier-like subsequences (see <IP_ADDRESS>, translation phases), they
are never scanned for macro names or parameters.
10 A preprocessing directive of the form
# define identifier lparen identifier-listopt ) replacement-list new-line
# define identifier lparen ... ) replacement-list new-line
# define identifier lparen identifier-list , ... ) replacement-list new-line
defines a function-like macro with parameters, whose use is similar syntactically to a
function call. The parameters are specified by the optional list of identifiers, whose scope
extends from their declaration in the identifier list until the new-line character that
terminates the #define preprocessing directive. Each subsequent instance of the
function-like macro name followed by a ( as the next preprocessing token introduces the
sequence of preprocessing tokens that is replaced by the replacement list in the definition
(an invocation of the macro). The replaced sequence of preprocessing tokens is
terminated by the matching ) preprocessing token, skipping intervening matched pairs of
left and right parenthesis preprocessing tokens. Within the sequence of preprocessing
tokens making up an invocation of a function-like macro, new-line is considered a normal
white-space character.
11 The sequence of preprocessing tokens bounded by the outside-most matching parentheses
forms the list of arguments for the function-like macro. The individual arguments within
the list are separated by comma preprocessing tokens, but comma preprocessing tokens
between matching inner parentheses do not separate arguments. If there are sequences of
preprocessing tokens within the list of arguments that would otherwise act as
preprocessing directives,[150] the behavior is undefined.
Footnote 150) Despite the name, a non-directive is a preprocessing directive.
12 If there is a ... in the identifier-list in the macro definition, then the trailing arguments,
including any separating comma preprocessing tokens, are merged to form a single item:
the variable arguments. The number of arguments so combined is such that, following
merger, the number of arguments is one more than the number of parameters in the macro
definition (excluding the ...).
<IP_ADDRESS> [Argument substitution]
1 After the arguments for the invocation of a function-like macro have been identified,
argument substitution takes place. A parameter in the replacement list, unless preceded
by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is
replaced by the corresponding argument after all macros contained therein have been
expanded. Before being substituted, each argument’s preprocessing tokens are
completely macro replaced as if they formed the rest of the preprocessing file; no other
preprocessing tokens are available.
2 An identifier _ _VA_ARGS_ _ that occurs in the replacement list shall be treated as if it
were a parameter, and the variable arguments shall form the preprocessing tokens used to
replace it.
<IP_ADDRESS> [The # operator]
1 Constraints
Each # preprocessing token in the replacement list for a function-like macro shall be
followed by a parameter as the next preprocessing token in the replacement list.
Semantics
2 If, in the replacement list, a parameter is immediately preceded by a # preprocessing
token, both are replaced by a single character string literal preprocessing token that
contains the spelling of the preprocessing token sequence for the corresponding
argument. Each occurrence of white space between the argument’s preprocessing tokens
becomes a single space character in the character string literal. White space before the
first preprocessing token and after the last preprocessing token composing the argument
is deleted. Otherwise, the original spelling of each preprocessing token in the argument
is retained in the character string literal, except for special handling for producing the
spelling of string literals and character constants: a \ character is inserted before each "
and \ character of a character constant or string literal (including the delimiting "
characters), except that it is implementation-defined whether a \ character is inserted
before the \ character beginning a universal character name. If the replacement that
results is not a valid character string literal, the behavior is undefined. The character
string literal corresponding to an empty argument is "". The order of evaluation of # and
## operators is unspecified.
<IP_ADDRESS> [The ## operator]
1 Constraints
A ## preprocessing token shall not occur at the beginning or at the end of a replacement
list for either form of macro definition.
Semantics
2 If, in the replacement list of a function-like macro, a parameter is immediately preceded
or followed by a ## preprocessing token, the parameter is replaced by the corresponding
argument’s preprocessing token sequence; however, if an argument consists of no
preprocessing tokens, the parameter is replaced by a placemarker preprocessing token
instead.[151]
Footnote 151) Placemarker preprocessing tokens do not appear in the syntax because they are temporary entities that
exist only within translation phase 4.
3 For both object-like and function-like macro invocations, before the replacement list is
reexamined for more macro names to replace, each instance of a ## preprocessing token
in the replacement list (not from an argument) is deleted and the preceding preprocessing
token is concatenated with the following preprocessing token. Placemarker
preprocessing tokens are handled specially: concatenation of two placemarkers results in
a single placemarker preprocessing token, and concatenation of a placemarker with a
non-placemarker preprocessing token results in the non-placemarker preprocessing token.
If the result is not a valid preprocessing token, the behavior is undefined. The resulting
token is available for further macro replacement. The order of evaluation of ## operators
is unspecified.
4 EXAMPLE In the following fragment:
#define hash_hash # ## #
#define mkstr(a) # a
#define in_between(a) mkstr(a)
#define join(c, d) in_between(c hash_hash d)
char p[] = join(x, y); // equivalent to
// char p[] = "x ## y";
The expansion produces, at various stages:
join(x, y)
in_between(x hash_hash y)
in_between(x ## y)
mkstr(x ## y)
"x ## y"
In other words, expanding hash_hash produces a new token, consisting of two adjacent sharp signs, but
this new token is not the ## operator.
<IP_ADDRESS> [Rescanning and further replacement]
1 After all parameters in the replacement list have been substituted and # and ##
processing has taken place, all placemarker preprocessing tokens are removed. Then, the
resulting preprocessing token sequence is rescanned, along with all subsequent
preprocessing tokens of the source file, for more macro names to replace.
2 If the name of the macro being replaced is found during this scan of the replacement list
(not including the rest of the source file’s preprocessing tokens), it is not replaced.
Furthermore, if any nested replacements encounter the name of the macro being replaced,
it is not replaced. These nonreplaced macro name preprocessing tokens are no longer
available for further replacement even if they are later (re)examined in contexts in which
that macro name preprocessing token would otherwise have been replaced.
3 The resulting completely macro-replaced preprocessing token sequence is not processed
as a preprocessing directive even if it resembles one, but all pragma unary operator
expressions within it are then processed as specified in 6.10.9 below.
<IP_ADDRESS> [Scope of macro definitions]
1 A macro definition lasts (independent of block structure) until a corresponding #undef
directive is encountered or (if none is encountered) until the end of the preprocessing
translation unit. Macro definitions have no significance after translation phase 4.
2 A preprocessing directive of the form
# undef identifier new-line
causes the specified identifier no longer to be defined as a macro name. It is ignored if
the specified identifier is not currently defined as a macro name.
3 EXAMPLE 1 The simplest use of this facility is to define a ‘‘manifest constant’’, as in
#define TABSIZE 100
int table[TABSIZE];
4 EXAMPLE 2 The following defines a function-like macro whose value is the maximum of its arguments.
It has the advantages of working for any compatible types of the arguments and of generating in-line code
without the overhead of function calling. It has the disadvantages of evaluating one or the other of its
arguments a second time (including side effects) and generating more code than a function if invoked
several times. It also cannot have its address taken, as it has none.
#define max(a, b) ((a) > (b) ? (a) : (b))
The parentheses ensure that the arguments and the resulting expression are bound properly.
5 EXAMPLE 3 To illustrate the rules for redefinition and reexamination, the sequence
#define x 3
#define f(a) f(x * (a))
#undef x
#define x 2
#define g f
#define z z[0]
#define h g(~
#define m(a) a(w)
#define w 0,1
#define t(a) a
#define p() int
#define q(x) x
#define r(x,y) x ## y
#define str(x) # x
f(y+1) + f(f(z)) % t(t(g)(0) + t)(1);
g(x+(3,4)-w) | h 5) & m
(f)^m(m);
p() i[q()] = { q(1), r(2,3), r(4,), r(,5), r(,) };
char c[2][6] = { str(hello), str() };
results in
f(2 * (y+1)) + f(2 * (f(2 * (z[0])))) % f(2 * (0)) + t(1);
f(2 * (2+(3,4)-0,1)) | f(2 * (~ 5)) & f(2 * (0,1))^m(0,1);
int i[] = { 1, 23, 4, 5, };
char c[2][6] = { "hello", "" };
6 EXAMPLE 4 To illustrate the rules for creating character string literals and concatenating tokens, the
sequence
#define str(s) # s
#define xstr(s) str(s)
#define debug(s, t) printf("x" # s "= %d, x" # t "= %s", \
x ## s, x ## t)
#define INCFILE(n) vers ## n
#define glue(a, b) a ## b
#define xglue(a, b) glue(a, b)
#define HIGHLOW "hello"
#define LOW LOW ", world"
debug(1, 2);
fputs(str(strncmp("abc\0d", "abc", '\4') // this goes away
== 0) str(: @\n), s);
#include xstr(INCFILE(2).h)
glue(HIGH, LOW);
xglue(HIGH, LOW)
results in
printf("x" "1" "= %d, x" "2" "= %s", x1, x2);
fputs(
"strncmp(\"abc\\0d\", \"abc\", '\\4') == 0" ": @\n",
s);
#include "vers2.h" (after macro replacement, before file access)
"hello";
"hello" ", world"
or, after concatenation of the character string literals,
printf("x1= %d, x2= %s", x1, x2);
fputs(
"strncmp(\"abc\\0d\", \"abc\", '\\4') == 0: @\n",
s);
#include "vers2.h" (after macro replacement, before file access)
"hello";
"hello, world"
Space around the # and ## tokens in the macro definition is optional.
7 EXAMPLE 5 To illustrate the rules for placemarker preprocessing tokens, the sequence
#define t(x,y,z) x ## y ## z
int j[] = { t(1,2,3), t(,4,5), t(6,,7), t(8,9,),
t(10,,), t(,11,), t(,,12), t(,,) };
results in
int j[] = { 123, 45, 67, 89,
10, 11, 12, };
8 EXAMPLE 6 To demonstrate the redefinition rules, the following sequence is valid.
#define OBJ_LIKE (1-1)
#define OBJ_LIKE /* white space */ (1-1) /* other */
#define FUNC_LIKE(a) ( a )
#define FUNC_LIKE( a )( /* note the white space */ \
a /* other stuff on this line
*/ )
But the following redefinitions are invalid:
#define OBJ_LIKE (0) // different token sequence
#define OBJ_LIKE (1 - 1) // different white space
#define FUNC_LIKE(b) ( a ) // different parameter usage
#define FUNC_LIKE(b) ( b ) // different parameter spelling
9 EXAMPLE 7 Finally, to show the variable argument list macro facilities:
#define debug(...) fprintf(stderr, _ _VA_ARGS_ _)
#define showlist(...) puts(#_ _VA_ARGS_ _)
#define report(test, ...) ((test)?puts(#test):\
printf(_ _VA_ARGS_ _))
debug("Flag");
debug("X = %d\n", x);
showlist(The first, second, and third items.);
report(x>y, "x is %d but y is %d", x, y);
results in
fprintf(stderr, "Flag" );
fprintf(stderr, "X = %d\n", x );
puts( "The first, second, and third items." );
((x>y)?puts("x>y"):
printf("x is %d but y is %d", x, y));
6.10.4 [Line control]
1 Constraints
The string literal of a #line directive, if present, shall be a character string literal.
Semantics
2 The line number of the current source line is one greater than the number of new-line
characters read or introduced in translation phase 1 (<IP_ADDRESS>) while processing the source
file to the current token.
3 A preprocessing directive of the form
# line digit-sequence new-line
causes the implementation to behave as if the following sequence of source lines begins
with a source line that has a line number as specified by the digit sequence (interpreted as
a decimal integer). The digit sequence shall not specify zero, nor a number greater than
2147483647.
4 A preprocessing directive of the form
# line digit-sequence "s-char-sequenceopt" new-line
sets the presumed line number similarly and changes the presumed name of the source
file to be the contents of the character string literal.
5 A preprocessing directive of the form
# line pp-tokens new-line
(that does not match one of the two previous forms) is permitted. The preprocessing
tokens after line on the directive are processed just as in normal text (each identifier
currently defined as a macro name is replaced by its replacement list of preprocessing
tokens). The directive resulting after all replacements shall match one of the two
previous forms and is then processed as appropriate.
6.10.5 [Error directive]
1 Semantics
A preprocessing directive of the form
# error pp-tokensopt new-line
causes the implementation to produce a diagnostic message that includes the specified
sequence of preprocessing tokens.
6.10.6 [Pragma directive]
1 Semantics
A preprocessing directive of the form
# pragma pp-tokensopt new-line
where the preprocessing token STDC does not immediately follow pragma in the
directive (prior to any macro replacement)[152] causes the implementation to behave in an
implementation-defined manner. The behavior might cause translation to fail or cause the
translator or the resulting program to behave in a non-conforming manner. Any such
pragma that is not recognized by the implementation is ignored.
Footnote 152) An implementation is not required to perform macro replacement in pragmas, but it is permitted
except for in standard pragmas (where STDC immediately follows pragma). If the result of macro
replacement in a non-standard pragma has the same form as a standard pragma, the behavior is still
implementation-defined; an implementation is permitted to behave as if it were the standard pragma,
but is not required to.
2 If the preprocessing token STDC does immediately follow pragma in the directive (prior
to any macro replacement), then no macro replacement is performed on the directive, and
the directive shall have one of the following forms[153] whose meanings are described
elsewhere:
#pragma STDC FP_CONTRACT on-off-switch
#pragma STDC FENV_ACCESS on-off-switch
#pragma STDC CX_LIMITED_RANGE on-off-switch
on-off-switch: one of
ON OFF DEFAULT
Forward references: the FP_CONTRACT pragma (7.12.2), the FENV_ACCESS pragma
(7.6.1), the CX_LIMITED_RANGE pragma (7.3.4).
Footnote 153) See ‘‘future language directions’’ (6.11.8).
6.10.7 [Null directive]
1 Semantics
A preprocessing directive of the form
# new-line
has no effect.
6.10.8 [Predefined macro names]
1 The following macro names[154] shall be defined by the implementation:
_ _DATE_ _ The date of translation of the preprocessing translation unit: a character
string literal of the form "Mmm dd yyyy", where the names of the
months are the same as those generated by the asctime function, and the
first character of dd is a space character if the value is less than 10. If the
date of translation is not available, an implementation-defined valid date
shall be supplied.
_ _FILE_ _ The presumed name of the current source file (a character string literal).[155]
_ _LINE_ _ The presumed line number (within the current source file) of the current
source line (an integer constant).[155]
_ _STDC_ _ The integer constant 1, intended to indicate a conforming implementation.
_ _STDC_HOSTED_ _ The integer constant 1 if the implementation is a hosted
implementation or the integer constant 0 if it is not.
_ _STDC_MB_MIGHT_NEQ_WC_ _ The integer constant 1, intended to indicate that, in
the encoding for wchar_t, a member of the basic character set need not
have a code value equal to its value when used as the lone character in an
integer character constant.
TIME_ _ The time of translation of the preprocessing translation unit: a character
string literal of the form "hh:mm:ss" as in the time generated by the
asctime function. If the time of translation is not available, an
implementation-defined valid time shall be supplied.
Footnote 154) See ‘‘future language directions’’ (6.11.9).
Footnote 155) The presumed source file name and line number can be changed by the #line directive.
Footnote 155) The presumed source file name and line number can be changed by the #line directive.
Footnote 156) This macro was not specified in ISO/IEC 9899:1990 and was specified as 199409L in
ISO/IEC 9899/AMD1:1995. The intention is that this will remain an integer constant of type long
int that is increased with each revision of this International Standard.
2 The following macro names are conditionally defined by the implementation:
_ _STDC_IEC_559_ _ The integer constant 1, intended to indicate conformance to the
specifications in annex F (IEC 60559 floating-point arithmetic).
_ _STDC_IEC_559_COMPLEX_ _ The integer constant 1, intended to indicate
adherence to the specifications in informative annex G (IEC 60559
compatible complex arithmetic).
_ _STDC_ISO_10646_ _ An integer constant of the form yyyymmL (for example,
199712L). If this symbol is defined, then every character in the Unicode
required set, when stored in an object of type wchar_t, has the same
value as the short identifier of that character. The Unicode required set
consists of all the characters that are defined by ISO/IEC 10646, along with
all amendments and technical corrigenda, as of the specified year and
month.
3 The values of the predefined macros (except for _ _FILE_ _ and _ _LINE_ _) remain
constant throughout the translation unit.
4 None of these macro names, nor the identifier defined, shall be the subject of a
#define or a #undef preprocessing directive. Any other predefined macro names
shall begin with a leading underscore followed by an uppercase letter or a second
underscore.
5 The implementation shall not predefine the macro _ _cplusplus, nor shall it define it
in any standard header.
Forward references: the asctime function (<IP_ADDRESS>), standard headers (7.1.2).
6.10.9 [Pragma operator]
1 Semantics
A unary operator expression of the form:
_Pragma ( string-literal )
is processed as follows: The string literal is destringized by deleting the L prefix, if
present, deleting the leading and trailing double-quotes, replacing each escape sequence
\" by a double-quote, and replacing each escape sequence \\ by a single backslash. The
resulting sequence of characters is processed through translation phase 3 to produce
preprocessing tokens that are executed as if they were the pp-tokens in a pragma
directive. The original four preprocessing tokens in the unary operator expression are
removed.
2 EXAMPLE A directive of the form:
#pragma listing on "..\listing.dir"
_Pragma ( "listing on \"..\\listing.dir\"" )
The latter form is processed in the same way whether it appears literally as shown, or results from macro
replacement, as in:
#define LISTING(x) PRAGMA(listing on #x)
#define PRAGMA(x) _Pragma(#x)
LISTING ( ..\listing.dir )
6.11 [Future language directions]
6.11.1 [Floating types]
1 Future standardization may include additional floating-point types, including those with
greater range, precision, or both than long double.
6.11.2 [Linkages of identifiers]
1 Declaring an identifier with internal linkage at file scope without the static storage-
class specifier is an obsolescent feature.
6.11.3 [External names]
1 Restriction of the significance of an external name to fewer than 255 characters
(considering each universal character name or extended source character as a single
character) is an obsolescent feature that is a concession to existing implementations.
6.11.4 [Character escape sequences]
1 Lowercase letters as escape sequences are reserved for future standardization. Other
characters may be used in extensions.
6.11.5 [Storage-class specifiers]
1 The placement of a storage-class specifier other than at the beginning of the declaration
specifiers in a declaration is an obsolescent feature.
6.11.6 [Function declarators]
1 The use of function declarators with empty parentheses (not prototype-format parameter
type declarators) is an obsolescent feature.
6.11.7 [Function definitions]
1 The use of function definitions with separate parameter identifier and declaration lists
(not prototype-format parameter type and identifier declarators) is an obsolescent feature.
6.11.8 [Pragma directives]
1 Pragmas whose first preprocessing token is STDC are reserved for future standardization.
6.11.9 [Predefined macro names]
1 Macro names beginning with _ _STDC_ are reserved for future standardization.
7. [Library]
7.1 [Introduction]
7.1.1 [Definitions of terms]
1 A string is a contiguous sequence of characters terminated by and including the first null
character. The term multibyte string is sometimes used instead to emphasize special
processing given to multibyte characters contained in the string or to avoid confusion
with a wide string. A pointer to a string is a pointer to its initial (lowest addressed)
character. The length of a string is the number of bytes preceding the null character and
the value of a string is the sequence of the values of the contained characters, in order.
2 The decimal-point character is the character used by functions that convert floating-point
numbers to or from character sequences to denote the beginning of the fractional part of
such character sequences.[157] It is represented in the text and examples by a period, but
may be changed by the setlocale function.
Footnote 157) The functions that make use of the decimal-point character are the numeric conversion functions
(7.20.1, <IP_ADDRESS>) and the formatted input/output functions (7.19.6, 7.24.2).
3 A null wide character is a wide character with code value zero.
4 A wide string is a contiguous sequence of wide characters terminated by and including
the first null wide character. A pointer to a wide string is a pointer to its initial (lowest
addressed) wide character. The length of a wide string is the number of wide characters
preceding the null wide character and the value of a wide string is the sequence of code
values of the contained wide characters, in order.
5 A shift sequence is a contiguous sequence of bytes within a multibyte string that
(potentially) causes a change in shift state (see <IP_ADDRESS>). A shift sequence shall not have a
corresponding wide character; it is instead taken to be an adjunct to an adjacent multibyte
character.[158]
Forward references: character handling (7.4), the setlocale function (<IP_ADDRESS>).
Footnote 158) For state-dependent encodings, the values for MB_CUR_MAX and MB_LEN_MAX shall thus be large
enough to count all the bytes in any complete multibyte character plus at least one adjacent shift
sequence of maximum length. Whether these counts provide for more than one shift sequence is the
implementation’s choice.
7.1.2 [Standard headers]
1 Each library function is declared, with a type that includes a prototype, in a header,[159]
whose contents are made available by the #include preprocessing directive. The
header declares a set of related functions, plus any necessary types and additional macros
needed to facilitate their use. Declarations of types described in this clause shall not
include type qualifiers, unless explicitly stated otherwise.
Footnote 159) A header is not necessarily a source file, nor are the < and > delimited sequences in header names
necessarily valid source file names.
2 The standard headers are
<assert.h> <inttypes.h> <signal.h> <stdlib.h>
<complex.h> <iso646.h> <stdarg.h> <string.h>
<ctype.h> <limits.h> <stdbool.h> <tgmath.h>
<errno.h> <locale.h> <stddef.h> <time.h>
<fenv.h> <math.h> <stdint.h> <wchar.h>
<float.h> <setjmp.h> <stdio.h> <wctype.h>
3 If a file with the same name as one of the above < and > delimited sequences, not
provided as part of the implementation, is placed in any of the standard places that are
searched for included source files, the behavior is undefined.
4 Standard headers may be included in any order; each may be included more than once in
a given scope, with no effect different from being included only once, except that the
effect of including <assert.h> depends on the definition of NDEBUG (see 7.2). If
used, a header shall be included outside of any external declaration or definition, and it
shall first be included before the first reference to any of the functions or objects it
declares, or to any of the types or macros it defines. However, if an identifier is declared
or defined in more than one header, the second and subsequent associated headers may be
included after the initial reference to the identifier. The program shall not have any
macros with names lexically identical to keywords currently defined prior to the
inclusion.
5 Any definition of an object-like macro described in this clause shall expand to code that is
fully protected by parentheses where necessary, so that it groups in an arbitrary
expression as if it were a single identifier.
6 Any declaration of a library function shall have external linkage.
7 A summary of the contents of the standard headers is given in annex B.
Forward references: diagnostics (7.2).
7.1.3 [Reserved identifiers]
1 Each header declares or defines all identifiers listed in its associated subclause, and
optionally declares or defines identifiers listed in its associated future library directions
subclause and identifiers which are always reserved either for any use or for use as file
scope identifiers.
— All identifiers that begin with an underscore and either an uppercase letter or another
underscore are always reserved for any use.
— All identifiers that begin with an underscore are always reserved for use as identifiers
with file scope in both the ordinary and tag name spaces.
— Each macro name in any of the following subclauses (including the future library
directions) is reserved for use as specified if any of its associated headers is included;
unless explicitly stated otherwise (see 7.1.4).
— All identifiers with external linkage in any of the following subclauses (including the
future library directions) are always reserved for use as identifiers with external
linkage.[160]
— Each identifier with file scope listed in any of the following subclauses (including the
future library directions) is reserved for use as a macro name and as an identifier with
file scope in the same name space if any of its associated headers is included.
Footnote 160) The list of reserved identifiers with external linkage includes errno, math_errhandling,
setjmp, and va_end.
2 No other identifiers are reserved. If the program declares or defines an identifier in a
context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved
identifier as a macro name, the behavior is undefined.
3 If the program removes (with #undef) any macro definition of an identifier in the first
group listed above, the behavior is undefined.
7.1.4 [Use of library functions]
1 Each of the following statements applies unless explicitly stated otherwise in the detailed
descriptions that follow: If an argument to a function has an invalid value (such as a value
outside the domain of the function, or a pointer outside the address space of the program,
or a null pointer, or a pointer to non-modifiable storage when the corresponding
parameter is not const-qualified) or a type (after promotion) not expected by a function
with variable number of arguments, the behavior is undefined. If a function argument is
described as being an array, the pointer actually passed to the function shall have a value
such that all address computations and accesses to objects (that would be valid if the
pointer did point to the first element of such an array) are in fact valid. Any function
declared in a header may be additionally implemented as a function-like macro defined in
the header, so if a library function is declared explicitly when its header is included, one
of the techniques shown below can be used to ensure the declaration is not affected by
such a macro. Any macro definition of a function can be suppressed locally by enclosing
the name of the function in parentheses, because the name is then not followed by the left
parenthesis that indicates expansion of a macro function name. For the same syntactic
reason, it is permitted to take the address of a library function even if it is also defined as
a macro.[161] The use of #undef to remove any macro definition will also ensure that an
actual function is referred to. Any invocation of a library function that is implemented as
a macro shall expand to code that evaluates each of its arguments exactly once, fully
protected by parentheses where necessary, so it is generally safe to use arbitrary
expressions as arguments.[162] Likewise, those function-like macros described in the
following subclauses may be invoked in an expression anywhere a function with a
compatible return type could be called.[163] All object-like macros listed as expanding to
integer constant expressions shall additionally be suitable for use in #if preprocessing
directives.
Footnote 161) This means that an implementation shall provide an actual function for each library function, even if it
also provides a macro for that function.
Footnote 162) Such macros might not contain the sequence points that the corresponding function calls do.
Footnote 163) Because external identifiers and some macro names beginning with an underscore are reserved,
implementations may provide special semantics for such names. For example, the identifier
_BUILTIN_abs could be used to indicate generation of in-line code for the abs function. Thus, the
appropriate header could specify
#define abs(x) _BUILTIN_abs(x)
for a compiler whose code generator will accept it.
In this manner, a user desiring to guarantee that a given library function such as abs will be a genuine
function may write
#undef abs
whether the implementation’s header provides a macro implementation of abs or a built-in
implementation. The prototype for the function, which precedes and is hidden by any macro
definition, is thereby revealed also.
2 Provided that a library function can be declared without reference to any type defined in a
header, it is also permissible to declare the function and use it without including its
associated header.
3 There is a sequence point immediately before a library function returns.
4 The functions in the standard library are not guaranteed to be reentrant and may modify
objects with static storage duration.[164]
Footnote 164) Thus, a signal handler cannot, in general, call standard library functions.
5 EXAMPLE The function atoi may be used in any of several ways:
— by use of its associated header (possibly generating a macro expansion)
#include <stdlib.h>
const char *str;
/* ... */
i = atoi(str);
— by use of its associated header (assuredly generating a true function reference)
#include <stdlib.h>
#undef atoi
const char *str;
/* ... */
i = atoi(str);
or
#include <stdlib.h>
const char *str;
/* ... */
i = (atoi)(str);
— by explicit declaration
extern int atoi(const char *);
const char *str;
/* ... */
i = atoi(str);
7.2 [Diagnostics <assert.h>]
1 The header <assert.h> defines the assert macro and refers to another macro,
NDEBUG
which is not defined by <assert.h>. If NDEBUG is defined as a macro name at the
point in the source file where <assert.h> is included, the assert macro is defined
simply as
#define assert(ignore) ((void)0)
The assert macro is redefined according to the current state of NDEBUG each time that
<assert.h> is included.
2 The assert macro shall be implemented as a macro, not as an actual function. If the
macro definition is suppressed in order to access an actual function, the behavior is
undefined.
7.2.1 [Program diagnostics]
<IP_ADDRESS> [The assert macro]
1 Synopsis
#include <assert.h>
void assert(scalar expression);
Description
2 The assert macro puts diagnostic tests into programs; it expands to a void expression.
When it is executed, if expression (which shall have a scalar type) is false (that is,
compares equal to 0), the assert macro writes information about the particular call that
failed (including the text of the argument, the name of the source file, the source line
number, and the name of the enclosing function — the latter are respectively the values of
the preprocessing macros _ _FILE_ _ and _ _LINE_ _ and of the identifier
_ _func_ _) on the standard error stream in an implementation-defined format.[165] It
then calls the abort function.
Returns
Footnote 165) The message written might be of the form:
Assertion failed: expression, function abc, file xyz, line nnn.
3 The assert macro returns no value.
Forward references: the abort function (<IP_ADDRESS>).
7.3 [Complex arithmetic <complex.h>]
7.3.1 [Introduction]
1 The header <complex.h> defines macros and declares functions that support complex
arithmetic.[166] Each synopsis specifies a family of functions consisting of a principal
function with one or more double complex parameters and a double complex or
double return value; and other functions with the same name but with f and l suffixes
which are corresponding functions with float and long double parameters and
return values.
Footnote 166) See ‘‘future library directions’’ (7.26.1).
2 The macro
complex
expands to _Complex; the macro
_Complex_I
expands to a constant expression of type const float _Complex, with the value of
the imaginary unit.[167]
Footnote 167) The imaginary unit is a number i such that i 2 = −1.
3 The macros
imaginary
and
_Imaginary_I
are defined if and only if the implementation supports imaginary types;[168] if defined,
they expand to _Imaginary and a constant expression of type const float
_Imaginary with the value of the imaginary unit.
Footnote 168) A specification for imaginary types is in informative annex G.
4 The macro
I
expands to either _Imaginary_I or _Complex_I. If _Imaginary_I is not
defined, I shall expand to _Complex_I.
5 Notwithstanding the provisions of 7.1.3, a program may undefine and perhaps then
redefine the macros complex, imaginary, and I.
Forward references: IEC 60559-compatible complex arithmetic (annex G).
7.3.2 [Conventions]
1 Values are interpreted as radians, not degrees. An implementation may set errno but is
not required to.
7.3.3 [Branch cuts]
1 Some of the functions below have branch cuts, across which the function is
discontinuous. For implementations with a signed zero (including all IEC 60559
implementations) that follow the specifications of annex G, the sign of zero distinguishes
one side of a cut from another so the function is continuous (except for format
limitations) as the cut is approached from either side. For example, for the square root
function, which has a branch cut along the negative real axis, the top of the cut, with
imaginary part +0, maps to the positive imaginary axis, and the bottom of the cut, with
imaginary part −0, maps to the negative imaginary axis.
2 Implementations that do not support a signed zero (see annex F) cannot distinguish the
sides of branch cuts. These implementations shall map a cut so the function is continuous
as the cut is approached coming around the finite endpoint of the cut in a counter
clockwise direction. (Branch cuts for the functions specified here have just one finite
endpoint.) For example, for the square root function, coming counter clockwise around
the finite endpoint of the cut along the negative real axis approaches the cut from above,
so the cut maps to the positive imaginary axis.
7.3.4 [The CX_LIMITED_RANGE pragma]
1 Synopsis
#include <complex.h>
#pragma STDC CX_LIMITED_RANGE on-off-switch
Description
2 The usual mathematical formulas for complex multiply, divide, and absolute value are
problematic because of their treatment of infinities and because of undue overflow and
underflow. The CX_LIMITED_RANGE pragma can be used to inform the
implementation that (where the state is ‘‘on’’) the usual mathematical formulas are
acceptable.[169] The pragma can occur either outside external declarations or preceding all
explicit declarations and statements inside a compound statement. When outside external
declarations, the pragma takes effect from its occurrence until another
CX_LIMITED_RANGE pragma is encountered, or until the end of the translation unit.
When inside a compound statement, the pragma takes effect from its occurrence until
another CX_LIMITED_RANGE pragma is encountered (including within a nested
compound statement), or until the end of the compound statement; at the end of a
compound statement the state for the pragma is restored to its condition just before the
compound statement. If this pragma is used in any other context, the behavior is
undefined. The default state for the pragma is ‘‘off’’.
Footnote 169) The purpose of the pragma is to allow the implementation to use the formulas:
(x + iy) × (u + iv) = (xu − yv) + i(yu + xv)
(x + iy) / (u + iv) = [(xu + yv) + i(yu − xv)]/(u2 + v 2 )
| x + iy | = √
x 2 + y2
where the programmer can determine they are safe.
7.3.5 [Trigonometric functions]
<IP_ADDRESS> [The cacos functions]
1 Synopsis
#include <complex.h>
double complex cacos(double complex z);
float complex cacosf(float complex z);
long double complex cacosl(long double complex z);
Description
2 The cacos functions compute the complex arc cosine of z, with branch cuts outside the
interval [−1, +1] along the real axis.
Returns
3 The cacos functions return the complex arc cosine value, in the range of a strip
mathematically unbounded along the imaginary axis and in the interval [0, π ] along the
real axis.
<IP_ADDRESS> [The casin functions]
1 Synopsis
#include <complex.h>
double complex casin(double complex z);
float complex casinf(float complex z);
long double complex casinl(long double complex z);
Description
2 The casin functions compute the complex arc sine of z, with branch cuts outside the
interval [−1, +1] along the real axis.
Returns
3 The casin functions return the complex arc sine value, in the range of a strip
mathematically unbounded along the imaginary axis and in the interval [−π /2, +π /2]
along the real axis.
<IP_ADDRESS> [The catan functions]
1 Synopsis
#include <complex.h>
double complex catan(double complex z);
float complex catanf(float complex z);
long double complex catanl(long double complex z);
Description
2 The catan functions compute the complex arc tangent of z, with branch cuts outside the
interval [−i, +i] along the imaginary axis.
Returns
3 The catan functions return the complex arc tangent value, in the range of a strip
mathematically unbounded along the imaginary axis and in the interval [−π /2, +π /2]
along the real axis.
<IP_ADDRESS> [The ccos functions]
1 Synopsis
#include <complex.h>
double complex ccos(double complex z);
float complex ccosf(float complex z);
long double complex ccosl(long double complex z);
Description
2 The ccos functions compute the complex cosine of z.
Returns
3 The ccos functions return the complex cosine value.
<IP_ADDRESS> [The csin functions]
1 Synopsis
#include <complex.h>
double complex csin(double complex z);
float complex csinf(float complex z);
long double complex csinl(long double complex z);
Description
2 The csin functions compute the complex sine of z.
Returns
3 The csin functions return the complex sine value.
<IP_ADDRESS> [The ctan functions]
1 Synopsis
#include <complex.h>
double complex ctan(double complex z);
float complex ctanf(float complex z);
long double complex ctanl(long double complex z);
Description
2 The ctan functions compute the complex tangent of z.
Returns
3 The ctan functions return the complex tangent value.
7.3.6 [Hyperbolic functions]
<IP_ADDRESS> [The cacosh functions]
1 Synopsis
#include <complex.h>
double complex cacosh(double complex z);
float complex cacoshf(float complex z);
long double complex cacoshl(long double complex z);
Description
2 The cacosh functions compute the complex arc hyperbolic cosine of z, with a branch
cut at values less than 1 along the real axis.
Returns
3 The cacosh functions return the complex arc hyperbolic cosine value, in the range of a
half-strip of non-negative values along the real axis and in the interval [−iπ , +iπ ] along
the imaginary axis.
<IP_ADDRESS> [The casinh functions]
1 Synopsis
#include <complex.h>
double complex casinh(double complex z);
float complex casinhf(float complex z);
long double complex casinhl(long double complex z);
Description
2 The casinh functions compute the complex arc hyperbolic sine of z, with branch cuts
outside the interval [−i, +i] along the imaginary axis.
Returns
3 The casinh functions return the complex arc hyperbolic sine value, in the range of a
strip mathematically unbounded along the real axis and in the interval [−iπ /2, +iπ /2]
along the imaginary axis.
<IP_ADDRESS> [The catanh functions]
1 Synopsis
#include <complex.h>
double complex catanh(double complex z);
float complex catanhf(float complex z);
long double complex catanhl(long double complex z);
Description
2 The catanh functions compute the complex arc hyperbolic tangent of z, with branch
cuts outside the interval [−1, +1] along the real axis.
Returns
3 The catanh functions return the complex arc hyperbolic tangent value, in the range of a
strip mathematically unbounded along the real axis and in the interval [−iπ /2, +iπ /2]
along the imaginary axis.
<IP_ADDRESS> [The ccosh functions]
1 Synopsis
#include <complex.h>
double complex ccosh(double complex z);
float complex ccoshf(float complex z);
long double complex ccoshl(long double complex z);
Description
2 The ccosh functions compute the complex hyperbolic cosine of z.
Returns
3 The ccosh functions return the complex hyperbolic cosine value.
<IP_ADDRESS> [The csinh functions]
1 Synopsis
#include <complex.h>
double complex csinh(double complex z);
float complex csinhf(float complex z);
long double complex csinhl(long double complex z);
Description
2 The csinh functions compute the complex hyperbolic sine of z.
Returns
3 The csinh functions return the complex hyperbolic sine value.
<IP_ADDRESS> [The ctanh functions]
1 Synopsis
#include <complex.h>
double complex ctanh(double complex z);
float complex ctanhf(float complex z);
long double complex ctanhl(long double complex z);
Description
2 The ctanh functions compute the complex hyperbolic tangent of z.
Returns
3 The ctanh functions return the complex hyperbolic tangent value.
7.3.7 [Exponential and logarithmic functions]
<IP_ADDRESS> [The cexp functions]
1 Synopsis
#include <complex.h>
double complex cexp(double complex z);
float complex cexpf(float complex z);
long double complex cexpl(long double complex z);
Description
2 The cexp functions compute the complex base-e exponential of z.
Returns
3 The cexp functions return the complex base-e exponential value.
<IP_ADDRESS> [The clog functions]
1 Synopsis
#include <complex.h>
double complex clog(double complex z);
float complex clogf(float complex z);
long double complex clogl(long double complex z);
Description
2 The clog functions compute the complex natural (base-e) logarithm of z, with a branch
cut along the negative real axis.
Returns
3 The clog functions return the complex natural logarithm value, in the range of a strip
mathematically unbounded along the real axis and in the interval [−iπ , +iπ ] along the
imaginary axis.
7.3.8 [Power and absolute-value functions]
<IP_ADDRESS> [The cabs functions]
1 Synopsis
#include <complex.h>
double cabs(double complex z);
float cabsf(float complex z);
long double cabsl(long double complex z);
Description
2 The cabs functions compute the complex absolute value (also called norm, modulus, or
magnitude) of z.
Returns
3 The cabs functions return the complex absolute value.
<IP_ADDRESS> [The cpow functions]
1 Synopsis
#include <complex.h>
double complex cpow(double complex x, double complex y);
float complex cpowf(float complex x, float complex y);
long double complex cpowl(long double complex x,
long double complex y);
Description
2 The cpow functions compute the complex power function xy , with a branch cut for the
first parameter along the negative real axis.
Returns
3 The cpow functions return the complex power function value.
<IP_ADDRESS> [The csqrt functions]
1 Synopsis
#include <complex.h>
double complex csqrt(double complex z);
float complex csqrtf(float complex z);
long double complex csqrtl(long double complex z);
Description
2 The csqrt functions compute the complex square root of z, with a branch cut along the
negative real axis.
Returns
3 The csqrt functions return the complex square root value, in the range of the right half-
plane (including the imaginary axis).
7.3.9 [Manipulation functions]
<IP_ADDRESS> [The carg functions]
1 Synopsis
#include <complex.h>
double carg(double complex z);
float cargf(float complex z);
long double cargl(long double complex z);
Description
2 The carg functions compute the argument (also called phase angle) of z, with a branch
cut along the negative real axis.
Returns
3 The carg functions return the value of the argument in the interval [−π , +π ].
<IP_ADDRESS> [The cimag functions]
1 Synopsis
#include <complex.h>
double cimag(double complex z);
float cimagf(float complex z);
long double cimagl(long double complex z);
Description
2 The cimag functions compute the imaginary part of z.[170]
Returns
Footnote 170) For a variable z of complex type, z == creal(z) + cimag(z)*I.
3 The cimag functions return the imaginary part value (as a real).
<IP_ADDRESS> [The conj functions]
1 Synopsis
#include <complex.h>
double complex conj(double complex z);
float complex conjf(float complex z);
long double complex conjl(long double complex z);
Description
2 The conj functions compute the complex conjugate of z, by reversing the sign of its
imaginary part.
Returns
3 The conj functions return the complex conjugate value.
<IP_ADDRESS> [The cproj functions]
1 Synopsis
#include <complex.h>
double complex cproj(double complex z);
float complex cprojf(float complex z);
long double complex cprojl(long double complex z);
Description
2 The cproj functions compute a projection of z onto the Riemann sphere: z projects to
z except that all complex infinities (even those with one infinite part and one NaN part)
project to positive infinity on the real axis. If z has an infinite part, then cproj(z) is
equivalent to
INFINITY + I * copysign(0.0, cimag(z))
Returns
3 The cproj functions return the value of the projection onto the Riemann sphere.
<IP_ADDRESS> [The creal functions]
1 Synopsis
#include <complex.h>
double creal(double complex z);
float crealf(float complex z);
long double creall(long double complex z);
Description
2 The creal functions compute the real part of z.[171]
Returns
Footnote 171) For a variable z of complex type, z == creal(z) + cimag(z)*I.
3 The creal functions return the real part value.
7.4 [Character handling <ctype.h>]
1 The header <ctype.h> declares several functions useful for classifying and mapping
characters.[172] In all cases the argument is an int, the value of which shall be
representable as an unsigned char or shall equal the value of the macro EOF. If the
argument has any other value, the behavior is undefined.
Footnote 172) See ‘‘future library directions’’ (7.26.2).
2 The behavior of these functions is affected by the current locale. Those functions that
have locale-specific aspects only when not in the "C" locale are noted below.
3 The term printing character refers to a member of a locale-specific set of characters, each
of which occupies one printing position on a display device; the term control character
refers to a member of a locale-specific set of characters that are not printing
characters.[173] All letters and digits are printing characters.
Forward references: EOF (7.19.1), localization (7.11).
Footnote 173) In an implementation that uses the seven-bit US ASCII character set, the printing characters are those
whose values lie from 0x20 (space) through 0x7E (tilde); the control characters are those whose
values lie from 0 (NUL) through 0x1F (US), and the character 0x7F (DEL).
7.4.1 [Character classification functions]
1 The functions in this subclause return nonzero (true) if and only if the value of the
argument c conforms to that in the description of the function.
<IP_ADDRESS> [The isalnum function]
1 Synopsis
#include <ctype.h>
int isalnum(int c);
Description
2 The isalnum function tests for any character for which isalpha or isdigit is true.
<IP_ADDRESS> [The isalpha function]
1 Synopsis
#include <ctype.h>
int isalpha(int c);
Description
2 The isalpha function tests for any character for which isupper or islower is true,
or any character that is one of a locale-specific set of alphabetic characters for which
none of iscntrl, isdigit, ispunct, or isspace is true.[174] In the "C" locale,
isalpha returns true only for the characters for which isupper or islower is true.
Footnote 174) The functions islower and isupper test true or false separately for each of these additional
characters; all four combinations are possible.
<IP_ADDRESS> [The isblank function]
1 Synopsis
#include <ctype.h>
int isblank(int c);
Description
2 The isblank function tests for any character that is a standard blank character or is one
of a locale-specific set of characters for which isspace is true and that is used to
separate words within a line of text. The standard blank characters are the following:
space (' '), and horizontal tab ('\t'). In the "C" locale, isblank returns true only
for the standard blank characters.
<IP_ADDRESS> [The iscntrl function]
1 Synopsis
#include <ctype.h>
int iscntrl(int c);
Description
2 The iscntrl function tests for any control character.
<IP_ADDRESS> [The isdigit function]
1 Synopsis
#include <ctype.h>
int isdigit(int c);
Description
2 The isdigit function tests for any decimal-digit character (as defined in 5.2.1).
<IP_ADDRESS> [The isgraph function]
1 Synopsis
#include <ctype.h>
int isgraph(int c);
Description
2 The isgraph function tests for any printing character except space (' ').
<IP_ADDRESS> [The islower function]
1 Synopsis
#include <ctype.h>
int islower(int c);
Description
2 The islower function tests for any character that is a lowercase letter or is one of a
locale-specific set of characters for which none of iscntrl, isdigit, ispunct, or
isspace is true. In the "C" locale, islower returns true only for the lowercase
letters (as defined in 5.2.1).
<IP_ADDRESS> [The isprint function]
1 Synopsis
#include <ctype.h>
int isprint(int c);
Description
2 The isprint function tests for any printing character including space (' ').
<IP_ADDRESS> [The ispunct function]
1 Synopsis
#include <ctype.h>
int ispunct(int c);
Description
2 The ispunct function tests for any printing character that is one of a locale-specific set
of punctuation characters for which neither isspace nor isalnum is true. In the "C"
locale, ispunct returns true for every printing character for which neither isspace
nor isalnum is true.
<IP_ADDRESS> [The isspace function]
1 Synopsis
#include <ctype.h>
int isspace(int c);
Description
2 The isspace function tests for any character that is a standard white-space character or
is one of a locale-specific set of characters for which isalnum is false. The standard
white-space characters are the following: space (' '), form feed ('\f'), new-line
('\n'), carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v'). In the
"C" locale, isspace returns true only for the standard white-space characters.
<IP_ADDRESS> [The isupper function]
1 Synopsis
#include <ctype.h>
int isupper(int c);
Description
2 The isupper function tests for any character that is an uppercase letter or is one of a
locale-specific set of characters for which none of iscntrl, isdigit, ispunct, or
isspace is true. In the "C" locale, isupper returns true only for the uppercase
letters (as defined in 5.2.1).
<IP_ADDRESS> [The isxdigit function]
1 Synopsis
#include <ctype.h>
int isxdigit(int c);
Description
2 The isxdigit function tests for any hexadecimal-digit character (as defined in <IP_ADDRESS>).
7.4.2 [Character case mapping functions]
<IP_ADDRESS> [The tolower function]
1 Synopsis
#include <ctype.h>
int tolower(int c);
Description
2 The tolower function converts an uppercase letter to a corresponding lowercase letter.
Returns
3 If the argument is a character for which isupper is true and there are one or more
corresponding characters, as specified by the current locale, for which islower is true,
the tolower function returns one of the corresponding characters (always the same one
for any given locale); otherwise, the argument is returned unchanged.
<IP_ADDRESS> [The toupper function]
1 Synopsis
#include <ctype.h>
int toupper(int c);
Description
2 The toupper function converts a lowercase letter to a corresponding uppercase letter.
Returns
3 If the argument is a character for which islower is true and there are one or more
corresponding characters, as specified by the current locale, for which isupper is true,
the toupper function returns one of the corresponding characters (always the same one
for any given locale); otherwise, the argument is returned unchanged.
7.5 [Errors <errno.h>]
1 The header <errno.h> defines several macros, all relating to the reporting of error
conditions.
2 The macros are
EDOM
EILSEQ
ERANGE
which expand to integer constant expressions with type int, distinct positive values, and
which are suitable for use in #if preprocessing directives; and
errno
which expands to a modifiable lvalue[175] that has type int, the value of which is set to a
positive error number by several library functions. It is unspecified whether errno is a
macro or an identifier declared with external linkage. If a macro definition is suppressed
in order to access an actual object, or a program defines an identifier with the name
errno, the behavior is undefined.
Footnote 175) The macro errno need not be the identifier of an object. It might expand to a modifiable lvalue
resulting from a function call (for example, *errno()).
3 The value of errno is zero at program startup, but is never set to zero by any library
function.[176] The value of errno may be set to nonzero by a library function call
whether or not there is an error, provided the use of errno is not documented in the
description of the function in this International Standard.
Footnote 176) Thus, a program that uses errno for error checking should set it to zero before a library function call,
then inspect it before a subsequent library function call. Of course, a library function can save the
value of errno on entry and then set it to zero, as long as the original value is restored if errno’s
value is still zero just before the return.
4 Additional macro definitions, beginning with E and a digit or E and an uppercase
letter,[177] may also be specified by the implementation.
Footnote 177) See ‘‘future library directions’’ (7.26.3).
7.6 [Floating-point environment <fenv.h>]
1 The header <fenv.h> declares two types and several macros and functions to provide
access to the floating-point environment. The floating-point environment refers
collectively to any floating-point status flags and control modes supported by the
implementation.[178] A floating-point status flag is a system variable whose value is set
(but never cleared) when a floating-point exception is raised, which occurs as a side effect
of exceptional floating-point arithmetic to provide auxiliary information.[179] A floating-
point control mode is a system variable whose value may be set by the user to affect the
subsequent behavior of floating-point arithmetic.
Footnote 178) This header is designed to support the floating-point exception status flags and directed-rounding
control modes required by IEC 60559, and other similar floating-point state information. Also it is
designed to facilitate code portability among all systems.
Footnote 179) A floating-point status flag is not an object and can be set more than once within an expression.
2 Certain programming conventions support the intended model of use for the floating-
point environment:[180]
— a function call does not alter its caller’s floating-point control modes, clear its caller’s
floating-point status flags, nor depend on the state of its caller’s floating-point status
flags unless the function is so documented;
— a function call is assumed to require default floating-point control modes, unless its
documentation promises otherwise;
— a function call is assumed to have the potential for raising floating-point exceptions,
unless its documentation promises otherwise.
Footnote 180) With these conventions, a programmer can safely assume default floating-point control modes (or be
unaware of them). The responsibilities associated with accessing the floating-point environment fall
on the programmer or program that does so explicitly.
3 The type
fenv_t
represents the entire floating-point environment.
4 The type
fexcept_t
represents the floating-point status flags collectively, including any status the
implementation associates with the flags.
5 Each of the macros
FE_DIVBYZERO
FE_INEXACT
FE_INVALID
FE_OVERFLOW
FE_UNDERFLOW
is defined if and only if the implementation supports the floating-point exception by
means of the functions in 7.6.2.[181] Additional implementation-defined floating-point
exceptions, with macro definitions beginning with FE_ and an uppercase letter, may also
be specified by the implementation. The defined macros expand to integer constant
expressions with values such that bitwise ORs of all combinations of the macros result in
distinct values, and furthermore, bitwise ANDs of all combinations of the macros result in
zero.[182]
Footnote 181) The implementation supports an exception if there are circumstances where a call to at least one of the
functions in 7.6.2, using the macro as the appropriate argument, will succeed. It is not necessary for
all the functions to succeed all the time.
Footnote 182) The macros should be distinct powers of two.
6 The macro
FE_ALL_EXCEPT
is simply the bitwise OR of all floating-point exception macros defined by the
implementation. If no such macros are defined, FE_ALL_EXCEPT shall be defined as 0.
7 Each of the macros
FE_DOWNWARD
FE_TONEAREST
FE_TOWARDZERO
FE_UPWARD
is defined if and only if the implementation supports getting and setting the represented
rounding direction by means of the fegetround and fesetround functions.
Additional implementation-defined rounding directions, with macro definitions beginning
with FE_ and an uppercase letter, may also be specified by the implementation. The
defined macros expand to integer constant expressions whose values are distinct
nonnegative values.[183]
Footnote 183) Even though the rounding direction macros may expand to constants corresponding to the values of
FLT_ROUNDS, they are not required to do so.
8 The macro
FE_DFL_ENV
represents the default floating-point environment — the one installed at program startup
— and has type ‘‘pointer to const-qualified fenv_t’’. It can be used as an argument to
<fenv.h> functions that manage the floating-point environment.
9 Additional implementation-defined environments, with macro definitions beginning with
FE_ and an uppercase letter, and having type ‘‘pointer to const-qualified fenv_t’’, may
also be specified by the implementation.
7.6.1 [The FENV_ACCESS pragma]
1 Synopsis
#include <fenv.h>
#pragma STDC FENV_ACCESS on-off-switch
Description
2 The FENV_ACCESS pragma provides a means to inform the implementation when a
program might access the floating-point environment to test floating-point status flags or
run under non-default floating-point control modes.[184] The pragma shall occur either
outside external declarations or preceding all explicit declarations and statements inside a
compound statement. When outside external declarations, the pragma takes effect from
its occurrence until another FENV_ACCESS pragma is encountered, or until the end of
the translation unit. When inside a compound statement, the pragma takes effect from its
occurrence until another FENV_ACCESS pragma is encountered (including within a
nested compound statement), or until the end of the compound statement; at the end of a
compound statement the state for the pragma is restored to its condition just before the
compound statement. If this pragma is used in any other context, the behavior is
undefined. If part of a program tests floating-point status flags, sets floating-point control
modes, or runs under non-default mode settings, but was translated with the state for the
FENV_ACCESS pragma ‘‘off’’, the behavior is undefined. The default state (‘‘on’’ or
‘‘off’’) for the pragma is implementation-defined. (When execution passes from a part of
the program translated with FENV_ACCESS ‘‘off’’ to a part translated with
FENV_ACCESS ‘‘on’’, the state of the floating-point status flags is unspecified and the
floating-point control modes have their default settings.)
Footnote 184) The purpose of the FENV_ACCESS pragma is to allow certain optimizations that could subvert flag
tests and mode changes (e.g., global common subexpression elimination, code motion, and constant
folding). In general, if the state of FENV_ACCESS is ‘‘off’’, the translator can assume that default
modes are in effect and the flags are not tested.
3 EXAMPLE
#include <fenv.h>
void f(double x)
{
#pragma STDC FENV_ACCESS ON
void g(double);
void h(double);
/* ... */
g(x + 1);
h(x + 1);
/* ... */
}
4 If the function g might depend on status flags set as a side effect of the first x + 1, or if the second
x + 1 might depend on control modes set as a side effect of the call to function g, then the program shall
contain an appropriately placed invocation of #pragma STDC FENV_ACCESS ON.[185]
Footnote 185) The side effects impose a temporal ordering that requires two evaluations of x + 1. On the other
hand, without the #pragma STDC FENV_ACCESS ON pragma, and assuming the default state is
‘‘off’’, just one evaluation of x + 1 would suffice.
7.6.2 [Floating-point exceptions]
1 The following functions provide access to the floating-point status flags.[186] The int
input argument for the functions represents a subset of floating-point exceptions, and can
be zero or the bitwise OR of one or more floating-point exception macros, for example
FE_OVERFLOW | FE_INEXACT. For other argument values the behavior of these
functions is undefined.
Footnote 186) The functions fetestexcept, feraiseexcept, and feclearexcept support the basic
abstraction of flags that are either set or clear. An implementation may endow floating-point status
flags with more information — for example, the address of the code which first raised the floating-
point exception; the functions fegetexceptflag and fesetexceptflag deal with the full
content of flags.
<IP_ADDRESS> [The feclearexcept function]
1 Synopsis
#include <fenv.h>
int feclearexcept(int excepts);
Description
2 The feclearexcept function attempts to clear the supported floating-point exceptions
represented by its argument.
Returns
3 The feclearexcept function returns zero if the excepts argument is zero or if all
the specified exceptions were successfully cleared. Otherwise, it returns a nonzero value.
<IP_ADDRESS> [The fegetexceptflag function]
1 Synopsis
#include <fenv.h>
int fegetexceptflag(fexcept_t *flagp,
int excepts);
Description
2 The fegetexceptflag function attempts to store an implementation-defined
representation of the states of the floating-point status flags indicated by the argument
excepts in the object pointed to by the argument flagp.
Returns
3 The fegetexceptflag function returns zero if the representation was successfully
stored. Otherwise, it returns a nonzero value.
<IP_ADDRESS> [The feraiseexcept function]
1 Synopsis
#include <fenv.h>
int feraiseexcept(int excepts);
Description
2 The feraiseexcept function attempts to raise the supported floating-point exceptions
represented by its argument.[187] The order in which these floating-point exceptions are
raised is unspecified, except as stated in F.7.6. Whether the feraiseexcept function
additionally raises the ‘‘inexact’’ floating-point exception whenever it raises the
‘‘overflow’’ or ‘‘underflow’’ floating-point exception is implementation-defined.
Returns
Footnote 187) The effect is intended to be similar to that of floating-point exceptions raised by arithmetic operations.
Hence, enabled traps for floating-point exceptions raised by this function are taken. The specification
in F.7.6 is in the same spirit.
3 The feraiseexcept function returns zero if the excepts argument is zero or if all
the specified exceptions were successfully raised. Otherwise, it returns a nonzero value.
<IP_ADDRESS> [The fesetexceptflag function]
1 Synopsis
#include <fenv.h>
int fesetexceptflag(const fexcept_t *flagp,
int excepts);
Description
2 The fesetexceptflag function attempts to set the floating-point status flags
indicated by the argument excepts to the states stored in the object pointed to by
flagp. The value of *flagp shall have been set by a previous call to
fegetexceptflag whose second argument represented at least those floating-point
exceptions represented by the argument excepts. This function does not raise floating-
point exceptions, but only sets the state of the flags.
Returns
3 The fesetexceptflag function returns zero if the excepts argument is zero or if
all the specified flags were successfully set to the appropriate state. Otherwise, it returns
a nonzero value.
<IP_ADDRESS> [The fetestexcept function]
1 Synopsis
#include <fenv.h>
int fetestexcept(int excepts);
Description
2 The fetestexcept function determines which of a specified subset of the floating-
point exception flags are currently set. The excepts argument specifies the floating-
point status flags to be queried.[188]
Returns
Footnote 188) This mechanism allows testing several floating-point exceptions with just one function call.
3 The fetestexcept function returns the value of the bitwise OR of the floating-point
exception macros corresponding to the currently set floating-point exceptions included in
excepts.
4 EXAMPLE Call f if ‘‘invalid’’ is set, then g if ‘‘overflow’’ is set:
#include <fenv.h>
/* ... */
{
#pragma STDC FENV_ACCESS ON
int set_excepts;
feclearexcept(FE_INVALID | FE_OVERFLOW);
// maybe raise exceptions
set_excepts = fetestexcept(FE_INVALID | FE_OVERFLOW);
if (set_excepts & FE_INVALID) f();
if (set_excepts & FE_OVERFLOW) g();
/* ... */
}
7.6.3 [Rounding]
1 The fegetround and fesetround functions provide control of rounding direction
modes.
<IP_ADDRESS> [The fegetround function]
1 Synopsis
#include <fenv.h>
int fegetround(void);
Description
2 The fegetround function gets the current rounding direction.
Returns
3 The fegetround function returns the value of the rounding direction macro
representing the current rounding direction or a negative value if there is no such
rounding direction macro or the current rounding direction is not determinable.
<IP_ADDRESS> [The fesetround function]
1 Synopsis
#include <fenv.h>
int fesetround(int round);
Description
2 The fesetround function establishes the rounding direction represented by its
argument round. If the argument is not equal to the value of a rounding direction macro,
the rounding direction is not changed.
Returns
3 The fesetround function returns zero if and only if the requested rounding direction
was established.
4 EXAMPLE Save, set, and restore the rounding direction. Report an error and abort if setting the
rounding direction fails.
#include <fenv.h>
#include <assert.h>
void f(int round_dir)
{
#pragma STDC FENV_ACCESS ON
int save_round;
int setround_ok;
save_round = fegetround();
setround_ok = fesetround(round_dir);
assert(setround_ok == 0);
/* ... */
fesetround(save_round);
/* ... */
}
7.6.4 [Environment]
1 The functions in this section manage the floating-point environment — status flags and
control modes — as one entity.
<IP_ADDRESS> [The fegetenv function]
1 Synopsis
#include <fenv.h>
int fegetenv(fenv_t *envp);
Description
2 The fegetenv function attempts to store the current floating-point environment in the
object pointed to by envp.
Returns
3 The fegetenv function returns zero if the environment was successfully stored.
Otherwise, it returns a nonzero value.
<IP_ADDRESS> [The feholdexcept function]
1 Synopsis
#include <fenv.h>
int feholdexcept(fenv_t *envp);
Description
2 The feholdexcept function saves the current floating-point environment in the object
pointed to by envp, clears the floating-point status flags, and then installs a non-stop
(continue on floating-point exceptions) mode, if available, for all floating-point
exceptions.[189]
Returns
Footnote 189) IEC 60559 systems have a default non-stop mode, and typically at least one other mode for trap
handling or aborting; if the system provides only the non-stop mode then installing it is trivial. For
such systems, the feholdexcept function can be used in conjunction with the feupdateenv
function to write routines that hide spurious floating-point exceptions from their callers.
3 The feholdexcept function returns zero if and only if non-stop floating-point
exception handling was successfully installed.
<IP_ADDRESS> [The fesetenv function]
1 Synopsis
#include <fenv.h>
int fesetenv(const fenv_t *envp);
Description
2 The fesetenv function attempts to establish the floating-point environment represented
by the object pointed to by envp. The argument envp shall point to an object set by a
call to fegetenv or feholdexcept, or equal a floating-point environment macro.
Note that fesetenv merely installs the state of the floating-point status flags
represented through its argument, and does not raise these floating-point exceptions.
Returns
3 The fesetenv function returns zero if the environment was successfully established.
Otherwise, it returns a nonzero value.
<IP_ADDRESS> [The feupdateenv function]
1 Synopsis
#include <fenv.h>
int feupdateenv(const fenv_t *envp);
Description
2 The feupdateenv function attempts to save the currently raised floating-point
exceptions in its automatic storage, install the floating-point environment represented by
the object pointed to by envp, and then raise the saved floating-point exceptions. The
argument envp shall point to an object set by a call to feholdexcept or fegetenv,
or equal a floating-point environment macro.
Returns
3 The feupdateenv function returns zero if all the actions were successfully carried out.
Otherwise, it returns a nonzero value.
4 EXAMPLE Hide spurious underflow floating-point exceptions:
#include <fenv.h>
double f(double x)
{
#pragma STDC FENV_ACCESS ON
double result;
fenv_t save_env;
if (feholdexcept(&save_env))
return /* indication of an environmental problem */;
// compute result
if (/* test spurious underflow */)
if (feclearexcept(FE_UNDERFLOW))
return /* indication of an environmental problem */;
if (feupdateenv(&save_env))
return /* indication of an environmental problem */;
return result;
}
7.7 [Characteristics of floating types <float.h>]
1 The header <float.h> defines several macros that expand to various limits and
parameters of the standard floating-point types.
2 The macros, their meanings, and the constraints (or restrictions) on their values are listed
in <IP_ADDRESS>.2.
7.8 [Format conversion of integer types <inttypes.h>]
1 The header <inttypes.h> includes the header <stdint.h> and extends it with
additional facilities provided by hosted implementations.
2 It declares functions for manipulating greatest-width integers and converting numeric
character strings to greatest-width integers, and it declares the type
imaxdiv_t
which is a structure type that is the type of the value returned by the imaxdiv function.
For each type declared in <stdint.h>, it defines corresponding macros for conversion
specifiers for use with the formatted input/output functions.[190]
Forward references: integer types <stdint.h> (7.18), formatted input/output
functions (7.19.6), formatted wide character input/output functions (7.24.2).
Footnote 190) See ‘‘future library directions’’ (7.26.4).
7.8.1 [Macros for format specifiers]
1 Each of the following object-like macros[191] expands to a character string literal
containing a conversion specifier, possibly modified by a length modifier, suitable for use
within the format argument of a formatted input/output function when converting the
corresponding integer type. These macro names have the general form of PRI (character
string literals for the fprintf and fwprintf family) or SCN (character string literals
for the fscanf and fwscanf family),[192] followed by the conversion specifier,
followed by a name corresponding to a similar type name in 7.18.1. In these names, N
represents the width of the type as described in 7.18.1. For example, PRIdFAST32 can
be used in a format string to print the value of an integer of type int_fast32_t.
Footnote 191) C++ implementations should define these macros only when _ _STDC_FORMAT_MACROS is defined
before <inttypes.h> is included.
Footnote 192) Separate macros are given for use with fprintf and fscanf functions because, in the general case,
different format specifiers may be required for fprintf and fscanf, even when the type is the
same.
2 The fprintf macros for signed integers are:
PRIdN PRIdLEASTN PRIdFASTN PRIdMAX PRIdPTR
PRIiN PRIiLEASTN PRIiFASTN PRIiMAX PRIiPTR
3 The fprintf macros for unsigned integers are:
PRIoN PRIoLEASTN PRIoFASTN PRIoMAX PRIoPTR
PRIuN PRIuLEASTN PRIuFASTN PRIuMAX PRIuPTR
PRIxN PRIxLEASTN PRIxFASTN PRIxMAX PRIxPTR
PRIXN PRIXLEASTN PRIXFASTN PRIXMAX PRIXPTR
4 The fscanf macros for signed integers are:
SCNdN SCNdLEASTN SCNdFASTN SCNdMAX SCNdPTR
SCNiN SCNiLEASTN SCNiFASTN SCNiMAX SCNiPTR
5 The fscanf macros for unsigned integers are:
SCNoN SCNoLEASTN SCNoFASTN SCNoMAX SCNoPTR
SCNuN SCNuLEASTN SCNuFASTN SCNuMAX SCNuPTR
SCNxN SCNxLEASTN SCNxFASTN SCNxMAX SCNxPTR
6 For each type that the implementation provides in <stdint.h>, the corresponding
fprintf macros shall be defined and the corresponding fscanf macros shall be
defined unless the implementation does not have a suitable fscanf length modifier for
the type.
7 EXAMPLE
#include <inttypes.h>
#include <wchar.h>
int main(void)
{
uintmax_t i = UINTMAX_MAX; // this type always exists
wprintf(L"The largest integer value is %020"
PRIxMAX "\n", i);
return 0;
}
7.8.2 [Functions for greatest-width integer types]
<IP_ADDRESS> [The imaxabs function]
1 Synopsis
#include <inttypes.h>
intmax_t imaxabs(intmax_t j);
Description
2 The imaxabs function computes the absolute value of an integer j. If the result cannot
be represented, the behavior is undefined.[193]
Returns
Footnote 193) The absolute value of the most negative number cannot be represented in two’s complement.
3 The imaxabs function returns the absolute value.
<IP_ADDRESS> [The imaxdiv function]
1 Synopsis
#include <inttypes.h>
imaxdiv_t imaxdiv(intmax_t numer, intmax_t denom);
Description
2 The imaxdiv function computes numer / denom and numer % denom in a single
operation.
Returns
3 The imaxdiv function returns a structure of type imaxdiv_t comprising both the
quotient and the remainder. The structure shall contain (in either order) the members
quot (the quotient) and rem (the remainder), each of which has type intmax_t. If
either part of the result cannot be represented, the behavior is undefined.
<IP_ADDRESS> [The strtoimax and strtoumax functions]
1 Synopsis
#include <inttypes.h>
intmax_t strtoimax(const char * restrict nptr,
char ** restrict endptr, int base);
uintmax_t strtoumax(const char * restrict nptr,
char ** restrict endptr, int base);
Description
2 The strtoimax and strtoumax functions are equivalent to the strtol, strtoll,
strtoul, and strtoull functions, except that the initial portion of the string is
converted to intmax_t and uintmax_t representation, respectively.
Returns
3 The strtoimax and strtoumax functions return the converted value, if any. If no
conversion could be performed, zero is returned. If the correct value is outside the range
of representable values, INTMAX_MAX, INTMAX_MIN, or UINTMAX_MAX is returned
(according to the return type and sign of the value, if any), and the value of the macro
ERANGE is stored in errno.
Forward references: the strtol, strtoll, strtoul, and strtoull functions
(<IP_ADDRESS>).
<IP_ADDRESS> [The wcstoimax and wcstoumax functions]
1 Synopsis
#include <stddef.h> // for wchar_t
#include <inttypes.h>
intmax_t wcstoimax(const wchar_t * restrict nptr,
wchar_t ** restrict endptr, int base);
uintmax_t wcstoumax(const wchar_t * restrict nptr,
wchar_t ** restrict endptr, int base);
Description