code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
c _Alignof operator \_Alignof operator
==================
Queries the alignment requirement of its operand type.
### Syntax
| | | |
| --- | --- | --- |
| `_Alignof(` type-name `)` | | (since C11) |
This operator is typically used through the convenience macro [`alignof`](../types "c/types"), which is provided in the header `stdalign.h`.
### Explanation
Returns the [alignment requirement](object#Alignment "c/language/object") of the type [named](type#Type_names "c/language/type") by type-name. If type-name is an array type, the result is the alignment requirement of the array element type. The type-name cannot be function type or an incomplete type.
The result is an integer constant of type `[size\_t](../types/size_t "c/types/size t")`.
The operand is not evaluated (so external identifiers used in the operand do not have to be defined).
If type-name is a [VLA](array "c/language/array") type, its size expression is not evaluated.
### Notes
The use of `_Alignof` with expressions is allowed by some C compilers as a non-standard extension.
### Keywords
[`_Alignof`](../keyword/_alignof "c/keyword/ Alignof").
### Example
```
#include <stdio.h>
#include <stddef.h>
#include <stdalign.h>
int main(void)
{
printf("Alignment of char = %zu\n", alignof(char));
printf("Alignment of max_align_t = %zu\n", alignof(max_align_t));
printf("alignof(float[10]) = %zu\n", alignof(float[10]));
printf("alignof(struct{char c; int n;}) = %zu\n",
alignof(struct {char c; int n;}));
}
```
Possible output:
```
Alignment of char = 1
Alignment of max_align_t = 16
alignof(float[10]) = 4
alignof(struct{char c; int n;}) = 4
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [DR 494](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_494) | C11 | whether the size expression in a VLA is evaluated in `_Alignof` was unspecified | it is unevaluated |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.5.3.4 The sizeof and \_Alignof operators (p: 64-65)
* C11 standard (ISO/IEC 9899:2011):
+ 6.5.3.4 The sizeof and \_Alignof operators (p: 90-91)
### See also
| | |
| --- | --- |
| [max\_align\_t](../types/max_align_t "c/types/max align t")
(C11) | a type with alignment requirement as great as any other scalar type (typedef) |
| [`_Alignas` specifier](_alignas "c/language/ Alignas")(C11) | sets alignment requirements of an object |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/alignof "cpp/language/alignof") for `alignof operator` |
c continue statement continue statement
==================
Causes the remaining portion of the enclosing [for](for "c/language/for"), [while](while "c/language/while") or [do-while](do "c/language/do") loop body to be skipped.
Used when it is otherwise awkward to ignore the remaining portion of the loop using conditional statements.
### Syntax
| | | |
| --- | --- | --- |
| attr-spec-seq(optional) `continue` `;` | | |
| | | |
| --- | --- | --- |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the `continue` statement |
### Explanation
The `continue` statement causes a jump, as if by [goto](goto "c/language/goto"), to the end of the loop body (it may only appear within the loop body of [for](for "c/language/for"), [while](while "c/language/while"), and [do-while](do "c/language/do") loops).
For [while](while "c/language/while") loop, it acts as.
```
while (/* ... */) {
// ...
continue; // acts as goto contin;
// ...
contin:;
}
```
For [do-while](do "c/language/do") loop, it acts as:
```
do {
// ...
continue; // acts as goto contin;
// ...
contin:;
} while (/* ... */);
```
For [for](for "c/language/for") loop, it acts as:
```
for (/* ... */) {
// ...
continue; // acts as goto contin;
// ...
contin:;
}
```
### Keywords
[`continue`](../keyword/continue "c/keyword/continue").
### Example
```
#include <stdio.h>
int main(void)
{
for (int i = 0; i < 10; i++) {
if (i != 5) continue;
printf("%d ", i); // this statement is skipped each time i != 5
}
printf("\n");
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 5; k++) { // only this loop is affected by continue
if (k == 3) continue;
printf("%d%d ", j, k); // this statement is skipped each time k == 3
}
}
}
```
Output:
```
5
00 01 02 04 10 11 12 14
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.8.6.2 The continue statement (p: 111)
* C11 standard (ISO/IEC 9899:2011):
+ 6.8.6.2 The continue statement (p: 153)
* C99 standard (ISO/IEC 9899:1999):
+ 6.8.6.2 The continue statement (p: 138)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.6.6.2 The continue statement
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/continue "cpp/language/continue") for `continue` statement |
c Union declaration Union declaration
=================
A union is a type consisting of a sequence of members whose storage overlaps (as opposed to struct, which is a type consisting of a sequence of members whose storage is allocated in an ordered sequence). The value of at most one of the members can be stored in a union at any one time.
The [type specifier](declarations "c/language/declarations") for a union is identical to the [`struct`](struct "c/language/struct") type specifier except for the keyword used:
### Syntax
| | | |
| --- | --- | --- |
| `union` attr-spec-seq(optional) name(optional) `{` struct-declaration-list `}` | (1) | |
| `union` attr-spec-seq(optional) name | (2) | |
| | | |
| --- | --- | --- |
| name | - | the name of the union that's being defined |
| struct-declaration-list | - | any number of variable declarations, bit field declarations, and static assert declarations. Members of incomplete type and members of function type are not allowed. |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the union type, not allowed for (2) if such form is not followed by a `;` (i.e. not a forward declaration). |
### Explanation
The union is only as big as necessary to hold its largest member (additional unnamed trailing padding may also be added). The other members are allocated in the same bytes as part of that largest member.
A pointer to a union can be cast to a pointer to each of its members (if a union has bit field members, the pointer to a union can be cast to the pointer to the bit field's underlying type). Likewise, a pointer to any member of a union can be cast to a pointer to the enclosing union.
| | |
| --- | --- |
| If the member used to access the contents of a union is not the same as the member last used to store a value, the object representation of the value that was stored is reinterpreted as an object representation of the new type (this is known as *type punning*). If the size of the new type is larger than the size of the last-written type, the contents of the excess bytes are unspecified (and may be a trap representation). Before C99 TC3 (DR 283) this behaviour was undefined, but commonly implemented this way. | (since C99) |
| | |
| --- | --- |
| Similar to struct, an unnamed member of a union whose type is a union without name is known as *anonymous union*. Every member of an anonymous union is considered to be a member of the enclosing struct or union. This applies recursively if the enclosing struct or union is also anonymous.
```
struct v {
union { // anonymous union
struct { int i, j; }; // anonymous structure
struct { long k, l; } w;
};
int m;
} v1;
v1.i = 2; // valid
v1.k = 3; // invalid: inner structure is not anonymous
v1.w.k = 5; // valid
```
Similar to struct, the behavior of the program is undefined if union is defined without any named members (including those obtained via anonymous nested structs or unions). | (since C11) |
### Keywords
[`union`](../keyword/union "c/keyword/union").
### Notes
See [struct initialization](struct_initialization "c/language/struct initialization") for the rules about initialization of structs and unions.
### Example
```
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
int main(void)
{
union S {
uint32_t u32;
uint16_t u16[2];
uint8_t u8;
} s = {0x12345678}; // s.u32 is now the active member
printf("Union S has size %zu and holds %x\n", sizeof s, s.u32);
s.u16[0] = 0x0011; // s.u16 is now the active member
// reading from s.u32 or from s.u8 reinterprets the object representation
// printf("s.u8 is now %x\n", s.u8); // unspecified, typically 11 or 00
// printf("s.u32 is now %x\n", s.u32); // unspecified, typically 12340011 or 00115678
// pointers to all members of a union compare equal to themselves and the union
assert((uint8_t*)&s == &s.u8);
// this union has 3 bytes of trailing padding
union pad {
char c[5]; // occupies 5 bytes
float f; // occupies 4 bytes, imposes alignment 4
} p = {.f = 1.23}; // the size is 8 to satisfy float's alignment
printf("size of union of char[5] and float is %zu\n", sizeof p);
}
```
Possible output:
```
Union S has size 4 and holds 12345678
size of union of char[5] and float is 8
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.2.1 Structure and union specifiers (p: 81-84)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.2.1 Structure and union specifiers (p: 112-117)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.2.1 Structure and union specifiers (p: 101-104)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.5.2.1 Structure and union specifiers
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/union "cpp/language/union") for Union declaration |
c Comparison operators Comparison operators
====================
Comparison operators are binary operators that test a condition and return **1** if that condition is logically **true** and **0** if that condition is **false**.
| Operator | Operator name | Example | Description |
| --- | --- | --- | --- |
| `==` | equal to | `a == b` | **a** is equal to **b** |
| `!=` | not equal to | `a != b` | **a** is not equal to **b** |
| `<` | less than | `a < b` | **a** is less than **b** |
| `>` | greater than | `a > b` | **a** is greater than **b** |
| `<=` | less than or equal to | `a <= b` | **a** is less than or equal to **b** |
| `>=` | greater than or equal to | `a >= b` | **a** is greater than or equal to **b** |
### Relational operators
The relational operator expressions have the form.
| | | |
| --- | --- | --- |
| lhs `<` rhs | (1) | |
| lhs `>` rhs | (2) | |
| lhs `<=` rhs | (3) | |
| lhs `>=` rhs | (4) | |
1) less-than expression
2) greater-than expression
3) less or equal expression
4) greater or equal expression where.
| | | |
| --- | --- | --- |
| lhs, rhs | - | expressions that both have real type or both have pointer to object type |
The type of any relational operator expression is `int`, and its value (which is not an lvalue) is `1` when the specified relationship holds true and `0` when the specified relationship does not hold.
If lhs and rhs are expressions of any [real type](types "c/language/types"), then.
* [usual arithmetic conversions](conversion#Usual_arithmetic_conversions "c/language/conversion") are performed
* the values of the operands after conversion are compared in the usual mathematical sense (except that positive and negative zeroes compare equal and any comparison involving a NaN value returns zero)
Note that complex and imaginary numbers cannot be compared with these operators.
If lhs and rhs are expressions of pointer type, they must be both pointers to objects of [compatible types](types#Compatible_types "c/language/types"), except that qualifications of the pointed-to objects are ignored.
* a pointer to an object that is not an element of an array is treated as if it were pointing to an element of an array with one element
* if two pointers point to the same object, or both point one past the end of the same array, they compare equal
* if two pointers point to different elements of the same array, the one pointing at the element with the larger index compares greater.
* if one pointer points to the element of an array and the other pointer points one past the end of the same array, the one-past-the-end pointer compares greater
* if the two pointers point to members of the same [struct](struct "c/language/struct"), the pointer to the member declared later in the struct definition compares greater than then pointer to the member declared earlier.
* pointers to members of the same union compare equal
* all other pointer comparisons invoke undefined behavior
```
#include <assert.h>
int main(void)
{
assert(1 < 2);
assert(2+2 <= 4.0); // int converts to double, two 4.0's compare equal
struct { int x,y; } s;
assert(&s.x < &s.y); // struct members compare in order of declaration
double d = 0.0/0.0; // NaN
assert( !(d < d) );
assert( !(d > d) );
assert( !(d <= d) );
assert( !(d >= d) );
assert( !(d == d) );
float f = 0.1; // f = 0.100000001490116119384765625
double g = 0.1; // g = 0.1000000000000000055511151231257827021181583404541015625
assert(f > g); // different values
}
```
### Equality operators
The equality operator expressions have the form.
| | | |
| --- | --- | --- |
| lhs `==` rhs | (1) | |
| lhs `!=` rhs | (2) | |
1) equal-to expression
2) not equal to expression where.
| | | | | |
| --- | --- | --- | --- | --- |
| lhs, rhs | - | expressions that * both have any [arithmetic types](arithmetic_types "c/language/arithmetic types") (including complex and imaginary)
| | |
| --- | --- |
| * both have type `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")`
* one has type `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` and the other is a null pointer constant
| (since C23) |
* both are pointers to objects or functions of [compatible](types#Compatible_types "c/language/types") types, ignoring qualifiers of the pointed-to types
* one is a pointer to object and the other is a pointer to (possibly qualified) `void`
* one is a pointer to object or function and the other is a null pointer constant such as `[NULL](../types/null "c/types/NULL")` or `nullptr` (since C23)
|
The type of any equality operator expression is `int`, and its value (which is not an lvalue) is `1` when the specified relationship holds true and `0` when the specified relationship does not hold.
* if both operands have arithmetic types, [usual arithmetic conversions](conversion#Usual_arithmetic_conversions "c/language/conversion") are performed and the resulting values are compared in the usual mathematical sense (except that positive and negative zeroes compare equal and any comparison involving a NaN value, including equality with itself, returns zero). In particular, values of complex type are equal if their real parts compare equal and their imaginary parts compare equal.
| | |
| --- | --- |
| * two `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` value or one `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` value and a null pointer constant compare equal
| (since C23) |
* if one operand is a pointer and the other is a null pointer constant, the null pointer constant is first [converted](conversion "c/language/conversion") to the type of the pointer (which gives a null pointer value), and the two pointers are compared as described below
* if one operand is a pointer and the other is a pointer to void, the non-void pointer is [converted](conversion "c/language/conversion") to the pointer to void and the two pointers are compared as described below
* two pointers compare equal if any of the following is true:
+ they are both null pointer values of their type
+ they are both pointers to the same object
+ one pointer is to a struct/union/array object and the other is to its first member/any member/first element
+ they are both pointing one past the last element of the same array
+ one is one past the end of an array, and the other is at the start of a different array (of the same type) that follows the first in a larger array or in a struct with no padding
(as with relational operators, pointers to objects that aren't elements of any array behave as pointers to elements of arrays of size 1).
#### Notes
Objects of struct type do not compare equal automatically, and comparing them with `[memcmp](../string/byte/memcmp "c/string/byte/memcmp")` is not reliable because the padding bytes may have any values.
Because pointer comparison works with pointers to void, the macro `[NULL](../types/null "c/types/NULL")` may be defined as `(void*)0` in C, although that would be invalid in C++ where void pointers do not implicitly convert to typed pointers.
Care must be taken when comparing floating-point values for equality, because the results of many operations cannot be represented exactly and must be rounded. In practice, floating-point numbers are usually compared allowing for the difference of one or more units of the last place.
```
#include <assert.h>
int main(void)
{
assert(2+2 == 4.0); // int converts to double, two 4.0's compare equal
int n[2][3] = {1,2,3,4,5,6};
int* p1 = &n[0][2]; // last element in the first row
int* p2 = &n[1][0]; // start of second row
assert(p1+1 == p2); // compare equal
double d = 0.0/0.0; // NaN
assert( d != d ); // NaN does not equal itself
float f = 0.1; // f = 0.100000001490116119384765625
double g = 0.1; // g = 0.1000000000000000055511151231257827021181583404541015625
assert(f != g); // different values
}
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.5.8 Relational operators (p: 68-69)
+ 6.5.9 Equality operators (p: 69-70)
* C11 standard (ISO/IEC 9899:2011):
+ 6.5.8 Relational operators (p: 95-96)
+ 6.5.9 Equality operators (p: 96-97)
* C99 standard (ISO/IEC 9899:1999):
+ 6.5.8 Relational operators (p: 85-86)
+ 6.5.9 Equality operators (p: 86-87)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.3.8 Relational operators
+ 3.3.9 Equality operators
### See also
[Operator precedence](operator_precedence "c/language/operator precedence").
| Common operators |
| --- |
| [assignment](operator_assignment "c/language/operator assignment") | [incrementdecrement](operator_incdec "c/language/operator incdec") | [arithmetic](operator_arithmetic "c/language/operator arithmetic") | [logical](operator_logical "c/language/operator logical") | **comparison** | [memberaccess](operator_member_access "c/language/operator member access") | [other](operator_other "c/language/operator other") |
| `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b`. | `a[b] *a &a a->b a.b`. | `a(...) a, b (type) a ? : sizeof _Alignof` (since C11). |
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_comparison "cpp/language/operator comparison") for Comparison operators |
c restrict type qualifier restrict type qualifier
=======================
Each individual type in the C [type system](type "c/language/type") has several *qualified* versions of that type, corresponding to one, two, or all three of the [const](const "c/language/const"), [volatile](volatile "c/language/volatile"), and, for pointers to object types, *restrict* qualifiers. This page describes the effects of the *restrict* qualifier.
Only a pointer to an [object type](type "c/language/type") or a (possibly multi-dimensional) array thereof (since C23) may be restrict-qualified; in particular, the following are *erroneous*:
* `int restrict *p`
* `float (* restrict f9)(void)`
Restrict semantics apply to lvalue expressions only; for example, a cast to restrict-qualified pointer or a function call returning a restrict-qualified pointer are not lvalues and the qualifier has no effect.
During each execution of a block in which a restricted pointer `P` is declared (typically each execution of a function body in which `P` is a function parameter), if some object that is accessible through `P` (directly or indirectly) is modified, by any means, then all accesses to that object (both reads and writes) in that block must occur through `P` (directly or indirectly), otherwise the behavior is undefined:
```
void f(int n, int * restrict p, int * restrict q)
{
while(n-- > 0)
*p++ = *q++; // none of the objects modified through *p is the same
// as any of the objects read through *q
// compiler free to optimize, vectorize, page map, etc.
}
void g(void)
{
extern int d[100];
f(50, d + 50, d); // OK
f(50, d + 1, d); // Undefined behavior: d[1] is accessed through both p and q in f
}
```
If the object is never modified, it may be aliased and accessed through different restrict-qualified pointers (note that if the objects pointed to by aliased restrict-qualified pointers are, in turn, pointers, this aliasing can inhibit optimization).
Assignment from one restricted pointer to another is undefined behavior, except when assigning from a pointer to an object in some outer block to a pointer in some inner block (including using a restricted pointer argument when calling a function with a restricted pointer parameter) or when returning from a function (and otherwise when the block of the from-pointer ended):
```
int* restrict p1 = &a;
int* restrict p2 = &b;
p1 = p2; // undefined behavior
```
Restricted pointers can be assigned to unrestricted pointers freely, the optimization opportunities remain in place as long as the compiler is able to analyze the code:
```
void f(int n, float * restrict r, float * restrict s) {
float * p = r, * q = s; // OK
while(n-- > 0) *p++ = *q++; // almost certainly optimized just like *r++ = *s++
}
```
| | |
| --- | --- |
| If an array type is declared with the restrict type qualifier (through the use of [typedef](typedef "c/language/typedef")), the array type is not restrict-qualified, but its element type is: | (until C23) |
| An array type and its element type are always considered to be identically restrict-qualified: | (since C23) |
```
typedef int *array_t[10];
restrict array_t a; // the type of a is int *restrict[10]
// Notes: clang and icc reject this on the grounds that array_t is not a pointer type
void *unqual_ptr = &a; // OK until C23; error since C23
// Notes: clang applies the rule in C++/C23 even in C89-C17 modes
```
In a function declaration, the keyword `restrict` may appear inside the square brackets that are used to declare an array type of a function parameter. It qualifies the pointer type to which the array type is transformed:
```
void f(int m, int n, float a[restrict m][n], float b[restrict m][n]);
void g12(int n, float (*p)[n]) {
f(10, n, p, p+10); // OK
f(20, n, p, p+10); // possibly undefined behavior (depending on what f does)
}
```
### Notes
The intended use of the restrict qualifier (like the register storage class) is to promote optimization, and deleting all instances of the qualifier from all preprocessing translation units composing a conforming program does not change its meaning (i.e., observable behavior).
The compiler is free to ignore any or all aliasing implications of uses of `restrict`.
To avoid undefined behavior, the programmer must ensure that the aliasing assertions made by the restrict-qualified pointers are not violated.
Many compilers provide, as a language extension, the opposite of `restrict`: an attribute indicating that pointers may alias even if their types differ: [may\_alias (gcc)](https://gcc.gnu.org/onlinedocs/gcc/Common-Type-Attributes.html#index-g_t_0040code_007bmay_005falias_007d-type-attribute-3667),
### Usage patterns
There are several common usage patterns for restrict-qualified pointers:
#### File scope
A file-scope restrict-qualified pointer has to point into a single array object for the duration of the program. That array object may not be referenced both through the restricted pointer and through either its declared name (if it has one) or another restricted pointer.
File scope restricted pointers are useful in providing access to dynamically allocated global arrays; the restrict semantics make it possible to optimize references through this pointer as effectively as references to a static array through its declared name:
```
float * restrict a, * restrict b;
float c[100];
int init(int n) {
float * t = malloc(2*n*sizeof(float));
a = t; // a refers to 1st half
b = t + n; // b refers to 2nd half
}
// compiler can deduce from the restrict qualifiers that
// there is no potential aliasing among the names a, b, and c
```
#### Function parameter
The most popular use case for restrict-qualified pointers is the use as function parameters.
In the following example, the compiler may infer that there is no aliasing of modified objects, and so optimize the loop aggressively. Upon entry to f, the restricted pointer a must provide exclusive access to its associated array. In particular, within f neither b nor c may point into the array associated with a, because neither is assigned a pointer value based on a. For b, this is evident from the const-qualifier in its declaration, but for c, an inspection of the body of f is required:
```
float x[100];
float *c;
void f(int n, float * restrict a, float * const b) {
int i;
for ( i=0; i<n; i++ )
a[i] = b[i] + c[i];
}
void g3(void) {
float d[100], e[100];
c = x; f(100, d, e); // OK
f( 50, d, d+50); // OK
f( 99, d+1, d); // undefined behavior
c = d; f( 99, d+1, e); // undefined behavior
f( 99, e, d+1); // OK
}
```
Note that it is permitted for c to point into the array associated with b. Note also that, for these purposes, the "array" associated with a particular pointer means only that portion of an array object which is actually referenced through that pointer.
Note that in the example above, the compiler can infer that a and b do not alias because b's constness guarantees that it cannot become dependent on a in the body of the function. Equivalently, the programmer could write `void f(int n, float * a, float const * restrict b)`, in which case the compiler can reason that objects referenced through b cannot be modified, and so no modified object can be referenced using both b and a. If the programmer were to write `void f(int n, float * restrict a, float * b)`, the compiler would be unable to infer non-aliasing of a and b without examining the body of the function.
In general, it is best to explicitly annotate all non-aliasing pointers in a function's prototype with `restrict`.
#### Block scope
A block scope restrict-qualified pointer makes an aliasing assertion that is limited to its block. It allows local assertions that apply only to important blocks, such as tight loops. It also makes it possible to convert a function that takes restrict-qualified pointers into a macro:
```
float x[100];
float *c;
#define f3(N, A, B) \
do \
{ int n = (N); \
float * restrict a = (A); \
float * const b = (B); \
int i; \
for ( i=0; i<n; i++ ) \
a[i] = b[i] + c[i]; \
} while(0)
```
#### Struct members
The scope of the aliasing assertion made by a restrict-qualified pointer that is a member of a struct is the scope of the identifier used to access the struct.
Even if the struct is declared at file scope, when the identifier used to access the struct has block scope, the aliasing assertions in the struct also have block scope; the aliasing assertions are only in effect within a block execution or a function call, depending on how the object of this struct type was created:
```
struct t { // Restricted pointers assert that
int n; // members point to disjoint storage.
float * restrict p;
float * restrict q;
};
void ff(struct t r, struct t s) {
struct t u;
// r,s,u have block scope
// r.p, r.q, s.p, s.q, u.p, u.q should all point to
// disjoint storage during each execution of ff.
// ...
}
```
### Keywords
[`restrict`](../keyword/restrict "c/keyword/restrict").
### Example
code generation example; compile with -S (gcc, clang, etc) or /FA (visual studio).
```
int foo(int *a, int *b)
{
*a = 5;
*b = 6;
return *a + *b;
}
int rfoo(int *restrict a, int *restrict b)
{
*a = 5;
*b = 6;
return *a + *b;
}
```
Possible output:
```
; generated code on 64bit Intel platform:
foo:
movl $5, (%rdi) ; store 5 in *a
movl $6, (%rsi) ; store 6 in *b
movl (%rdi), %eax ; read back from *a in case previous store modified it
addl $6, %eax ; add 6 to the value read from *a
ret
rfoo:
movl $11, %eax ; the result is 11, a compile-time constant
movl $5, (%rdi) ; store 5 in *a
movl $6, (%rsi) ; store 6 in *b
ret
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.3.1 Formal definition of restrict (p: 89-90)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.3.1 Formal definition of restrict (p: 123-125)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.3.1 Formal definition of restrict (p: 110-112)
| programming_docs |
c Pointer declaration Pointer declaration
===================
Pointer is a type of an object that refers to a function or an object of another type, possibly adding qualifiers. Pointer may also refer to nothing, which is indicated by the special null pointer value.
### Syntax
In the [declaration grammar](declarations "c/language/declarations") of a pointer declaration, the type-specifier sequence designates the pointed-to type (which may be function or object type and may be incomplete), and the declarator has the form:
| | | |
| --- | --- | --- |
| `*` attr-spec-seq(optional) qualifiers(optional) declarator | | |
where declarator may be the identifier that names the pointer being declared, including another pointer declarator (which would indicate a pointer to a pointer):
```
float *p, **pp; // p is a pointer to float
// pp is a pointer to a pointer to float
int (*fp)(int); // fp is a pointer to function with type int(int)
```
The qualifiers that appear between `*` and the identifier (or other nested declarator) qualify the type of the pointer that is being declared:
```
int n;
const int * pc = &n; // pc is a non-const pointer to a const int
// *pc = 2; // Error: n cannot be changed through pc without a cast
pc = NULL; // OK: pc itself can be changed
int * const cp = &n; // cp is a const pointer to a non-const int
*cp = 2; // OK to change n through cp
// cp = NULL; // Error: cp itself cannot be changed
int * const * pcp = &cp; // non-const pointer to const pointer to non-const int
```
The attr-spec-seq(C23) is an optional list of [attributes](attributes "c/language/attributes"), applied to the declared pointer.
### Explanation
Pointers are used for indirection, which is a ubiquitous programming technique; they can be used to implement pass-by-reference semantics, to access objects with dynamic [storage duration](storage_duration "c/language/storage duration"), to implement "optional" types (using the null pointer value), aggregation relationship between structs, callbacks (using pointers to functions), generic interfaces (using pointers to void), and much more.
#### Pointers to objects
A pointer to object can be initialized with the result of the [address-of operator](operator_member_access "c/language/operator member access") applied to an expression of object type (which may be incomplete):
```
int n;
int *np = &n; // pointer to int
int *const *npp = &np; // non-const pointer to const pointer to non-const int
int a[2];
int (*ap)[2] = &a; // pointer to array of int
struct S { int n; } s = {1}
int* sp = &s.n; // pointer to the int that is a member of s
```
Pointers may appear as operands to the [indirection operator](operator_member_access#Dereference "c/language/operator member access") (unary `*`), which returns [the lvalue](value_category "c/language/value category") identifying the pointed-to object:
```
int n;
int* p = &n; // pointer p is pointing to n
*p = 7; // stores 7 in n
printf("%d\n", *p); // lvalue-to-rvalue conversion reads the value from n
```
Pointers to objects of [struct](struct "c/language/struct") and [union](union "c/language/union") type may also appear as the left-hand operands of the [member access through pointer](operator_member_access "c/language/operator member access") operator `->`.
Because of the [array-to-pointer](array "c/language/array") implicit conversion, pointer to the first element of an array can be initialized with an expression of array type:
```
int a[2];
int *p = a; // pointer to a[0]
int b[3][3];
int (*row)[3] = b; // pointer to b[0]
```
Certain [addition, subtraction](operator_arithmetic "c/language/operator arithmetic"), [compound assignment](operator_assignment "c/language/operator assignment"), [increment, and decrement](operator_incdec "c/language/operator incdec") operators are defined for pointers to elements of arrays.
[Comparison operators](operator_comparison "c/language/operator comparison") are defined for pointers to objects in some situations: two pointers that represent the same address compare equal, two null pointer values compare equal, pointers to elements of the same array compare the same as the array indexes of those elements, and pointers to struct members compare in order of declaration of those members.
Many implementations also provide [strict total ordering](https://en.wikipedia.org/wiki/Total_order#Strict_total_order "enwiki:Total order") of pointers of random origin, e.g. if they are implemented as addresses within continuous ("flat") virtual address space.
#### Pointers to functions
A pointer to function can be initialized with an address of a function. Because of the [function-to-pointer](conversion "c/language/conversion") conversion, the address-of operator is optional:
```
void f(int);
void (*pf1)(int) = &f;
void (*pf2)(int) = f; // same as &f
```
Unlike functions, pointers to functions are objects and thus can be stored in arrays, copied, assigned, passed to other functions as arguments, etc.
A pointer to function can be used on the left-hand side of the [function call operator](operator_other#Function_call "c/language/operator other"); this invokes the pointed-to function:
```
#include <stdio.h>
int f(int n)
{
printf("%d\n", n);
return n*n;
}
int main(void)
{
int (*p)(int) = f;
int x = p(7);
}
```
Dereferencing a function pointer yields the function designator for the pointed-to function:
```
int f();
int (*p)() = f; // pointer p is pointing to f
(*p)(); // function f invoked through the function designator
p(); // function f invoked directly through the pointer
```
[Equality comparison operators](operator_comparison "c/language/operator comparison") are defined for pointers to functions (they compare equal if pointing to the same function).
Because [compatibility of function types](type#Compatible_types "c/language/type") ignores top-level qualifiers of the function parameters, pointers to functions whose parameters only differ in their top-level qualifiers are interchangeable:
```
int f(int), fc(const int);
int (*pc)(const int) = f; // OK
int (*p)(int) = fc; // OK
pc = p; // OK
```
#### Pointers to void
Pointer to object of any type can be [implicitly converted](conversion "c/language/conversion") to pointer to `void` (optionally [const](const "c/language/const") or [volatile](volatile "c/language/volatile")-qualified), and vice versa:
```
int n=1, *p=&n;
void* pv = p; // int* to void*
int* p2 = pv; // void* to int*
printf("%d\n", *p2); // prints 1
```
Pointers to void are used to pass objects of unknown type, which is common in generic interfaces: `[malloc](../memory/malloc "c/memory/malloc")` returns `void*`, `[qsort](../algorithm/qsort "c/algorithm/qsort")` expects a user-provided callback that accepts two `const void*` arguments. [pthread\_create](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_create.html) expects a user-provided callback that accepts and returns `void*`. In all cases, it is the caller's responsibility to convert the pointer to the correct type before use.
### Null pointers
Pointers of every type have a special value known as *null pointer value* of that type. A pointer whose value is null does not point to an object or a function (dereferencing a null pointer is undefined behavior), and compares equal to all pointers of the same type whose value is also *null*.
To initialize a pointer to null or to assign the null value to an existing pointer, a null pointer constant (`[NULL](../types/null "c/types/NULL")`, or any other integer constant with the value zero) may be used. [static initialization](initialization "c/language/initialization") also initializes pointers to their null values.
Null pointers can indicate the absence of an object or can be used to indicate other types of error conditions. In general, a function that receives a pointer argument almost always needs to check if the value is null and handle that case differently (for example, `[free](../memory/free "c/memory/free")` does nothing when a null pointer is passed).
### Notes
Although any pointer to object [can be cast](cast "c/language/cast") to pointer to object of a different type, dereferencing a pointer to the type different from the declared type of the object is almost always undefined behavior. See [strict aliasing](object#Strict_aliasing "c/language/object") for details.
| | |
| --- | --- |
| It is possible to indicate to a function that accesses objects through pointers that those pointers do not alias. See [restrict](restrict "c/language/restrict") for details. | (since C99) |
lvalue expressions of array type, when used in most contexts, undergo an [implicit conversion](conversion "c/language/conversion") to the pointer to the first element of the array. See [array](array#Array_to_pointer_conversion "c/language/array") for details.
```
char *str = "abc"; // "abc" is a char[4] array, str is a pointer to 'a'
```
Pointers to char are often [used to represent strings](../string/byte "c/string/byte"). To represent a valid byte string, a pointer must be pointing at a char that is an element of an array of char, and there must be a char with the value zero at some index greater or equal to the index of the element referenced by the pointer.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.6.1 Pointer declarators (p: 93-94)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.6.1 Pointer declarators (p: 130)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.5.1 Pointer declarators (p: 115-116)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.5.4.1 Pointer declarators
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/pointer "cpp/language/pointer") for Pointer declaration |
c Statements Statements
==========
Statements are fragments of the C program that are executed in sequence. The body of any function is a compound statement, which, in turn is a sequence of statements and declarations:
```
int main(void)
{ // start of a compound statement
int n = 1; // declaration (not a statement)
n = n+1; // expression statement
printf("n = %d\n", n); // expression statement
return 0; // return statement
} // end of compound statement, end of function body
```
There are five types of statements:
1) [compound statements](#Compound_statements)
2) [expression statements](#Expression_statements)
3) [selection statements](#Selection_statements)
4) [iteration statements](#Iteration_statements)
5) [jump statements](#Jump_statements)
| | |
| --- | --- |
| An [attribute specifier sequence](attributes "c/language/attributes") (attr-spec-seq) can be applied to an unlabeled statement, in which case (except for an expression statement) the attributes are applied to the respective statement. | (since C23) |
### Labels
Any statement can be *labeled*, by providing a name followed by a colon before the statement itself.
| | | |
| --- | --- | --- |
| attr-spec-seq(optional)(since C23) identifier `:` | (1) | |
| attr-spec-seq(optional)(since C23) `case` constant-expression `:` | (2) | |
| attr-spec-seq(optional)(since C23) `default` `:` | (3) | |
1) Target for [goto](goto "c/language/goto").
2) Case label in a [switch](switch "c/language/switch") statement.
3) Default label in a [switch](switch "c/language/switch") statement. Any statement (but not a declaration) may be preceded by any number of *labels*, each of which declares identifier to be a label name, which must be unique within the enclosing function (in other words, label names have [function scope](scope "c/language/scope")).
Label declaration has no effect on its own, does not alter the flow of control, or modify the behavior of the statement that follows in any way.
| | |
| --- | --- |
| A label shall be followed by a statement. | (until C23) |
| A label can appear without its following statement. If a label appears alone in a block, it behaves as if it is followed by a [null statement](#Expression_statements).
The optional [attr-spec-seq](attributes "c/language/attributes") is applied to the label. | (since C23) |
### Compound statements
A compound statement, or *block*, is a brace-enclosed sequence of statements and declarations.
| | | |
| --- | --- | --- |
| `{` statement `|` declaration...(optional) `}` | | (until C23) |
| attr-spec-seq(optional) `{` unlabeled-statement `|` label `|` declaration...(optional) `}` | | (since C23) |
The compound statement allows a set of declarations and statements to be grouped into one unit that can be used anywhere a single statement is expected (for example, in an [if](if "c/language/if") statement or an iteration statement):
```
if (expr) // start of if-statement
{ // start of block
int n = 1; // declaration
printf("%d\n", n); // expression statement
} // end of block, end of if-statement
```
Each compound statement introduces its own [block scope](scope "c/language/scope").
The initializers of the variables with automatic [storage duration](storage_duration "c/language/storage duration") declared inside a block and the VLA declarators are executed when flow of control passes over these declarations in order, as if they were statements:
```
int main(void)
{ // start of block
{ // start of block
puts("hello"); // expression statement
int n = printf("abc\n"); // declaration, prints "abc", stores 4 in n
int a[n*printf("1\n")]; // declaration, prints "1", allocates 8*sizeof(int)
printf("%zu\n", sizeof(a)); // expression statement
} // end of block, scope of n and a ends
int n = 7; // n can be reused
}
```
### Expression statements
An expression followed by a semicolon is a statement.
| | | |
| --- | --- | --- |
| expression(optional) `;` | (1) | |
| attr-spec-seq expression `;` | (2) | (since C23) |
Most statements in a typical C program are expression statements, such as assignments or function calls.
An expression statement without an expression is called a *null statement*. It is often used to provide an empty body to a [for](for "c/language/for") or [while](while "c/language/while") loop. It can also be used to carry a label in the end of a compound statement or before a declaration:
```
puts("hello"); // expression statement
char *s;
while (*s++ != '\0')
; // null statement
```
| | |
| --- | --- |
| The optional [attr-spec-seq](attributes "c/language/attributes") is applied to the expression.
An attr-spec-seq followed by `;` does not form an expression statement. It forms an [attribute declaration](declarations "c/language/declarations") instead. | (since C23) |
### Selection statements
The selection statements choose between one of several statements depending on the value of an expression.
| | | |
| --- | --- | --- |
| attr-spec-seq(optional)(since C23) `if` `(` expression `)` statement | (1) | |
| attr-spec-seq(optional)(since C23) `if` `(` expression `)` statement `else` statement | (2) | |
| attr-spec-seq(optional)(since C23) `switch` `(` expression `)` statement | (3) | |
1) [if](if "c/language/if") statement
2) [if](if "c/language/if") statement with an else clause
3) [switch](switch "c/language/switch") statement ### Iteration statements
The iteration statements repeatedly execute a statement.
| | | |
| --- | --- | --- |
| attr-spec-seq(optional)(since C23) `while` `(` expression `)` statement | (1) | |
| attr-spec-seq(optional)(since C23) `do` statement `while` `(` expression `)` `;` | (2) | |
| attr-spec-seq(optional)(since C23) `for` `(` init-clause `;` expression(optional) `;` expression(optional) `)` statement | (3) | |
1) [while](while "c/language/while") loop
2) [do-while](do "c/language/do") loop
3) [for](for "c/language/for") loop ### Jump statements
The jump statements unconditionally transfer flow control.
| | | |
| --- | --- | --- |
| attr-spec-seq(optional)(since C23) `break` `;` | (1) | |
| attr-spec-seq(optional)(since C23) `continue` `;` | (2) | |
| attr-spec-seq(optional)(since C23) `return` expression(optional) `;` | (3) | |
| attr-spec-seq(optional)(since C23) `goto` identifier `;` | (4) | |
1) [break](break "c/language/break") statement
2) [continue](continue "c/language/continue") statement
3) [return](return "c/language/return") statement with an optional expression
4) [goto](goto "c/language/goto") statement ### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.8 Statements and blocks (p: 106-112)
* C11 standard (ISO/IEC 9899:2011):
+ 6.8 Statements and blocks (p: 146-154)
* C99 standard (ISO/IEC 9899:1999):
+ 6.8 Statements and blocks (p: 131-139)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.6 STATEMENTS
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/statements "cpp/language/statements") for Statements |
c Integer constant Integer constant
================
Allows values of integer type to be used in expressions directly.
### Syntax
An integer constant is a [non-lvalue](value_category "c/language/value category") expression of the form.
| | | |
| --- | --- | --- |
| decimal-constant integer-suffix(optional) | (1) | |
| octal-constant integer-suffix(optional) | (2) | |
| hex-constant integer-suffix(optional) | (3) | |
| binary-constant integer-suffix(optional) | (4) | (since C23) |
where.
* decimal-constant is a non-zero decimal digit (`1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`), followed by zero or more decimal digits (`0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`)
* octal-constant is the digit zero (`0`) followed by zero or more octal digits (`0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`)
* hex-constant is the character sequence `0x` or the character sequence `0X` followed by one or more hexadecimal digits (`0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `a`, `A`, `b`, `B`, `c`, `C`, `d`, `D`, `e`, `E`, `f`, `F`)
* binary-constant is the character sequence `0b` or the character sequence `0B` followed by one or more binary digits (`0`, `1`)
* integer-suffix, if provided, may contain one or both of the following (if both are provided, they may appear in any order):
+ unsigned-suffix (the character `u` or the character `U`)
+ long-suffix (the character `l` or the character `L`) or the long-long-suffix (the character sequence `ll` or the character sequence `LL`) (since C99)
| | |
| --- | --- |
| Optional single quotes (`'`) may be inserted between the digits as a separator. They are ignored by the compiler. | (since C23) |
### Explanation
1) Decimal integer constant (base 10, the first digit is the most significant).
2) Octal integer constant (base 8, the first digit is the most significant).
3) Hexadecimal integer constant (base 16, the first digit is the most significant, the letters 'a' through 'f' represent the decimal values 10 through 15).
4) Binary integer constant (base 2, the first digit is the most significant) The following variables are initialized to the same value:
```
int d = 42;
int o = 052;
int x = 0x2a;
int X = 0X2A;
int b = 0b101010; // C23
```
The following variables are also initialized to the same value:
```
unsigned long long l1 = 18446744073709550592ull; // C99
unsigned long long l2 = 18'446'744'073'709'550'592llu; // C23
unsigned long long l3 = 1844'6744'0737'0955'0592uLL; // C23
unsigned long long l4 = 184467'440737'0'95505'92LLU; // C23
```
### The type of the integer constant
The type of the integer constant is the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used.
| Types allowed for integer constants |
| --- |
| suffix | decimal bases | other bases |
| no suffix | `int` `long int` `unsigned long int` (until C99) `long long int` (since C99). | `int` `unsigned int` `long int` `unsigned long int` `long long int`(since C99) `unsigned long long int`(since C99). |
| `u` or `U` | `unsigned int` `unsigned long int` `unsigned long long int`(since C99). | `unsigned int` `unsigned long int` `unsigned long long int`(since C99). |
| `l` or `L` | `long int` `unsigned long int`(until C99) `long long int`(since C99). | `long int` `unsigned long int` `long long int`(since C99) `unsigned long long int`(since C99). |
| both `l`/`L` and `u`/`U` | `unsigned long int` `unsigned long long int`(since C99). | `unsigned long int` `unsigned long long int`(since C99). |
| `ll` or `LL` | `long long int`(since C99) | `long long int`(since C99) `unsigned long long int`(since C99). |
| both `ll`/`LL` and `u`/`U` | `unsigned long long int`(since C99) | `unsigned long long int`(since C99) |
If the value of the integer constant is too big to fit in any of the types allowed by suffix/base combination and the compiler supports extended integer types (such as `__int128`), the constant may be given the extended integer type; otherwise, the program is ill-formed.
### Notes
Letters in the integer constants are case-insensitive: `0xDeAdBaBeU` and `0XdeadBABEu` represent the same number (one exception is the long-long-suffix, which is either `ll` or `LL`, never `lL` or `Ll`) (since C99).
There are no negative integer constants. Expressions such as `-1` apply the [unary minus operator](operator_arithmetic "c/language/operator arithmetic") to the value represented by the constant.
| | |
| --- | --- |
| When used in a controlling expression of [`#if`](../preprocessor/conditional "c/preprocessor/conditional") or [`#elif`](../preprocessor/conditional "c/preprocessor/conditional"), all signed integer constants act as if they have type `[intmax\_t](../types/integer "c/types/integer")` and all unsigned integer constants act as if they have type `[uintmax\_t](../types/integer "c/types/integer")`. | (since C99) |
Integer constants may be used in [integer constant expressions](constant_expression "c/language/constant expression").
Due to [maximal munch](translation_phases#maximal_munch "c/language/translation phases"), hexadecimal integer constants ending in `e` and `E`, when followed by the operators `+` or `-`, must be separated from the operator with whitespace or parentheses in the source:
```
int x = 0xE+2; // error
int y = 0xa+2; // OK
int z = 0xE +2; // OK
int q = (0xE)+2; // OK
```
Otherwise, a single invalid preprocessing number token is formed, which causes further analysis to fail.
### Example
```
#include <stdio.h>
#include <inttypes.h>
int main(void)
{
printf("123 = %d\n", 123);
printf("0123 = %d\n", 0123);
printf("0x123 = %d\n", 0x123);
printf("12345678901234567890ull = %llu\n", 12345678901234567890ull);
// the type is a 64-bit type (unsigned long long or possibly unsigned long)
// even without a long suffix
printf("12345678901234567890u = %"PRIu64"\n", 12345678901234567890u );
// printf("%lld\n", -9223372036854775808); // ERROR
// the value 9223372036854775808 cannot fit in signed long long, which is the
// biggest type allowed for unsuffixed decimal integer constant
printf("%llu\n", -9223372036854775808ull );
// unary minus applied to unsigned value subtracts it from 2^64,
// this gives unsigned 9223372036854775808
printf("%lld\n", -9223372036854775807ull - 1);
// correct way to form signed value -9223372036854775808
}
```
Output:
```
123 = 123
0123 = 83
0x123 = 291
12345678901234567890ull = 12345678901234567890
12345678901234567890u = 12345678901234567890
9223372036854775808
-9223372036854775808
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.4.4.1 Integer constants (p: 45-46)
* C11 standard (ISO/IEC 9899:2011):
+ 6.4.4.1 Integer constants (p: 62-64)
* C99 standard (ISO/IEC 9899:1999):
+ 6.4.4.1 Integer constants (p: 54-56)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.3.2 Integer constants
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/integer_literal "cpp/language/integer literal") for Integer literal |
| programming_docs |
c Array initialization Array initialization
====================
When [initializing](initialization "c/language/initialization") an object of [array](array "c/language/array") type, the initializer must be either a [string literal](string_literal "c/language/string literal") (optionally enclosed in braces) or be a brace-enclosed list of initialized for array members:
| | | |
| --- | --- | --- |
| `=` string-literal | (1) | |
| `=` `{` expression `,` `...` `}` | (2) | (until C99) |
| `=` `{` designator(optional) expression `,` `...` `}` | (2) | (since C99) |
| `=` `{` `}` | (3) | (since C23) |
1) string literal initializer for character and wide character arrays
2) comma-separated list of constant (until C99) expressions that are initializers for array elements, optionally using array designators of the form `[` constant-expression `]` `=` (since C99)
3) empty initializer empty-initializes every element of the array Arrays of known size and arrays of unknown size may be initialized, but not VLAs. (since C99)(until C23) A VLA can only be empty-initialized. (since C23).
All array elements that are not initialized explicitly are [empty-initialized](initialization#Empty_initialization "c/language/initialization").
### Initialization from strings
[String literal](string_literal "c/language/string literal") (optionally enclosed in braces) may be used as the initializer for an array of matching type:
* ordinary string literals and UTF-8 string literals (since C11) can initialize arrays of any character type (`char`, `signed char`, `unsigned char`)
* L-prefixed wide string literals can be used to initialize arrays of any type compatible with (ignoring cv-qualifications) `wchar_t`
| | |
| --- | --- |
| * u-prefixed wide string literals can be used to initialize arrays of any type compatible with (ignoring cv-qualifications) `char16_t`
* U-prefixed wide string literals can be used to initialize arrays of any type compatible with (ignoring cv-qualifications) `char32_t`
| (since C11) |
Successive bytes of the string literal or wide characters of the wide string literal, including the terminating null byte/character, initialize the elements of the array:
```
char str[] = "abc"; // str has type char[4] and holds 'a', 'b', 'c', '\0'
wchar_t wstr[4] = L"猫"; // str has type wchar_t[4] and holds L'猫', '\0', '\0', '\0'
```
If the size of the array is known, it may be one less than the size of the string literal, in which case the terminating null character is ignored:
```
char str[3] = "abc"; // str has type char[3] and holds 'a', 'b', 'c'
```
Note that the contents of such array are modifiable, unlike when accessing a string literal directly with `char* str = "abc";`.
### Initialization from brace-enclosed lists
When an array is initialized with a brace-enclosed list of initializers, the first initializer in the list initializes the array element at index zero (unless a designator is specified) (since C99), and each subsequent initializer without a designator (since C99)initializes the array element at index one greater than the one initialized by the previous initializer.
```
int x[] = {1,2,3}; // x has type int[3] and holds 1,2,3
int y[5] = {1,2,3}; // y has type int[5] and holds 1,2,3,0,0
int z[4] = {1}; // z has type int[4] and holds 1,0,0,0
int w[3] = {0}; // w has type int[3] and holds all zeroes
```
It's an error to provide more initializers than elements when initializing an array of known size (except when initializing character arrays from string literals).
| | |
| --- | --- |
| A designator causes the following initializer to initialize of the array element described by the designator. Initialization then continues forward in order, beginning with the next element after the one described by the designator.
```
int n[5] = {[4]=5,[0]=1,2,3,4}; // holds 1,2,3,4,5
int a[MAX] = { // starts initializing a[0] = 1, a[1] = 3, ...
1, 3, 5, 7, 9, [MAX-5] = 8, 6, 4, 2, 0
};
// for MAX=6, array holds 1,8,6,4,2,0
// for MAX=13, array holds 1,3,5,7,9,0,0,0,8,6,4,2,0 ("sparse array")
```
| (since C99) |
When initializing an array of unknown size, the largest subscript for which an initializer is specified determines the size of the array being declared.
### Nested arrays
If the elements of an array are arrays, structs, or unions, the corresponding initializers in the brace-enclosed list of initializers are any initializers that are valid for those members, except that their braces may be omitted as follows:
If the nested initializer begins with an opening brace, the entire nested initializer up to its closing brace initializes the corresponding array element:
```
int y[4][3] = { // array of 4 arrays of 3 ints each (4x3 matrix)
{ 1 }, // row 0 initialized to {1, 0, 0}
{ 0, 1 }, // row 1 initialized to {0, 1, 0}
{ [2]=1 }, // row 2 initialized to {0, 0, 1}
}; // row 3 initialized to {0, 0, 0}
```
If the nested initializer does not begin with an opening brace, only enough initializers from the list are taken to account for the elements or members of the sub-array, struct or union; any remaining initializers are left to initialize the next array element:
```
int y[4][3] = { // array of 4 arrays of 3 ints each (4x3 matrix)
1, 3, 5, 2, 4, 6, 3, 5, 7 // row 0 initialized to {1, 3, 5}
}; // row 1 initialized to {2, 4, 6}
// row 2 initialized to {3, 5, 7}
// row 3 initialized to {0, 0, 0}
struct { int a[3], b; } w[] = { { 1 }, 2 }; // array of structs
// { 1 } is taken to be a fully-braced initializer for element #0 of the array
// that element is initialized to { {1, 0, 0}, 0}
// 2 is taken to be the first initialized for element #1 of the array
// that element is initialized { {2, 0, 0}, 0}
```
| | |
| --- | --- |
| Array designators may be nested; the bracketed constant expression for nested arrays follows the bracketed constant expression for the outer array:
```
int y[4][3] = {[0][0]=1, [1][1]=1, [2][0]=1}; // row 0 initialized to {1, 0, 0}
// row 1 initialized to {0, 1, 0}
// row 2 initialized to {1, 0, 0}
// row 3 initialized to {0, 0, 0}
```
| (since C99) |
### Notes
The [order of evaluation](eval_order "c/language/eval order") of subexpressions in an array initializer is indeterminately sequenced in C (but not in C++ since C++11):
```
int n = 1;
int a[2] = {n++, n++}; // unspecified, but well-defined behavior,
// n is incremented twice (in arbitrary order)
// a initialized to {1, 2} and to {2, 1} are both valid
puts((char[4]){'0'+n} + n++); // undefined behavior:
// increment and read from n are unsequenced
```
| | |
| --- | --- |
| In C, the braced list of an initializer cannot be empty. C++ allows empty list: | (until C23) |
| An empty initializer can be used to initialize an array: | (since C23) |
```
int a[3] = {0}; // valid C and C++ way to zero-out a block-scope array
int a[3] = {}; // valid C++ way to zero-out a block-scope array; valid in C since C23
```
As with all other [initialization](initialization "c/language/initialization"), every expression in the initializer list must be a [constant expression](constant_expression "c/language/constant expression") when initializing arrays of static or thread-local [storage duration](storage_duration "c/language/storage duration"):
```
static char* p[2] = {malloc(1), malloc(2)}; // error
```
### Example
```
int main(void)
{
// The following four array declarations are the same
short q1[4][3][2] = {
{ 1 },
{ 2, 3 },
{ 4, 5, 6 }
};
short q2[4][3][2] = {1, 0, 0, 0, 0, 0, 2, 3, 0, 0, 0, 0, 4, 5, 6};
short q3[4][3][2] = {
{
{ 1 },
},
{
{ 2, 3 },
},
{
{ 4, 5 },
{ 6 },
}
};
short q4[4][3][2] = {1, [1]=2, 3, [2]=4, 5, 6};
// Character names can be associated with enumeration constants
// using arrays with designators:
enum { RED, GREEN, BLUE };
const char *nm[] = {
[RED] = "red",
[GREEN] = "green",
[BLUE] = "blue",
};
}
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.9/12-39 Initialization (p: 101-105)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.9/12-38 Initialization (p: 140-144)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.8/12-38 Initialization (p: 126-130)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 6.5.7 Initialization
c Order of evaluation Order of evaluation
===================
Order of evaluation of the operands of any C operator, including the order of evaluation of function arguments in a function-call expression, and the order of evaluation of the subexpressions within any expression is unspecified (except where noted below). The compiler will evaluate them in any order, and may choose another order when the same expression is evaluated again.
There is no concept of left-to-right or right-to-left evaluation in C, which is not to be confused with left-to-right and right-to-left associativity of operators: the expression `f1() + f2() + f3()` is parsed as `(f1() + f2()) + f3()` due to left-to-right associativity of operator+, but the function call to `f3` may be evaluated first, last, or between `f1()` or `f2()` at run time.
### Definitions
#### Evaluations
There are two kinds of evaluations performed by the compiler for each expression or subexpression (both of which are optional):
* *value computation*: calculation of the value that is returned by the expression. This may involve determination of the identity of the object ([lvalue evaluation](value_category "c/language/value category")) or reading the value previously assigned to an object (rvalue evaluation)
* *side effect*: access (read or write) to an object designated by a [volatile](volatile "c/language/volatile") lvalue, modification (writing) to an object, atomic synchronization (since C11), modifying a file, modifying the floating-point environment (if supported), or calling a function that does any of those operations.
If no side effects are produced by an expression and the compiler can determine that the value is not used, the expression [may not be evaluated](https://en.cppreference.com/mwiki/index.php?title=c/language/as-if&action=edit&redlink=1 "c/language/as-if (page does not exist)").
#### Ordering
"sequenced-before" is an asymmetric, transitive, pair-wise relationship between evaluations within the same thread (it may extend across threads if atomic types and memory barriers are involved).
* If a [*sequence point*](https://en.wikipedia.org/wiki/Sequence_point "enwiki:Sequence point") is present between the subexpressions E1 and E2, then both value computation and side effects of E1 are *sequenced-before* every value computation and side effect of E2
| | |
| --- | --- |
| * If evaluation A is sequenced before evaluation B, then evaluation of A will be complete before evaluation of B begins.
* If A is not sequenced before B and B is sequenced before A, then evaluation of B will be complete before evaluation of A begins.
* If A is not sequenced before B and B is not sequenced before A, then two possibilities exist:
+ evaluations of A and B are unsequenced: they may be performed in any order and may overlap (within a single thread of execution, the compiler may interleave the CPU instructions that comprise A and B)
+ evaluations of A and B are indeterminably-sequenced: they may be performed in any order but may not overlap: either A will be complete before B, or B will be complete before A. The order may be the opposite the next time the same expression is evaluated.
| (since C11) |
### Rules
1) There is a sequence point after the evaluation of all function arguments and of the function designator, and before the actual function call.
2) There is a sequence point after evaluation of the first (left) operand and before evaluation of the second (right) operand of the following binary operators: `&&` (logical AND), `||` (logical OR), and `,` (comma).
3) There is a sequence point after evaluation of the first (left) operand and before evaluation of the second or third operand (whichever is evaluated) of the conditional operator `?:`
4) There is a sequence point after the evaluation of a full expression (an expression that is not a subexpression: typically something that ends with a semicolon or a [controlling statement](statements "c/language/statements") of `if`/`switch`/`while`/`do`) and before the next full expression.
| | |
| --- | --- |
| 5) There is a sequence point at the end of a full declarator. 6) There is a sequence point immediately before the return of a library function. 7) There is a sequence point after the action associated with each conversion specifier in formatted I/O (in particular, it is well-formed for `[scanf](../io/fscanf "c/io/fscanf")` to write different fields into the same variable and for `[printf](../io/fprintf "c/io/fprintf")` to read and modify or modify the same variable more than once using `%n`) 8) There are sequence points before and immediately after each call to a comparison function made by the library functions `[qsort](../algorithm/qsort "c/algorithm/qsort")` and `[bsearch](../algorithm/bsearch "c/algorithm/bsearch")`, as well as between any call to the comparison function and the movement of the associated objects made by `[qsort](../algorithm/qsort "c/algorithm/qsort")` | (since C99) |
| 9) The value computations (but not the side-effects) of the operands to any operator are sequenced before the value computation of the result of the operator (but not its side-effects). 10) The side effect (modification of the left argument) of the direct assignment operator and of all compound assignment operators is sequenced after the value computation (but not the side effects) of both left and right arguments. 11) The value computation of the postincrement and postdecrement operators is sequenced before its side-effect. 12) A function call that is not sequenced before or sequenced after another function call is indeterminately sequenced (CPU instructions that constitute different function calls cannot be interleaved, even if the functions are inlined) 13) In [initialization](initialization "c/language/initialization") list expressions, all evaluations are indeterminately sequenced 14) With respect to an indeterminately-sequenced function call, the operation of compound assignment operators, and both prefix and postfix forms of increment and decrement operators are single evaluations. | (since C11) |
### Undefined behavior
1) If a side effect on a scalar object is unsequenced relative to another side effect on the same scalar object, the [behavior is undefined](behavior#UB_and_optimization "c/language/behavior").
```
i = ++i + i++; // undefined behavior
i = i++ + 1; // undefined behavior
f(++i, ++i); // undefined behavior
f(i = -1, i = -1); // undefined behavior
```
2) If a side effect on a scalar object is unsequenced relative to a value computation using the value of the same scalar object, the behavior is undefined.
```
f(i, i++); // undefined behavior
a[i] = i++; // undefined bevahior
```
3) The above rules apply as long as at least one allowable ordering of subexpressions permits such an unsequenced side-effect. ### See also
[Operator precedence](operator_precedence "c/language/operator precedence") which defines how expressions are built from their source code representation.
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/eval_order "cpp/language/eval order") for Order of evaluation |
c _Noreturn function specifier \_Noreturn function specifier
=============================
Specifies that the function does not return to its point of invocation.
### Syntax
| | | |
| --- | --- | --- |
| `_Noreturn` function\_declaration | | (since C11)(deprecated in C23) |
### Explanation
The `_Noreturn` keyword appears in a function declaration and specifies that the function does not return by executing the return statement or by reaching the end of the function body (it may return by executing `[longjmp](../program/longjmp "c/program/longjmp")`). If the function declared `_Noreturn` returns, the behavior is undefined. A compiler diagnostic is recommended if this can be detected.
The `_Noreturn` specifier may appear more than once in the same function declaration, the behavior is the same as if it appeared once.
This specifier is typically used through the convenience macro [`noreturn`](../types "c/types"), which is provided in the header `stdnoreturn.h`.
| | |
| --- | --- |
| `_Noreturn` function specifier is deprecated. `[[[noreturn](attributes/noreturn "c/language/attributes/noreturn")]]` attribute should be used instead.
The macro `noreturn` is also deprecated. | (since C23) |
### Keywords
[`_Noreturn`](../keyword/_noreturn "c/keyword/ Noreturn").
### Standard library
The following functions are `noreturn` in the standard library:
* `[abort()](../program/abort "c/program/abort")`
* `[exit()](../program/exit "c/program/exit")`
* `[\_Exit()](../program/_exit "c/program/ Exit")`
* `[quick\_exit()](../program/quick_exit "c/program/quick exit")`
* `[thrd\_exit()](../thread/thrd_exit "c/thread/thrd exit")`
* `[longjmp()](../program/longjmp "c/program/longjmp")`
### Example
```
#include <stdlib.h>
#include <stdio.h>
#include <stdnoreturn.h>
// causes undefined behavior if i <= 0
// exits if i > 0
noreturn void exit_now(int i) // or _Noreturn void exit_now(int i)
{
if (i > 0) exit(i);
}
int main(void)
{
puts("Preparing to exit...");
exit_now(2);
puts("This code is never executed.");
}
```
Output:
```
Preparing to exit...
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.4 Function specifiers (p: 90-91)
+ 7.23 \_Noreturn <stdnoreturn.h> (p: 263)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.4 Function specifiers (p: 125-127)
+ 7.23 \_Noreturn <stdnoreturn.h> (p: 361)
### See also
| |
| --- |
| [C documentation](attributes/noreturn "c/language/attributes/noreturn") for `[[noreturn]]` |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/attributes/noreturn "cpp/language/attributes/noreturn") for `[[noreturn]]` |
c Functions Functions
=========
A function is a C language construct that associates a [compound statement](statements#Compound_statements "c/language/statements") (the function body) with an [identifier](identifier "c/language/identifier") (the function name). Every C program begins execution from the [main function](main_function "c/language/main function"), which either terminates, or invokes other, user-defined or library functions.
```
// function definition.
// defines a function with the name "sum" and with the body "{ return x+y; }"
int sum(int x, int y)
{
return x + y;
}
```
Functions may accept zero or more *parameters*, which are initialized from the *arguments* of a [function call operator](operator_other#Function_call "c/language/operator other"), and may return a value to its caller by means of the [return statement](return "c/language/return").
```
int n = sum(1, 2); // parameters x and y are initialized with the arguments 1 and 2
```
The body of a function is provided in a [function definition](function_definition "c/language/function definition"). Each function that is [actually called](expressions#Unevaluated_expressions "c/language/expressions") must be [defined only once](extern#One_definition_rule "c/language/extern") in a program, unless the function is [inline](inline "c/language/inline") (since C99).
There are no nested functions (except where allowed through non-standard compiler extensions): each function definition must appear at file scope, and functions have no access to the local variables from the caller:
```
int main(void) // the main function definition
{
int sum(int, int); // function declaration (may appear at any scope)
int x = 1; // local variable in main
sum(1, 2); // function call
// int sum(int a, int b) // error: no nested functions
// {
// return a + b;
// }
}
int sum(int a, int b) // function definition
{
// return x + a + b; // error: main's x is not accessible within sum
return a + b;
}
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.6.3 Function declarators (including prototypes) (p: 96-98)
+ 6.9.1 Function definitions (p: 113-115)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.6.3 Function declarators (including prototypes) (p: 133-136)
+ 6.9.1 Function definitions (p: 156-158)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.5.3 Function declarators (including prototypes) (p: 118-121)
+ 6.9.1 Function definitions (p: 141-143)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.5.4.3 Function declarators (including prototypes)
+ 3.7.1 Function definitions
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/function "cpp/language/function") for Declaring functions |
| programming_docs |
c Conformance Conformance
===========
*Conformance* has a three-fold definition:
* *strictly conforming program* - uses only well-defined language constructs, that is constructs with a single behavior. It excludes unspecified, undefined, or implementation-defined behavior, and does not exceed any minimum implementation limit.
* *conforming program* - acceptable to a conforming implementation.
* *conforming implementation* -
+ A conforming hosted implementation shall accept any strictly conforming program.
+ A conforming freestanding implementation shall accept any strictly conforming program in which the use of the features specified in the library clause (clause 7) is confined to the contents of the freestanding standard library headers (see below).
+ A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any strictly conforming program.
### Explanation
The standard does not define any minimum implementation limit on translation units. A hosted environment has an operating system; a freestanding environment does not. A program running in a hosted environment may use all features described in the library clause (clause 7); a program running in a freestanding environment may use a subset of library features required by clause 4.
#### Freestanding standard library headers
All standard library features in every fully freestanding header are required to be provided by a freestanding implementation.
| | |
| --- | --- |
| Some standard library headers are conditionally freestanding.* If the implementation predefines the macro `__STDC_IEC_60559_BFP__` or `__STDC_IEC_60559_BFP__`, then
+ `<math.h>` and `<fenv.h>` are fully freestanding headers, and
+ `<stdlib.h>` is a partially freestanding header.
In a partially freestanding header, only a part of standard library features are required to be provided by a freestanding implementation.* [`strdup`](../string/byte/strdup "c/string/byte/strdup"), [`strndup`](../string/byte/strndup "c/string/byte/strndup"), `[strcoll](../string/byte/strcoll "c/string/byte/strcoll")`, `[strxfrm](../string/byte/strxfrm "c/string/byte/strxfrm")`, and `[strerror](../string/byte/strerror "c/string/byte/strerror")` are not required to be provided by a freestanding implementation.
* When `__STDC_IEC_60559_BFP__` or `__STDC_IEC_60559_BFP__` are predefined, in `<stdlib.h>`, only numeric conversion functions (`ato*X*`, `strto*X*`, and `strfrom*X*`) are required to be provided by a freestanding implementation.
| (since C23) |
| |
| --- |
| Fully freestanding standard library headers |
| `<float.h>` | [Limits of floating-point types](../types/limits#Limits_of_floating_point_types "c/types/limits") |
| `<iso646.h>` (C95) | [Alternative operator spellings](operator_alternative "c/language/operator alternative") |
| `<limits.h>` | [Ranges of integer types](../types/limits "c/types/limits") |
| `<stdalign.h>` (C11) | [`alignas` and `alignof`](../types "c/types") convenience macros |
| `<stdarg.h>` | [Variable arguments](../variadic "c/variadic") |
| `<stdbool.h>` (C99) | [Macros for boolean type](../types "c/types") |
| `<stddef.h>` | [Common macro definitions](../types "c/types") |
| `<stdint.h>` (C99) | [Fixed-width integer types](../types/integer "c/types/integer") |
| `<stdnoreturn.h>` (C11) | [`noreturn`](../types "c/types") convenience macro |
| Partially freestanding standard library headers |
| `<string.h>` (C23) | [String handling](../string/byte "c/string/byte") |
| Conditionally fully freestanding standard library headers |
| `<fenv.h>` (C23) | [Floating-point environment](../numeric/fenv "c/numeric/fenv") |
| `<math.h>` (C23) | [Common mathematics functions](../numeric/math "c/numeric/math") |
| Conditionally partially freestanding standard library headers |
| `<stdlib.h>` (C23) | General utilities: [memory management](../memory "c/memory"), [program utilities](../program "c/program"), [string conversions](../string "c/string"), [random numbers](../numeric/random "c/numeric/random"), [algorithms](../algorithm "c/algorithm") |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 4 Conformance (p: 4)
* C11 standard (ISO/IEC 9899:2011):
+ 4 Conformance (p: 8-9)
* C99 standard (ISO/IEC 9899:1999):
+ 4 Conformance (p: 7-8)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 1.7 Compliance
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/freestanding "cpp/freestanding") for Freestanding and hosted implementation |
c Type Type
====
(See also [arithmetic types](arithmetic_types "c/language/arithmetic types") for the details on most built-in types and [the list of type-related utilities](../types "c/types") that are provided by the C library).
[Objects](object "c/language/object"), [functions](functions "c/language/functions"), and [expressions](expressions "c/language/expressions") have a property called *type*, which determines the interpretation of the binary value stored in an object or evaluated by the expression.
### Type classification
The C type system consists of the following types:
* the type `void`
* basic types
* the type `char`
* signed integer types
+ standard: `signed char`, `short`, `int`, `long`, `long long` (since C99)
| | |
| --- | --- |
| * extended: implementation defined, e.g. `__int128`
| (since C99) |
* unsigned integer types
+ standard: `_Bool`, (since C99) `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long` (since C99)
| | |
| --- | --- |
| * extended: implementation-defined, e.g. `__uint128`
| (since C99) |
* floating-point types
+ real floating-point types: `float`, `double`, `long double`
| | |
| --- | --- |
| * decimal real floating-point types: `_Decimal32`, `_Decimal64`, `_Decimal128`
| (since C23) |
| * complex types: `float _Complex`, `double _Complex`, `long double _Complex`
* imaginary types: `float _Imaginary`, `double _Imaginary`, `long double _Imaginary`
| (since C99) |
* [enumerated types](enum "c/language/enum")
* derived types
+ [array types](array "c/language/array")
+ [structure types](struct "c/language/struct")
+ [union types](union "c/language/union")
+ [function types](functions "c/language/functions")
+ [pointer types](pointer "c/language/pointer")
| | |
| --- | --- |
| * [atomic types](atomic "c/language/atomic")
| (since C11) |
For every type listed above several qualified versions of its type may exist, corresponding to the combinations of one, two, or all three of the [`const`](const "c/language/const"), [`volatile`](volatile "c/language/volatile"), and [`restrict`](restrict "c/language/restrict") qualifiers (where allowed by the qualifier's semantics).
#### Type groups
* *object types*: all types that aren't function types
* *character types*: `char`, `signed char`, `unsigned char`
* *integer types*: `char`, signed integer types, unsigned integer types, enumerated types
* *real types*: integer types and real floating types
* [arithmetic types](arithmetic_types "c/language/arithmetic types"): integer types and floating types
* *scalar types*: arithmetic types, pointer types, and `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` (since C23)
* *aggregate types*: array types and structure types
* *derived declarator types*: array types, function types, and pointer types
### Compatible types
In a C program, the declarations referring to the same object or function in *different translation units* do not have to use the same type. They only have to use sufficiently similar types, formally known as *compatible types*. Same applies to function calls and lvalue accesses; argument types must be *compatible* with parameter types and lvalue expression type must be *compatible* with the object type that is accessed.
The types `T` and `U` are compatible, if.
* they are the same type (same name or aliases introduced by a [typedef](typedef "c/language/typedef"))
* they are identically cvr-qualified versions of compatible unqualified types
* they are pointer types and are pointing to compatible types
* they are array types, and
+ their element types are compatible, and
+ if both have constant size, that size is the same. Note: arrays of unknown bound are compatible with any array of compatible element type. VLA is compatible with any array of compatible element type. (since C99)
* they are both structure/union/enumeration types, and
* (C99)if one is declared with a tag, the other must also be declared with the same tag.
* if both are completed types, their members must correspond exactly in number, be declared with compatible types, and have matching names.
* additionally, if they are enumerations, corresponding members must also have the same values.
* additionally, if they are structures or unions,
+ Corresponding members must be declared in the same order (structures only)
+ Corresponding bit fields must have the same widths.
* one is an enumerated type and the other is that enumeration's underlying type
* they are function types, and
+ their return types are compatible
+ they both use parameter lists, the number of parameters (including the use of the ellipsis) is the same, and the corresponding parameter, after applying array-to-pointer and function-to-pointer type adjustments and after stripping top-level qualifiers, have compatible types
+ one is an old-style (parameter-less) definition, the other has a parameter list, the parameter list does not use an ellipsis and each parameter is compatible (after function parameter type adjustment) with the corresponding old-style parameter after default argument promotions
+ one is an old-style (parameter-less) declaration, the other has a parameter list, the parameter list does not use an ellipsis, and all parameters (after function parameter type adjustment) are unaffected by default argument promotions
The type `char` is not compatible with `signed char` and not compatible with `unsigned char`.
If two declarations refer to the same object or function and do not use compatible types, the behavior of the program is undefined.
```
// Translation Unit 1
struct S {int a;};
extern struct S *x; // compatible with TU2's x, but not with TU3's x
// Translation Unit 2
struct S;
extern struct S *x; // compatible with both x's
// Translation Unit 3
struct S {float a;};
extern struct S *x; // compatible with TU2's x, but not with TU1's x
// the behavior is undefined
```
```
// Translation Unit 1
#include <stdio.h>
struct s {int i;}; // compatible with TU3's s, but not TU2's
extern struct s x = {0}; // compatible with TU3's x
extern void f(void); // compatible with TU2's f
int main()
{
f();
return x.i;
}
// Translation Unit 2
struct s {float f;}; // compatible with TU4's s, but not TU1's s
extern struct s y = {3.14}; // compatible with TU4's y
void f() // compatible with TU1's f
{
return;
}
// Translation Unit 3
struct s {int i;}; // compatible with TU1's s, but not TU2's s
extern struct s x; // compatible with TU1's x
// Translation Unit 4
struct s {float f;}; // compatible with TU2's s, but not TU1's s
extern struct s y; // compatible with TU2's y
// the behavior is well-defined: only multiple declarations
// of objects and functions must have compatible types, not the types themselves
```
Note: C++ has no concept of compatible types. A C program that declares two types that are compatible but not identical in different translation units is not a valid C++ program.
### Composite types
A composite type can be constructed from two types that are compatible; it is a type that is compatible with both of the two types and satisfies the following conditions:
* If both types are array types, the following rules are applied:
+ If one type is an array of known constant size, the composite type is an array of that size.
| | |
| --- | --- |
| * Otherwise, if one type is a VLA whose size is specified by an expression that is not evaluated, the behavior is undefined.
* Otherwise, if one type is a VLA whose size is specified, the composite type is a VLA of that size.
* Otherwise, if one type is a VLA of unspecified size, the composite type is a VLA of unspecified size.
| (since C99) |
* Otherwise, both types are arrays of unknown size and the composite type is an array of unknown size.
* If only one type is a function type with a parameter type list (a function prototype), the composite type is a function prototype with the parameter type list.
* If both types are function types with parameter type lists, the type of each parameter in the composite parameter type list is the composite type of the corresponding parameters.
The element type of the composite type is the composite type of the two element types. These rules apply recursively to the types from which the two types are derived.
```
// Given the following two file scope declarations:
int f(int (*)(), double (*)[3]);
int f(int (*)(char *), double (*)[]);
// The resulting composite type for the function is:
int f(int (*)(char *), double (*)[3]);
```
For an identifier with internal or external [linkage](storage_duration "c/language/storage duration") declared in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the type of the identifier at the later declaration becomes the composite type.
### Incomplete types
An incomplete type is an object type that lacks sufficient information to determine the size of the objects of that type. An incomplete type may be completed at some point in the translation unit.
The following types are incomplete:
* the type `void`. This type cannot be completed.
* array type of unknown size. It can be completed by a later declaration that specifies the size.
```
extern char a[]; // the type of a is incomplete (this typically appears in a header)
char a[10]; // the type of a is now complete (this typically appears in a source file)
```
* structure or union type of unknown content. It can be completed by a declaration of the same structure or union that defines its content later in the same scope.
```
struct node {
struct node *next; // struct node is incomplete at this point
}; // struct node is complete at this point
```
### Type names
A type may have to be named in context other than the [declaration](declarations "c/language/declarations"). In these situations, *type name* is used, which is, grammatically, exactly the same as a list of *type-specifiers* and *type-qualifiers*, followed by the *declarator* (see [declarations](declarations "c/language/declarations")) as would be used to declare a single object or function of this type, except that the identifier is omitted:
```
int n; // declaration of an int
sizeof(int); // use of type name
int *a[3]; // declaration of an array of 3 pointers to int
sizeof(int *[3]); // use of type name
int (*p)[3]; // declaration of a pointer to array of 3 int
sizeof(int (*)[3]); // use of type name
int (*a)[*] // declaration of pointer to VLA (in a function parameter)
sizeof(int (*)[*]) // use of type name (in a function parameter)
int *f(void); // declaration of function
sizeof(int *(void)); // use of type name
int (*p)(void); // declaration of pointer to function
sizeof(int (*)(void)); // use of type name
int (*const a[])(unsigned int, ...) = {0}; // array of pointers to functions
sizeof(int (*const [])(unsigned int, ...)); // use of type name
```
Except the redundant parentheses around the identifier are meaningful in a type-name and represent "function with no parameter specification":
```
int (n); // declares n of type int
sizeof(int ()); // uses type "function returning int"
```
Type names are used in the following situations:
* [cast](cast "c/language/cast")
* [sizeof](sizeof "c/language/sizeof")
| | |
| --- | --- |
| * [compound literal](compound_literal "c/language/compound literal")
| (since C99) |
| * [generic selection](generic "c/language/generic")
* [\_Alignof](_alignof "c/language/ Alignof")
* [\_Alignas](_alignas "c/language/ Alignas")
* [\_Atomic](atomic "c/language/atomic") (when used as a type specifier)
| (since C11) |
A type name may introduce a new type:
```
void* p = (void*)(struct X {int i;} *)0;
// type name "struct X {int i;}*" used in the cast expression
// introduces the new type "struct X"
struct X x = {1}; // struct X is now in scope
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.2.5 Types (p: 31-33)
+ 6.2.6 Representations of types (p: 31-35)
+ 6.2.7 Compatible type and composite type (p: 35-36)
* C11 standard (ISO/IEC 9899:2011):
+ 6.2.5 Types (p: 39-43)
+ 6.2.6 Representations of types (p: 44-46)
+ 6.2.7 Compatible type and composite type (p: 47-48)
* C99 standard (ISO/IEC 9899:1999):
+ 6.2.5 Types (p: 33-37)
+ 6.2.6 Representations of types (p: 37-40)
+ 6.2.7 Compatible type and composite type (p: 40-41)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.2.5 Types
+ 3.1.2.6 Compatible type and composite type
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/type "cpp/language/type") for Type |
c volatile type qualifier volatile type qualifier
=======================
Each individual type in the C [type system](type "c/language/type") has several *qualified* versions of that type, corresponding to one, two, or all three of the [const](const "c/language/const"), *volatile*, and, for pointers to object types, [restrict](restrict "c/language/restrict") qualifiers. This page describes the effects of the *volatile* qualifier.
Every access (both read and write) made through an lvalue expression of volatile-qualified type is considered an observable side effect for the purpose of optimization and is evaluated strictly according to the rules of the abstract machine (that is, all writes are completed at some time before the next sequence point). This means that within a single thread of execution, a volatile access cannot be optimized out or reordered relative to another visible side effect that is separated by a [sequence point](eval_order "c/language/eval order") from the volatile access.
A cast of a non-volatile value to a volatile type has no effect. To access a non-volatile object using volatile semantics, its address must be cast to a pointer-to-volatile and then the access must be made through that pointer.
Any attempt to read or write to an object whose type is volatile-qualified through a non-volatile lvalue results in undefined behavior:
```
volatile int n = 1; // object of volatile-qualified type
int* p = (int*)&n;
int val = *p; // undefined behavior
```
A member of a volatile-qualified structure or union type acquires the qualification of the type it belongs to (both when accessed using the `.` operator or the `->` operator):
```
struct s { int i; const int ci; } s;
// the type of s.i is int, the type of s.ci is const int
volatile struct s vs;
// the types of vs.i and vs.ci are volatile int and const volatile int
```
| | |
| --- | --- |
| If an array type is declared with the volatile type qualifier (through the use of [typedef](typedef "c/language/typedef")), the array type is not volatile-qualified, but its element type is. | (until C23) |
| An array type and its element type are always considered to be identically volatile-qualified. | (since C23) |
If a function type is declared with the volatile type qualified (through the use of [typedef](typedef "c/language/typedef")), the behavior is undefined.
```
typedef int A[2][3];
volatile A a = {{4, 5, 6}, {7, 8, 9}}; // array of array of volatile int
int* pi = a[0]; // Error: a[0] has type volatile int*
void *unqual_ptr = a; // OK until C23; error since C23
// Notes: clang applies the rule in C++/C23 even in C89-C17 modes
```
| | |
| --- | --- |
| In a function declaration, the keyword `volatile` may appear inside the square brackets that are used to declare an array type of a function parameter. It qualifies the pointer type to which the array type is transformed.
The following two declarations declare the same function:
```
void f(double x[volatile], const double y[volatile]);
void f(double * volatile x, const double * volatile y);
```
| (since C99) |
A pointer to a non-volatile type can be implicitly converted to a pointer to the volatile-qualified version of the same or [compatible type](compatible_type "c/language/compatible type"). The reverse conversion can be performed with a cast expression.
```
int* p = 0;
volatile int* vp = p; // OK: adds qualifiers (int to volatile int)
p = vp; // Error: discards qualifiers (volatile int to int)
p = (int*)vp; // OK: cast
```
Note that pointer to pointer to `T` is not convertible to pointer to pointer to `volatile T`; for two types to be compatible, their qualifications must be identical:
```
char *p = 0;
volatile char **vpp = &p; // Error: char* and volatile char* are not compatible types
char * volatile *pvp = &p; // OK, adds qualifiers (char* to char*volatile)
```
### Uses of volatile
1) [static](static_storage_duration "c/language/static storage duration") `volatile` objects model memory-mapped I/O ports, and `static` `const` `volatile` objects model memory-mapped input ports, such as a real-time clock:
```
volatile short *ttyport = (volatile short*)TTYPORT_ADDR;
for(int i = 0; i < N; ++i)
*ttyport = a[i]; // *ttyport is an lvalue of type volatile short
```
2) `static` `volatile` objects of type `[sig\_atomic\_t](../program/sig_atomic_t "c/program/sig atomic t")` are used for communication with `[signal](../program/signal "c/program/signal")` handlers.
3) `volatile` variables that are local to a function that contains an invocation of the `[setjmp](../program/setjmp "c/program/setjmp")` macro are the only local variables guaranteed to retain their values after `[longjmp](../program/longjmp "c/program/longjmp")` returns.
4) In addition, volatile variables can be used to disable certain forms of optimization, e.g. to disable dead store elimination or constant folding for microbenchmarks. Note that volatile variables are not suitable for communication between threads; they do not offer atomicity, synchronization, or memory ordering. A read from a volatile variable that is modified by another thread without synchronization or concurrent modification from two unsynchronized threads is undefined behavior due to a data race.
### Keywords
[`volatile`](https://en.cppreference.com/w/cpp/keyword/volatile "cpp/keyword/volatile").
### Example
demonstrates the use of volatile to disable optimizations.
```
#include <stdio.h>
#include <time.h>
int main(void)
{
clock_t t = clock();
double d = 0.0;
for (int n = 0; n < 10000; ++n)
for (int m = 0; m < 10000; ++m)
d += d * n * m; // reads from and writes to a non-volatile
printf("Modified a non-volatile variable 100m times. "
"Time used: %.2f seconds\n",
(double)(clock() - t)/CLOCKS_PER_SEC);
t = clock();
volatile double vd = 0.0;
for (int n = 0; n < 10000; ++n)
for (int m = 0; m < 10000; ++m) {
double prod = vd * n * m; // reads from a volatile
vd += prod; // reads from and writes to a volatile
}
printf("Modified a volatile variable 100m times. "
"Time used: %.2f seconds\n",
(double)(clock() - t)/CLOCKS_PER_SEC);
}
```
Possible output:
```
Modified a non-volatile variable 100m times. Time used: 0.00 seconds
Modified a volatile variable 100m times. Time used: 0.79 seconds
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.3 Type qualifiers (p: 87-90)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.3 Type qualifiers (p: 121-123)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.3 Type qualifiers (p: 108-110)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 6.5.3 Type qualifiers
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/cv "cpp/language/cv") for cv (`const` and `volatile`) type qualifiers |
| programming_docs |
c Lifetime Lifetime
========
Every [object](object "c/language/object") in C exists, has a constant address, retains its last-stored value (except when the value is indeterminate), and, for VLA, retains its size (since C99) over a portion of program execution known as this object's *lifetime*.
For the objects that are declared with automatic, static, and thread storage duration, lifetime equals their [storage duration](storage_duration "c/language/storage duration") (note the difference between non-VLA and VLA automatic storage duration).
For the objects with allocated storage duration, the lifetime begins when the allocation function returns (including the return from `[realloc](../memory/realloc "c/memory/realloc")`) and ends when the `[realloc](../memory/realloc "c/memory/realloc")` or deallocation function is called. Note that since allocated objects have no [declared type](object "c/language/object"), the type of the lvalue expression first used to access this object becomes its [effective type](object "c/language/object").
Accessing an object outside of its lifetime is undefined behavior.
```
int* foo(void) {
int a = 17; // a has automatic storage duration
return &a;
} // lifetime of a ends
int main(void) {
int* p = foo(); // p points to an object past lifetime ("dangling pointer")
int n = *p; // undefined behavior
}
```
A pointer to an object (or one past the object) whose lifetime ended has indeterminate value.
### Temporary lifetime
Struct and union objects with array members (either direct or members of nested struct/union members) that are designated by [non-lvalue expressions](value_category "c/language/value category"), have *temporary lifetime*. Temporary lifetime begins when the expression that refers to such object is evaluated and ends at the next [sequence point](eval_order "c/language/eval order") (until C11)when the containing full expression or full declarator ends (since C11).
Any attempt to modify an object with temporary lifetime results in undefined behavior.
```
struct T { double a[4]; };
struct T f(void) { return (struct T){3.15}; }
double g1(double* x) { return *x; }
void g2(double* x) { *x = 1.0; }
int main(void)
{
double d = g1(f().a); // C99: UB access to a[0] in g1 whose lifetime ended
// at the sequence point at the start of g1
// C11: OK, d is 3.15
g2(f().a); // C99: UB modification of a[0] whose lifetime ended at the sequence point
// C11: UB attempt to modify a temporary object
}
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.2.4 Storage durations of objects (p: 30)
* C11 standard (ISO/IEC 9899:2011):
+ 6.2.4 Storage durations of objects (p: 38-39)
* C99 standard (ISO/IEC 9899:1999):
+ 6.2.4 Storage durations of objects (p: 32)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.2.4 Storage durations of objects
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/lifetime "cpp/language/lifetime") for Object lifetime |
c Assignment operators Assignment operators
====================
Assignment and compound assignment operators are binary operators that modify the variable to their left using the value to their right.
| Operator | Operator name | Example | Description | Equivalent of |
| --- | --- | --- | --- | --- |
| `=` | basic assignment | `a = b` | **a** becomes equal to **b** | N/A |
| `+=` | addition assignment | `a += b` | **a** becomes equal to the addition of **a** and **b** | `a = a + b` |
| `-=` | subtraction assignment | `a -= b` | **a** becomes equal to the subtraction of **b** from **a** | `a = a - b` |
| `*=` | multiplication assignment | `a *= b` | **a** becomes equal to the product of **a** and **b** | `a = a * b` |
| `/=` | division assignment | `a /= b` | **a** becomes equal to the division of **a** by **b** | `a = a / b` |
| `%=` | modulo assignment | `a %= b` | **a** becomes equal to the remainder of **a** divided by **b** | `a = a % b` |
| `&=` | bitwise AND assignment | `a &= b` | **a** becomes equal to the bitwise AND of **a** and **b** | `a = a & b` |
| `|=` | bitwise OR assignment | `a |= b` | **a** becomes equal to the bitwise OR of **a** and **b** | `a = a | b` |
| `^=` | bitwise XOR assignment | `a ^= b` | **a** becomes equal to the bitwise XOR of **a** and **b** | `a = a ^ b` |
| `<<=` | bitwise left shift assignment | `a <<= b` | **a** becomes equal to **a** left shifted by **b** | `a = a << b` |
| `>>=` | bitwise right shift assignment | `a >>= b` | **a** becomes equal to **a** right shifted by **b** | `a = a >> b` |
### Simple assignment
The simple assignment operator expressions have the form.
| | | |
| --- | --- | --- |
| lhs `=` rhs | | |
where.
| | | |
| --- | --- | --- |
| lhs | - | [modifiable lvalue](value_category "c/language/value category") expression of any complete object type |
| rhs | - | expression of any type [implicitly convertible](conversion "c/language/conversion") to lhs or [compatible](type#Compatible_types "c/language/type") with lhs |
Assignment performs [implicit conversion](conversion "c/language/conversion") from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs.
Assignment also returns the same value as what was stored in `lhs` (so that expressions such as `a = b = c` are possible). The [value category](value_category "c/language/value category") of the assignment operator is non-lvalue (so that expressions such as `(a=b)=c` are invalid).
rhs and lhs must satisfy one of the following:
* both lhs and rhs have [compatible](type#Compatible_types "c/language/type") [struct](struct "c/language/struct") or [union](union "c/language/union") type, or..
* rhs must be [implicitly convertible](conversion "c/language/conversion") to lhs, which implies
+ both lhs and rhs have [arithmetic types](arithmetic_types "c/language/arithmetic types"), in which case lhs may be [volatile](volatile "c/language/volatile")-qualified or [atomic](atomic "c/language/atomic") (since C11)
+ both lhs and rhs have [pointer](pointer "c/language/pointer") to [compatible](type#Compatible_types "c/language/type") (ignoring qualifiers) types, or one of the pointers is a pointer to void, and the [conversion](conversion "c/language/conversion") would not add qualifiers to the pointed-to type. lhs may be [volatile](volatile "c/language/volatile") or [restrict](restrict "c/language/restrict") (since C99)-qualified or [atomic](atomic "c/language/atomic") (since C11).
+ lhs is a (possibly qualified or atomic (since C11)) pointer and rhs is a null pointer constant such as `[NULL](../types/null "c/types/NULL")` or a `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` value (since C23)
| | |
| --- | --- |
| * lhs has type (possibly qualified or atomic (since C11)) `_Bool` and rhs is a pointer or a `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` value (since C23)
| (since C99) |
| | |
| --- | --- |
| * lhs has type (possibly qualified or atomic) `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` and rhs has type `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")`
| (since C23) |
#### Notes
If rhs and lhs overlap in memory (e.g. they are members of the same union), the behavior is undefined unless the overlap is exact and the types are [compatible](type#Compatible_types "c/language/type").
Although arrays are not assignable, an array wrapped in a struct is assignable to another object of the same (or compatible) struct type.
The side effect of updating lhs is [sequenced after](eval_order "c/language/eval order") the value computations, but not the side effects of lhs and rhs themselves and the evaluations of the operands are, as usual, unsequenced relative to each other (so the expressions such as `i=++i`; are undefined).
Assignment strips extra range and precision from floating-point expressions (see `[FLT\_EVAL\_METHOD](../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")`).
In C++, assignment operators are lvalue expressions, not so in C.
```
#include <stdio.h>
int main(void)
{
// integers
int i = 1, j = 2, k = 3; // initialization, not assignment
i = j = k; // values of i and j are now 3
// (i = j) = k; // Error: lvalue required
printf("%d %d %d\n", i, j, k);
// pointers
const char c = 'A'; // initialization; not assignment
const char *p = &c; // initialization; not assignment
const char **cpp = &p; // initialization; not assignment
// cpp = &p; // Error: char** is not convertible to const char**
*cpp = &c; // OK, char* is convertible to const char*
printf("%c \n", **cpp);
cpp = 0; // OK, null pointer constant is convertible to any pointer
// arrays
int arr1[2] = {1,2}, arr2[2] = {3, 4};
// arr1 = arr2; // Error: cannot assign to an array
printf("arr1[0]=%d arr1[1]=%d arr2[0]=%d arr2[1]=%d\n",
arr1[0], arr1[1], arr2[0], arr2[1]);
struct { int arr[2]; } sam1 = { {5, 6} }, sam2 = { {7, 8} };
sam1 = sam2; // OK: can assign arrays wrapped in structs
printf("%d %d \n", sam1.arr[0], sam1.arr[1]);
}
```
Output:
```
3 3 3
A
arr1[0]=1 arr1[1]=2 arr2[0]=3 arr2[1]=4
7 8
```
### Compound assignment
The compound assignment operator expressions have the form.
| | | |
| --- | --- | --- |
| lhs op rhs | | |
where.
| | | |
| --- | --- | --- |
| op | - | one of `*=`, `/=` `%=`, `+=` `-=`, `<<=`, `>>=`, `&=`, `^=`, `|=` |
| lhs, rhs | - | expressions with [arithmetic types](arithmetic_types "c/language/arithmetic types") (where lhs may be qualified or atomic), except when op is `+=` or `-=`, which also accept pointer types with the same restrictions as + and - |
The expression lhs @= rhs is exactly the same as lhs `=` lhs @ `(` rhs `)`, except that lhs is evaluated only once.
| | |
| --- | --- |
| If lhs has [atomic](atomic "c/language/atomic") type, the operation behaves as a single atomic read-modify-write operation with memory order `[memory\_order\_seq\_cst](../atomic/memory_order "c/atomic/memory order")`.
For integer atomic types, the compound assignment `@=` is equivalent to:
```
T1* addr = &lhs;
T2 val = rhs;
T1 old = *addr;
T1 new;
do { new = old @ val } while (!atomic_compare_exchange_strong(addr, &old, new);
```
| (since C11) |
```
#include <stdio.h>
int main(void)
{
int x = 10;
int hundred = 100;
int ten = 10;
int fifty = 50;
printf("%d %d %d %d\n", x, hundred, ten, fifty);
hundred *= x;
ten /= x;
fifty %= x;
printf("%d %d %d %d\n", x, hundred, ten, fifty);
return 0;
}
```
Output:
```
10 100 10 50
10 1000 1 0
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.5.16 Assignment operators (p: 72-73)
* C11 standard (ISO/IEC 9899:2011):
+ 6.5.16 Assignment operators (p: 101-104)
* C99 standard (ISO/IEC 9899:1999):
+ 6.5.16 Assignment operators (p: 91-93)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.3.16 Assignment operators
### See Also
[Operator precedence](operator_precedence "c/language/operator precedence").
| Common operators |
| --- |
| **assignment** | [incrementdecrement](operator_incdec "c/language/operator incdec") | [arithmetic](operator_arithmetic "c/language/operator arithmetic") | [logical](operator_logical "c/language/operator logical") | [comparison](operator_comparison "c/language/operator comparison") | [memberaccess](operator_member_access "c/language/operator member access") | [other](operator_other "c/language/operator other") |
| `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b`. | `a[b] *a &a a->b a.b`. | `a(...) a, b (type) a ? : sizeof _Alignof` (since C11). |
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_assignment "cpp/language/operator assignment") for Assignment operators |
c Typedef declaration Typedef declaration
===================
The *typedef declaration* provides a way to declare an identifier as a type alias, to be used to replace a possibly complex [type name](type#Type_names "c/language/type").
The keyword `typedef` is used in a [declaration](declarations "c/language/declarations"), in the grammatical position of a [storage-class specifier](storage_duration "c/language/storage duration"), except that it does not affect storage or linkage:
```
typedef int int_t; // declares int_t to be an alias for the type int
typedef char char_t, *char_p, (*fp)(void); // declares char_t to be an alias for char
// char_p to be an alias for char*
// fp to be an alias for char(*)(void)
```
### Explanation
If a [declaration](declarations "c/language/declarations") uses `typedef` as storage-class specifier, every declarator in it defines an identifier as an alias to the type specified. Since only one storage-class specifier is permitted in a declaration, typedef declaration cannot be [static or extern](storage_duration "c/language/storage duration").
typedef declaration does not introduce a distinct type, it only establishes a synonym for an existing type, thus typedef names are [compatible](type#Compatible_types "c/language/type") with the types they alias. Typedef names share the [name space](name_space "c/language/name space") with ordinary identifiers such as enumerators, variables and function.
| | |
| --- | --- |
| A typedef for a VLA can only appear at block scope. The length of the array is evaluated each time the flow of control passes over the typedef declaration, as opposed to the declaration of the array itself:
```
void copyt(int n)
{
typedef int B[n]; // B is a VLA, its size is n, evaluated now
n += 1;
B a; // size of a is n from before +=1
int b[n]; // a and b are different sizes
for (int i = 1; i < n; i++)
a[i-1] = b[i];
}
```
| (since C99) |
### Notes
typedef name may be an [incomplete type](type#Incomplete_types "c/language/type"), which may be completed as usual:
```
typedef int A[]; // A is int[]
A a = {1, 2}, b = {3,4,5}; // type of a is int[2], type of b is int[3]
```
typedef declarations are often used to inject names from the tag [name space](name_space "c/language/name space") into the ordinary name space:
```
typedef struct tnode tnode; // tnode in ordinary name space
// is an alias to tnode in tag name space
struct tnode {
int count;
tnode *left, *right; // same as struct tnode *left, *right;
}; // now tnode is also a complete type
tnode s, *sp; // same as struct tnode s, *sp;
```
They can even avoid using the tag name space at all:
```
typedef struct { double hi, lo; } range;
range z, *zp;
```
Typedef names are also commonly used to simplify the syntax of complex declarations:
```
// array of 5 pointers to functions returning pointers to arrays of 3 ints
int (*(*callbacks[5])(void))[3]
// same with typedefs
typedef int arr_t[3]; // arr_t is array of 3 int
typedef arr_t* (*fp)(void); // pointer to function returning arr_t*
fp callbacks[5];
```
Libraries often expose system-dependent or configuration-dependent types as typedef names, to present a consistent interface to the users or to other library components:
```
#if defined(_LP64)
typedef int wchar_t;
#else
typedef long wchar_t;
#endif
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.8 Type definitions (p: 137-138)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.7 Type definitions (p: 123-124)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.5.6 Type definitions
### Keywords
[`typedef`](../keyword/typedef "c/keyword/typedef").
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/typedef "cpp/language/typedef") for `typedef` declaration |
c String literals String literals
===============
Constructs an unnamed object of specified character array type in-place, used when a character string needs to be embedded in source code.
### Syntax
| | | |
| --- | --- | --- |
| `"` s-char-sequence `"` | (1) | |
| `u8"` s-char-sequence `"` | (2) | (since C11) |
| `u"` s-char-sequence `"` | (3) | (since C11) |
| `U"` s-char-sequence `"` | (4) | (since C11) |
| `L"` s-char-sequence `"` | (5) | |
where.
| | | |
| --- | --- | --- |
| s-char-sequence | - | zero or more characters, each of which is either a multibyte character from the source character set (excluding (`"`), `\`, and newline), or character escape, hex escape, octal escape, or universal character name (since C99) as defined in [escape sequences](escape "c/language/escape"). |
1) *character string literal*: The type of the literal is `char[N]`, where `N` is the size of the string in code units of the execution narrow encoding, including the null terminator. Each `char` element in the array is initialized from the next character in s-char-sequence using the execution character set.
2) *UTF-8 string literal*: The type of the literal is `char[N]` (until C23)`unsigned char[N]` (since C23), where `N` is the size of the string in UTF-8 code units including the null terminator. Each `char` (until C23)`unsigned char` (since C23) element in the array is initialized from the next multibyte character in s-char-sequence using UTF-8 encoding.
| | |
| --- | --- |
| 3) 16-bit wide string literal: The type of the literal is `char16_t[N]`, where `N` is the size of the string in code units of implementation-defined 16-bit encoding (typically UTF-16), including the null terminator. Each `char16_t` element in the array is initialized as if by executing `[mbrtoc16](../string/multibyte/mbrtoc16 "c/string/multibyte/mbrtoc16")` in implementation-defined locale. 4) 32-bit wide string literal: The type of the literal is `char32_t[N]`, where `N` is the size of the string in code units of implementation-defined 32-bit encoding (typically UTF-32), including the null terminator. Each `char32_t` element in the array is initialized as if by executing `[mbrtoc32](../string/multibyte/mbrtoc32 "c/string/multibyte/mbrtoc32")` in implementation-defined locale. | (until C23) |
| 3) *UTF-16 string literal*: The type of the literal is `char16_t[N]`, where `N` is the size of the string in UTF-16 code units including the null terminator. Each `char16_t` element in the array is initialized from the next multibyte character in s-char-sequence using UTF-16 encoding. 4) *UTF-32 string literal*: The type of the literal is `char32_t[N]`, where `N` is the size of the string in UTF-32 code units including the null terminator. Each `char32_t` element in the array is initialized from the next multibyte character in s-char-sequence using UTF-32 encoding. | (since C23) |
5) wide string literal: The type of the literal is `wchar_t[N]`, where `N` is the size of the string in code units of the execution wide encoding, including the null terminator. Each `wchar_t` element in the array is initialized as if by executing `[mbstowcs](../string/multibyte/mbstowcs "c/string/multibyte/mbstowcs")` in implementation-defined locale. ### Explanation
First, at [translation phase 6](translation_phases "c/language/translation phases") (after macro expansion), the adjacent string literals (that is, string literals separated by whitespace only) are concatenated.
| | |
| --- | --- |
| Only two narrow or two wide string literals may be concatenated. | (until C99) |
| If one literal is unprefixed, the resulting string literal has the width/encoding specified by the prefixed literal.
```
L"Δx = %" PRId16 // at phase 4, PRId16 expands to "d"
// at phase 6, L"Δx = %" and "d" form L"Δx = %d"
```
| (since C99) |
| | |
| --- | --- |
| If the two string literals have different encoding prefixes, concatenation is implementation-defined, except that a UTF-8 string literal and a wide string literal cannot be concatenated. | (since C11)(until C23) |
| If the two string literals have different encoding prefixes, concatenation is ill-formed. | (since C23) |
Secondly, at [translation phase 7](translation_phases "c/language/translation phases"), a terminating null character is added to each string literal, and then each literal initializes an unnamed array with static [storage duration](storage_duration "c/language/storage duration") and length just enough to contain the contents of the string literal plus one for the null terminator.
```
char* p = "\x12" "3"; // creates a static char[3] array holding {'\x12', '3', '\0'}
// sets p to point to the first element of the array
```
String literals are **not modifiable** (and in fact may be placed in read-only memory such as `.rodata`). If a program attempts to modify the static array formed by a string literal, the behavior is undefined.
```
char* p = "Hello";
p[1] = 'M'; // Undefined behavior
char a[] = "Hello";
a[1] = 'M'; // OK: a is not a string literal
```
It is neither required nor forbidden for identical string literals to refer to the same location in memory. Moreover, overlapping string literals or string literals that are substrings of other string literals may be combined.
```
"def" == 3+"abcdef"; // may be 1 or 0, implementation-defined
```
### Notes
A string literal is not necessarily a string; if a string literal has embedded null characters, it represents an array which contains more than one string:
```
char* p = "abc\0def"; // strlen(p) == 3, but the array has size 8
```
If a valid hex digit follows a hex escape in a string literal, it would fail to compile as an invalid escape sequence, but string concatenation can be used as a workaround:
```
//char* p = "\xfff"; // error: hex escape sequence out of range
char* p = "\xff""f"; // okay, the literal is char[3] holding {'\xff', 'f', '\0'}
```
String literals can be used to [initialize arrays](array_initialization "c/language/array initialization"), and if the size of the array is one less the size of the string literal, the null terminator is ignored:
```
char a1[] = "abc"; // a1 is char[4] holding {'a', 'b', 'c', '\0'}
char a2[4] = "abc"; // a2 is char[4] holding {'a', 'b', 'c', '\0'}
char a3[3] = "abc"; // a3 is char[3] holding {'a', 'b', 'c'}
```
The encoding of character string literals (1) and wide string literals (5) is implementation-defined. For example, gcc selects them with the [commandline options](https://gcc.gnu.org/onlinedocs/cpp/Invocation.html) `-fexec-charset` and `-fwide-exec-charset`.
Although mixed wide string literal concatenation is allowed in C11, almost all compilers reject such concatenation (the only known exception is [SDCC](http://sdcc.sourceforge.net/)), and its usage experience is unknown. As a result, allowance of mixed wide string literal concatenation is removed in C23.
### Example
```
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <uchar.h>
#include <locale.h>
int main(void)
{
char s1[] = "a猫🍌"; // or "a\u732B\U0001F34C"
char s2[] = u8"a猫🍌";
char16_t s3[] = u"a猫🍌";
char32_t s4[] = U"a猫🍌";
wchar_t s5[] = L"a猫🍌";
setlocale(LC_ALL, "en_US.utf8");
printf(" \"%s\" is a char[%zu] holding { ", s1, sizeof s1 / sizeof *s1);
for(size_t n = 0; n < sizeof s1 / sizeof *s1; ++n)
printf("0x%02X ", +(unsigned char)s1[n]);
puts("}");
printf("u8\"%s\" is a char[%zu] holding { ", s2, sizeof s2 / sizeof *s2);
for(size_t n = 0; n < sizeof s2 / sizeof *s2; ++n)
printf("0x%02X ", +(unsigned char)s2[n]);
puts("}");
printf(" u\"a猫🍌\" is a char16_t[%zu] holding { ", sizeof s3 / sizeof *s3);
for(size_t n = 0; n < sizeof s3 / sizeof *s3; ++n)
printf("0x%04X ", s3[n]);
puts("}");
printf(" U\"a猫🍌\" is a char32_t[%zu] holding { ", sizeof s4 / sizeof *s4);
for(size_t n = 0; n < sizeof s4 / sizeof *s4; ++n)
printf("0x%08X ", s4[n]);
puts("}");
printf(" L\"%ls\" is a wchar_t[%zu] holding { ", s5, sizeof s5 / sizeof *s5);
for(size_t n = 0; n < sizeof s5 / sizeof *s5; ++n)
printf("0x%08X ", (unsigned)s5[n]);
puts("}");
}
```
Possible output:
```
"a猫🍌" is a char[9] holding { 0x61 0xE7 0x8C 0xAB 0xF0 0x9F 0x8D 0x8C 0x00 }
u8"a猫🍌" is a char[9] holding { 0x61 0xE7 0x8C 0xAB 0xF0 0x9F 0x8D 0x8C 0x00 }
u"a猫🍌" is a char16_t[5] holding { 0x0061 0x732B 0xD83C 0xDF4C 0x0000 }
U"a猫🍌" is a char32_t[4] holding { 0x00000061 0x0000732B 0x0001F34C 0x00000000 }
L"a猫🍌" is a wchar_t[4] holding { 0x00000061 0x0000732B 0x0001F34C 0x00000000 }
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.4.5 String literals (p: 50-52)
* C11 standard (ISO/IEC 9899:2011):
+ 6.4.5 String literals (p: 70-72)
* C99 standard (ISO/IEC 9899:1999):
+ 6.4.5 String literals (p: 62-63)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.4 String literals
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/string_literal "cpp/language/string literal") for string literal |
| programming_docs |
c Basic concepts Basic concepts
==============
This section provides definitions for the specific terminology and the concepts used when describing the C programming language.
A C program is a sequence of text files (typically header and source files) that contain [declarations](declarations "c/language/declarations"). They undergo [translation](translation_phases "c/language/translation phases") to become an executable program, which is executed when the OS calls its [main function](main_function "c/language/main function") (unless it is itself the OS or another *freestanding* program, in which case the entry point is implementation-defined).
Certain words in a C program have special meaning, they are [keywords](../keyword "c/keyword"). Others can be used as [identifiers](identifier "c/language/identifier"), which may be used to identify [objects](object "c/language/object"), [functions](functions "c/language/functions"), [struct](struct "c/language/struct"), [union](union "c/language/union"), or [enumeration](enum "c/language/enum") tags, their members, [typedef](typedef "c/language/typedef") names, [labels](statements#Labels "c/language/statements"), or [macros](../preprocessor/replace "c/preprocessor/replace").
Each identifier (other than macro) is only valid within a part of the program called its [scope](scope "c/language/scope") and belongs to one of four kinds of [name spaces](name_space "c/language/name space"). Some identifiers have [linkage](storage_duration "c/language/storage duration") which makes them refer to the same entities when they appear in different scopes or translation units.
Definitions of functions include sequences of [statements](statements "c/language/statements") and [declarations](declarations "c/language/declarations"), some of which include [expressions](expressions "c/language/expressions"), which specify the computations to be performed by the program.
[Declarations](declarations "c/language/declarations") and [expressions](expressions "c/language/expressions") create, destroy, access, and manipulate [objects](object "c/language/object"). Each [object](object "c/language/object"), [function](functions "c/language/functions"), and [expression](expressions "c/language/expressions") in C is associated with a [type](type "c/language/type").
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/basic_concepts "cpp/language/basic concepts") for Basic concepts |
c Storage-class specifiers Storage-class specifiers
========================
Specify *storage duration* and *linkage* of objects and functions:
* `auto` - automatic duration and no linkage
* `register` - automatic duration and no linkage; address of this variable cannot be taken
* `static` - static duration and internal linkage (unless at block scope)
* `extern` - static duration and external linkage (unless already declared internal)
| | |
| --- | --- |
| * `_Thread_local` - thread storage duration
| (since C11) |
### Explanation
Storage-class specifiers appear in [declarations](declarations "c/language/declarations"). At most one specifier may be used, except that `_Thread_local` may be combined with `static` or `extern` to adjust linkage (since C11). The storage-class specifiers determine two independent properties of the names they declare: *storage duration* and *linkage*.
1) The `auto` specifier is only allowed for objects declared at block scope (except function parameter lists). It indicates automatic storage duration and no linkage, which are the defaults for these kinds of declarations.
2) The `register` specifier is only allowed for objects declared at block scope, including function parameter lists. It indicates automatic storage duration and no linkage (which is the default for these kinds of declarations), but additionally hints the optimizer to store the value of this variable in a CPU register if possible. Regardless of whether this optimization takes place or not, variables declared `register` cannot be used as arguments to the [address-of operator](operator_member_access "c/language/operator member access"), cannot use [alignas](_alignas "c/language/ Alignas") (since C11), and `register` arrays are not convertible to pointers.
3) The `static` specifier specifies both static storage duration (unless combined with `_Thread_local`) (since C11) and internal linkage (unless used at block scope). It can be used with functions at file scope and with variables at both file and block scope, but not in function parameter lists.
4) The `extern` specifier specifies static storage duration (unless combined with `_Thread_local`) (since C11) and external linkage. It can be used with function and object declarations in both file and block scope (excluding function parameter lists). If `extern` appears on a redeclaration of an identifier that was already declared with internal linkage, the linkage remains internal. Otherwise (if the prior declaration was external, no-linkage, or is not in scope), the linkage is external.
| | |
| --- | --- |
| 5) `_Thread_local` indicates *thread storage duration*. It cannot be used with function declarations. If it is used on a declaration of an object, it must be present on every declaration of the same object. If it is used on a block-scope declaration, it must be combined with either `static` or `extern` to decide linkage. | (since C11) |
If no storage-class specifier is provided, the defaults are:
`extern` for all functions
`extern` for objects at file scope
`auto` for objects at block scope
For any struct or union declared with a storage-class specifier, the storage duration (but not linkage) applies to their members, recursively.
Function declarations at block scope can use `extern` or none at all. Function declarations at file scope can use `extern` or `static`.
Function parameters cannot use any storage-class specifiers other than `register`. Note that `static` has special meaning in function parameters of array type.
### Storage duration
Every [object](object "c/language/object") has a property called *storage duration*, which limits the object [lifetime](lifetime "c/language/lifetime"). There are four kinds of storage duration in C:
* ***automatic*** storage duration. The storage is allocated when the [block](statements#Compound_statements "c/language/statements") in which the object was declared is entered and deallocated when it is exited by any means ([goto](goto "c/language/goto"), [return](return "c/language/return"), reaching the end). One exception is the [VLAs](array#Variable-length_arrays "c/language/array"); their storage is allocated when the declaration is executed, not on block entry, and deallocated when the declaration goes out of scope, not when the block is exited (since C99). If the block is entered recursively, a new allocation is performed for every recursion level. All function parameters and non-`static` block-scope objects have this storage duration, as well as [compound literals](compound_literal "c/language/compound literal") used at block scope.
+ ***static*** storage duration. The storage duration is the entire execution of the program, and the value stored in the object is initialized only once, prior to [main function](main_function "c/language/main function"). All objects declared `static` and all objects with either internal or external linkage that aren't declared `_Thread_local` (since C11) have this storage duration.
| | |
| --- | --- |
| * ***thread*** storage duration. The storage duration is the entire execution of the thread in which it was created, and the value stored in the object is initialized when the thread is started. Each thread has its own, distinct, object. If the thread that executes the expression that accesses this object is not the thread that executed its initialization, the behavior is implementation-defined. All objects declared `_Thread_local` have this storage duration.
| (since C11) |
* ***allocated*** storage duration. The storage is allocated and deallocated on request, using [dynamic memory allocation](../memory "c/memory") functions.
#### Linkage
Linkage refers to the ability of an identifier (variable or function) to be referred to in other scopes. If a variable or function with the same identifier is declared in several scopes, but cannot be referred to from all of them, then several instances of the variable are generated. The following linkages are recognized:
* ***no linkage***. The identifier can be referred to only from the scope it is in. All function parameters and all non-`extern` block-scope variables (including the ones declared `static`) have this linkage.
+ ***internal linkage***. The identifier can be referred to from all scopes in the current translation unit. All `static` file-scope identifiers (both functions and variables) have this linkage.
+ ***external linkage***. The identifier can be referred to from any other translation units in the entire program. All non-`static` functions, all `extern` variables (unless earlier declared `static`), and all file-scope non-`static` variables have this linkage.
If the same identifier appears with both internal and external linkage in the same translation unit, the behavior is undefined. This is possible when [tentative definitions](extern "c/language/extern") are used.
#### Linkage and libraries
Declarations with external linkage are commonly made available in header files so that all translation units that [#include](../preprocessor/include "c/preprocessor/include") the file may refer to the same identifier that are defined elsewhere.
Any declaration with internal linkage that appears in a header file results in a separate and distinct object in each translation unit that includes that file.
Library interface:
```
// flib.h
#ifndef FLIB_H
#define FLIB_H
void f(void); // function declaration with external linkage
extern int state; // variable declaration with external linkage
static const int size = 5; // definition of a read-only variable with internal linkage
enum { MAX = 10 }; // constant definition
inline int sum (int a, int b) { return a+b; } // inline function definition
#endif // FLIB_H
```
Library implementation:
```
// flib.c
#include "flib.h"
static void local_f(int s) {} // definition with internal linkage (only used in this file)
static int local_state; // definition with internal linkage (only used in this file)
int state; // definition with external linkage (used by main.c)
void f(void) {local_f(state);} // definition with external linkage (used by main.c)
```
Application code:
```
// main.c
#include "flib.h"
int main(void)
{
int x[MAX] = {size}; // uses the constant and the read-only variable
state = 7; // modifies state in flib.c
f(); // calls f() in flib.c
}
```
### Keywords
[`auto`](../keyword/auto "c/keyword/auto"), [`register`](../keyword/register "c/keyword/register"), [`static`](../keyword/static "c/keyword/static"), [`extern`](../keyword/extern "c/keyword/extern"), [`_Thread_local`](../keyword/_thread_local "c/keyword/ Thread local").
### Notes
The keyword `_Thread_local` is usually used through the convenience macro `[thread\_local](../thread/thread_local "c/thread/thread local")`, defined in the header `threads.h`.
The [typedef](typedef "c/language/typedef") specifier is formally listed as a storage-class specifier in the C language grammar, but it is used to declare type names and does not specify storage.
Names at file scope that are `const` and not `extern` have external linkage in C (as the default for all file-scope declarations), but internal linkage in C++.
### Example
```
#include <stdio.h>
#include <stdlib.h>
/* static storage duration */
int A;
int main(void)
{
printf("&A = %p\n", (void*)&A);
/* automatic storage duration */
int A = 1; // hides global A
printf("&A = %p\n", (void*)&A);
/* allocated storage duration */
int *ptr_1 = malloc(sizeof(int)); /* start allocated storage duration */
printf("address of int in allocated memory = %p\n", (void*)ptr_1);
free(ptr_1); /* stop allocated storage duration */
}
```
Possible output:
```
&A = 0x600ae4
&A = 0x7ffefb064f5c
address of int in allocated memory = 0x1f28c30
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.2.2 Linkages of identifiers (p: 29-30)
+ 6.2.4 Storage durations of objects (p: 30)
+ 6.7.1 Storage-class specifiers (p: 79)
* C11 standard (ISO/IEC 9899:2011):
+ 6.2.2 Linkages of identifiers (p: 36-37)
+ 6.2.4 Storage durations of objects (p: 38-39)
+ 6.7.1 Storage-class specifiers (p: 109-110)
* C99 standard (ISO/IEC 9899:1999):
+ 6.2.2 Linkages of identifiers (p: 30-31)
+ 6.2.4 Storage durations of objects (p: 32)
+ 6.7.1 Storage-class specifiers (p: 98-99)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.2.2 Linkages of identifiers
+ 3.1.2.4 Storage durations of objects
+ 3.5.1 Storage-class specifiers
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/storage_duration "cpp/language/storage duration") for Storage class specifiers |
c Memory model Memory model
============
Defines the semantics of computer memory storage for the purpose of the C abstract machine.
The data storage (memory) available to a C program is one or more contiguous sequences of *bytes*. Each byte in memory has a unique *address*.
### Byte
A *byte* is the smallest addressable unit of memory. It is defined as a contiguous sequence of bits, large enough to hold any member of the *basic execution character set* ([the 96 characters](translation_phases "c/language/translation phases") that are required to be single-byte). C supports bytes of sizes 8 bits and greater.
The [types](types "c/language/types") `char`, `unsigned char`, and `signed char` use one byte for both storage and [value representation](object "c/language/object"). The number of bits in a byte is accessible as `[CHAR\_BIT](../types/limits "c/types/limits")`.
For use of bytes to representation values of other fundamental types (including big-endian and little-endian memory layouts), see [object representation](object#Object_representation "c/language/object").
### Memory location
A *memory location* is.
* an object of [scalar type](type#Type_groups "c/language/type") (arithmetic type, pointer type, enumeration type)
* or the largest contiguous sequence of [bit fields](bit_field "c/language/bit field") of non-zero length
```
struct S {
char a; // memory location #1
int b : 5; // memory location #2
int c : 11, // memory location #2 (continued)
: 0,
d : 8; // memory location #3
struct {
int ee : 8; // memory location #4
} e;
} obj; // The object 'obj' consists of 4 separate memory locations
```
| | |
| --- | --- |
| Threads and data races A thread of execution is a flow of control within a program that begins with the invocation of a top-level function by `[thrd\_create](../thread/thrd_create "c/thread/thrd create")` or other means.
Any thread can potentially access any object in the program (objects with automatic and thread-local [storage duration](storage_duration "c/language/storage duration") may still be accessed by another thread through a pointer).
Different threads of execution are always allowed to access (read and modify) different *memory locations* concurrently, with no interference and no synchronization requirements. (note that it is not safe to concurrently update two non-atomic bit-fields in the same structure if all members declared between them are also (non-zero-length) bit-fields, no matter what the sizes of those intervening bit-fields happen to be).
When an [evaluation](eval_order "c/language/eval order") of an expression writes to a memory location and another evaluation reads or modifies the same memory location, the expressions are said to *conflict*. A program that has two conflicting evaluations has a *data race* unless either.* both conflicting evaluations are [atomic operations](atomic "c/language/atomic")
* one of the conflicting evaluations *happens-before* another (see `[memory\_order](../atomic/memory_order "c/atomic/memory order")`)
If a data race occurs, the behavior of the program is undefined. (in particular, `[mtx\_unlock](../thread/mtx_unlock "c/thread/mtx unlock")` is.
*synchronized-with*, and therefore, *happens-before* `[mtx\_lock](../thread/mtx_lock "c/thread/mtx lock")` of the same mutex by another thread, which makes it possible to use mutex locks to guard against data races) Memory order When a thread reads a value from a memory location, it may see the initial value, the value written in the same thread, or the value written in another thread. See `[memory\_order](../atomic/memory_order "c/atomic/memory order")` for details on the order in which writes made from threads become visible to other threads. | (since C11) |
### References
* C11 standard (ISO/IEC 9899:2011):
+ 3.6 byte (p: 4)
+ 3.14 memory location (p: 5)
+ 5.1.2.4 Multi-threaded executions and data races (p: 17-21)
* C99 standard (ISO/IEC 9899:1999):
+ 3.6 byte (p: 4)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 1.6 DEFINITIONS OF TERMS
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/memory_model "cpp/language/memory model") for Memory model |
c while loop while loop
==========
Executes a statement repeatedly, until the value of expression becomes equal to zero. The test takes place before each iteration.
### Syntax
| | | |
| --- | --- | --- |
| attr-spec-seq(optional) `while (` expression `)` statement | | |
| | | |
| --- | --- | --- |
| expression | - | any [expression](expressions "c/language/expressions") of [scalar type](type#Type_groups "c/language/type"). This expression is evaluated before each iteration, and if it compares equal to zero, the loop is exited. |
| statement | - | any [statement](statements "c/language/statements"), typically a compound statement, which serves as the body of the loop |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the loop statement |
### Explanation
A `while` statement causes the statement (also called *the loop body*) to be executed repeatedly until the expression (also called *controlling expression*) compares equal to zero. The repetition occurs regardless of whether the loop body is entered normally or by a [goto](goto "c/language/goto") into the middle of statement.
The evaluation of expression takes place before each execution of statement (unless entered by a goto). If the controlling expression needs to be evaluated after the loop body, the [do-while loop](do "c/language/do") may be used.
If the execution of the loop needs to be terminated at some point, [break statement](break "c/language/break") can be used as a terminating statement.
If the execution of the loop needs to be continued at the end of the loop body, [continue statement](continue "c/language/continue") can be used as a shortcut.
A program with an endless loop has undefined behavior if the loop has no observable behavior (I/O, volatile accesses, atomic or synchronization operation) in any part of its statement or expression. This allows the compilers to optimize out all unobservable loops without proving that they terminate. The only exceptions are the loops where expression is a constant expression; `while(true)` is always an endless loop.
| | |
| --- | --- |
| As with all other selection and iteration statements, the while statement establishes [block scope](scope "c/language/scope"): any identifier introduced in the expression goes out of scope after the statement. | (since C99) |
### Notes
Boolean and pointer expressions are often used as loop controlling expressions. The boolean value `false` and the null pointer value of any pointer type compare equal to zero.
### Keywords
[`while`](../keyword/while "c/keyword/while").
### Example
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { SIZE = 8 };
int main(void)
{
// trivial example
int array[SIZE], n = 0;
while(n < SIZE) array[n++] = rand() % 2;
puts("Array filled!");
n = 0;
while(n < SIZE) printf("%d ", array[n++]);
printf("\n");
// classic strcpy() implementation
// (copies a null-terminated string from src to dst)
char src[]="Hello, world", dst[sizeof src], *p=dst, *q=src;
while(*p++ = *q++)
; // null statement
puts(dst);
}
```
Output:
```
Array filled!
1 0 1 1 1 1 0 0
Hello, world
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.8.5.1 The while statement (p: 109)
* C11 standard (ISO/IEC 9899:2011):
+ 6.8.5.1 The while statement (p: 151)
* C99 standard (ISO/IEC 9899:1999):
+ 6.8.5.1 The while statement (p: 136)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.6.5.1 The while statement
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/while "cpp/language/while") for `while` loop |
| programming_docs |
c Initialization Initialization
==============
A [declaration](declarations "c/language/declarations") of an object may provide its initial value through the process known as *initialization*.
For each [declarator](declarations "c/language/declarations"), the initializer, if not omitted, may be one of the following:
| | | |
| --- | --- | --- |
| `=` expression | (1) | |
| `=` `{` initializer-list `}` | (2) | |
| `=` `{` `}` | (3) | (since C23) |
where initializer-list is a non-empty comma-separated list of initializers (with an optional trailing comma), where each initializer has one of three possible forms:
| | | |
| --- | --- | --- |
| expression | (1) | |
| `{` initializer-list `}` | (2) | |
| `{` `}` | (3) | (since C23) |
| designator-list `=` initializer | (4) | (since C99) |
| | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- |
| where designator-list is a list of either array designators of the form `[` constant-expression `]` or struct/union member designators of the form `.` identifier; see [array initialization](array_initialization "c/language/array initialization") and [struct initialization](struct_initialization "c/language/struct initialization").
Note: besides initializers, brace-enclosed initializer-list may appear in [compound literals](compound_literal "c/language/compound literal"), which are expressions of the form:
| | | |
| --- | --- | --- |
| `(` type `)` `{` initializer-list `}` | | |
| `(` type `)` `{` `}` | | (since C23) |
| (since C99) |
### Explanation
The initializer specifies the initial value stored in an object.
#### Explicit initialization
If an initializer is provided, see.
* [scalar initialization](scalar_initialization "c/language/scalar initialization") for the initialization of scalar types
* [array initialization](array_initialization "c/language/array initialization") for the initialization of array types
* [struct initialization](struct_initialization "c/language/struct initialization") for the initialization of struct and union types.
#### Implicit initialization
If an initializer is not provided:
* objects with automatic [storage duration](storage_duration "c/language/storage duration") are initialized to indeterminate values (which may be [trap representations](object "c/language/object"))
* objects with static and thread-local [storage duration](storage_duration "c/language/storage duration") are empty-initialized
#### Empty initialization
| | |
| --- | --- |
| An object is empty-initialized if it is explicitly initialized from initializer `= {}`. | (since C23) |
In some cases, an object is empty-initialized if it is not initialized explicitly, that is:
* pointers are initialized to null pointer values of their types
* objects of integral types are initialized to unsigned zero
* objects of floating types are initialized to positive zero
* all elements of arrays, all members of structs, and the first members of unions are empty-initialized, recursively, plus all padding bits are initialized to zero
(on platforms where null pointer values and floating zeroes have all-bit-zero representations, this form of initialization for statics is normally implemented by allocating them in the .bss section of the program image) ### Notes
When initializing an object of static or thread-local [storage duration](storage_duration "c/language/storage duration"), every expression in the initializer must be a [constant expression](constant_expression "c/language/constant expression") or [string literal](string_literal "c/language/string literal").
Initializers cannot be used in declarations of objects of incomplete type, VLAs, and block-scope objects with linkage.
The initial values of function parameters are established as if by assignment from the arguments of a [function call](operator_other#Function_call "c/language/operator other"), rather than by initialization.
If an indeterminate value is used as an argument to any standard library call, the behavior is undefined. Otherwise, the result of any expression involving indeterminate values is an indeterminate value (e.g. `int n;`, `n` may not compare equal to itself and it may appear to change its value on subsequent reads).
| | |
| --- | --- |
| There is no special construct in C corresponding to [value initialization](https://en.cppreference.com/w/cpp/language/value_initialization "cpp/language/value initialization") in C++; however, `= {0}` (or `(T){0}` in compound literals) (since C99) can be used instead, as the C standard does not allow empty structs, empty unions, or arrays of zero length. | (until C23) |
| The empty initializer `= {}` (or `(T){}` in compound literals) can be used to achieve the same semantics as [value initialization](https://en.cppreference.com/w/cpp/language/value_initialization "cpp/language/value initialization") in C++. | (since C23) |
### Example
```
#include <stdlib.h>
int a[2]; // initializes a to {0, 0}
int main(void)
{
int i; // initializes i to an indeterminate value
static int j; // initializes j to 0
int k = 1; // initializes k to 1
// initializes int x[3] to 1,3,5
// initializes int* p to &x[0]
int x[] = { 1, 3, 5 }, *p = x;
// initializes w (an array of two structs) to
// { { {1,0,0}, 0}, { {2,0,0}, 0} }
struct {int a[3], b;} w[] = {[0].a = {1}, [1].a[0] = 2};
// function call expression can be used for a local variable
char* ptr = malloc(10);
free(ptr);
// Error: objects with static storage duration require constant initializers
// static char* ptr = malloc(10);
// Error: VLA cannot be initialized
// int vla[n] = {0};
}
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.9 Initialization (p: 100-105)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.9 Initialization (p: 139-144)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.8 Initialization (p: 125-130)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 6.5.7 Initialization
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/initialization "cpp/language/initialization") for Initialization |
c Declarations Declarations
============
A *declaration* is a C language construct that introduces one or more [identifiers](identifier "c/language/identifier") into the program and specifies their meaning and properties.
Declarations may appear in any scope. Each declaration ends with a semicolon (just like [a statement](statements "c/language/statements")) and consists of two (until C23)three (since C23) distinct parts:
| | | |
| --- | --- | --- |
| specifiers-and-qualifiers declarators-and-initializers(optional) `;` | (1) | |
| attr-spec-seq specifiers-and-qualifiers declarators-and-initializers `;` | (2) | (since C23) |
| attr-spec-seq `;` | (3) | (since C23) |
where.
| | | |
| --- | --- | --- |
| specifiers-and-qualifiers | - | whitespace-separated list of, in any order, * type specifiers:
+ `void`
+ the name of an [arithmetic type](arithmetic_types "c/language/arithmetic types")
+ the name of an [atomic type](atomic "c/language/atomic")
+ a name earlier introduced by a [typedef](typedef "c/language/typedef") declaration
+ [`struct`](struct "c/language/struct"), [`union`](union "c/language/union"), or [`enum`](enum "c/language/enum") specifier
* zero or one storage-class specifiers: [`typedef`](typedef "c/language/typedef"), [`auto`, `register`, `static`, `extern`, `_Thread_local`](storage_duration "c/language/storage duration")
* zero or more type qualifiers: [`const`](const "c/language/const"), [`volatile`](volatile "c/language/volatile"), [`restrict`](restrict "c/language/restrict"), [`_Atomic`](atomic "c/language/atomic")
* (only when declaring functions), zero or more function specifiers: [`inline`](inline "c/language/inline"), [`_Noreturn`](_noreturn "c/language/ Noreturn")
* zero or more alignment specifiers: [`_Alignas`](_alignas "c/language/ Alignas")
|
| declarators-and-initializers | - | comma-separated list of declarators (each declarator provides additional type information and/or the identifier to declare). Declarators may be accompanied by [initializers](initialization "c/language/initialization"). The [enum](enum "c/language/enum"), [struct](struct "c/language/struct"), and [union](union "c/language/union") declarations may omit declarators, in which case they only introduce the enumeration constants and/or tags. |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the declared entities, or forms an attribute declaration if appears alone. |
1-2) Simple declaration. Introduces one or more identifiers which denotes objects, functions, struct/union/enum tags, typedefs, or enumeration constants.
3) Attribute declaration. Does not declares any identifier, and has implementation-defined meaning if the meaning is not specified by the standard. For example,
```
int a, *b=NULL; // "int" is the type specifier,
// "a" is a declarator
// "*b" is a declarator and NULL is its initializer
const int *f(void); // "int" is the type specifier
// "const" is the type qualifier
// "*f(void)" is the declarator
enum COLOR {RED, GREEN, BLUE} c; // "enum COLOR {RED, GREEN, BLUE}" is the type specifier
// "c" is the declarator
```
The type of each identifier introduced in a declaration is determined by a combination of the type specified by the type specifier and the type modifications applied by its declarator.
[Attributes](attributes "c/language/attributes")(since C23) may appear in specifiers-and-qualifiers, in which case they apply to the type determined by the preceding specifiers.
### Declarators
Each declarator is one of the following:
| | | |
| --- | --- | --- |
| identifier attr-spec-seq(optional) | (1) | |
| `(` declarator `)` | (2) | |
| `*` attr-spec-seq(optional) qualifiers(optional) declarator | (3) | |
| noptr-declarator `[` `static`(optional) qualifiers(optional) expression `]` noptr-declarator `[` qualifiers(optional) `*` `]` | (4) | |
| noptr-declarator `(` parameters-or-identifiers `)` | (5) | |
1) the identifier that this declarator introduces.
2) any declarator may be enclosed in parentheses; this is required to introduce pointers to arrays and pointers to functions.
3) [pointer declarator](pointer "c/language/pointer"): the declaration `S * cvr D`; declares `D` as a cvr-qualified pointer to the type determined by `S`.
4) [array declarator](array "c/language/array"): the declaration `S D[N]` declares `D` as an array of `N` objects of the type determined by `S`. noptr-declarator is any other declarator except unparenthesized pointer declarator.
5) [function declarator](function_declaration "c/language/function declaration"): the declaration `S D(params)` declared `D` as a function taking the parameters `params` and returning `S`. noptr-declarator is any other declarator except unparenthesized pointer declarator. The reasoning behind this syntax is that when the identifier declared by the declarator appears in an expression of the same form as the declarator, it would have the type specified by the type specifier sequence.
```
struct C {
int member; // "int" is the type specifier
// "member" is the declarator
} obj, *pObj = &obj;
// "struct C { int member; }" is the type specifier
// declarator "obj" defines an object of type struct C
// declarator "*pObj" declares a pointer to C,
// initializer "= &obj" provides the initial value for that pointer
int a = 1, *p = NULL, f(void), (*pf)(double);
// the type specifier is "int"
// declarator "a" defines an object of type int
// initializer "=1" provides its initial value
// declarator "*p" defines an object of type pointer to int
// initializer "=NULL" provides its initial value
// declarator "f(void)" declares a function taking void and returning int
// declarator "(*pf)(double)" defines an object of type pointer
// to function taking double and returning int
int (*(*foo)(double))[3] = NULL;
// the type specifier is int
// 1. declarator "(*(*foo)(double))[3]" is an array declarator:
// the type declared is "/nested declarator/ array of 3 int"
// 2. the nested declarator is "*(*foo)(double))", which is a pointer declarator
// the type declared is "/nested declarator/ pointer to array of 3 int"
// 3. the nested declarator is "(*foo)(double)", which is a function declarator
// the type declared is "/nested declarator/ function taking double and returning
// pointer to array of 3 int"
// 4. the nested declarator is "(*foo)" which is a (parenthesized, as required by
// function declarator syntax) pointer declarator.
// the type declared is "/nested declarator/ pointer to function taking double
// and returning pointer to array of 3 int"
// 5. the nested declarator is "foo", which is an identifier.
// The declaration introduces the identifier "foo" to refer to an object of type
// "pointer to function taking double and returning pointer to array of 3 int"
// The initializer "= NULL" provides the initial value of this pointer.
// If "foo" is used in an expression of the form of the declarator, its type would be
// int.
int x = (*(*foo)(1.2))[0];
```
The end of every declarator that is not part of another declarator is a [sequence point](eval_order "c/language/eval order").
In all cases, attr-spec-seq is an optional sequence of [attributes](attributes "c/language/attributes")(since C23). When appearing immediately after the identifier, it applies to the object or function being declared.
### Definitions
A *definition* is a declaration that provides all information about the identifiers it declares.
Every declaration of an [enum](enum "c/language/enum") or a [typedef](typedef "c/language/typedef") is a definition.
For functions, a declaration that includes the function body is a [function definition](function_definition "c/language/function definition"):
```
int foo(double); // declaration
int foo(double x){ return x; } // definition
```
For objects, a declaration that allocates storage ([automatic or static](storage_duration "c/language/storage duration"), but not extern) is a definition, while a declaration that does not allocate storage ([external declaration](extern "c/language/extern")) is not.
```
extern int n; // declaration
int n = 10; // definition
```
For [structs](struct "c/language/struct") and [unions](union "c/language/union"), declarations that specify the list of members are definitions:
```
struct X; // declaration
struct X { int n; }; // definition
```
### Redeclaration
A declaration cannot introduce an identifier if another declaration for the same identifier in the same [scope](scope "c/language/scope") appears earlier, except that.
* Declarations of objects [with linkage](storage_duration "c/language/storage duration") (external or internal) can be repeated:
```
extern int x;
int x = 10; // OK
extern int x; // OK
static int n;
static int n = 10; // OK
static int n; // OK
```
* Non-VLA [typedef](typedef "c/language/typedef") can be repeated as long as it names the same type:
```
typedef int int_t;
typedef int int_t; // OK
```
* [struct](struct "c/language/struct") and [union](union "c/language/union") declarations can be repeated:
```
struct X;
struct X { int n; };
struct X;
```
These rules simplify the use of header files.
### Notes
| | |
| --- | --- |
| In C89, declarations within any [compound statement](statements#Compound_statements "c/language/statements") (block scope) must appear in the beginning of the block, before any [statements](statements "c/language/statements").
Also, in C89, functions returning `int` may be implicitly declared by the [function call operator](operator_other#Function_call "c/language/operator other") and function parameters of type `int` do not have to be declared when using old-style [function definitions](function_definition "c/language/function definition"). | (until C99) |
Empty declarators are prohibited; a simple declaration must have at least one declarator or declare at least one struct/union/enum tag, or introduce at least one enumeration constant.
| | |
| --- | --- |
| If any part of a declarator is a [variable-length array](array "c/language/array") (VLA) declarator, the entire declarator's type is known as "variably-modified type". Types defined from variably-modified types are also variably modified (VM).
Declarations of any variably-modified types may appear only at [block scope](scope "c/language/scope") or function prototype scope and cannot be members of structs or unions. Although VLA can only have automatic or allocated [storage duration](storage_duration "c/language/storage duration"), a VM type such as a pointer to a VLA may be static. There are other restrictions on the use of VM types, see [goto](goto "c/language/goto"), [switch](switch "c/language/switch"). `[longjmp](../program/longjmp "c/program/longjmp")`. | (since C99) |
| | |
| --- | --- |
| [static\_asserts](_static_assert "c/language/ Static assert") are considered to be declarations from the point of view of the C grammar (so that they may appear anywhere a declaration may appear), but they do not introduce any identifiers and do not follow the declaration syntax. | (since C11) |
| | |
| --- | --- |
| [Attribute](attributes "c/language/attributes") declarations are also considered to be declarations (so that they may appear anywhere a declaration may appear), but they do not introduce any identifiers. A single `;` without attr-spec-seq is not an attribute declaration, but a statement. | (since C23) |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7 Declarations (p: 78-105)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7 Declarations (p: 108-145)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7 Declarations (p: 97-130)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.5 Declarations
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/declarations "cpp/language/declarations") for Declarations |
c C Operator Precedence C Operator Precedence
=====================
The following table lists the precedence and associativity of C operators. Operators are listed top to bottom, in descending precedence.
| Precedence | Operator | Description | Associativity |
| --- | --- | --- | --- |
| 1 | `++` `--` | Suffix/postfix increment and decrement | Left-to-right |
| `()` | Function call |
| `[]` | Array subscripting |
| `.` | Structure and union member access |
| `->` | Structure and union member access through pointer |
| `(*type*){*list*}` | Compound literal(C99) |
| 2 | `++` `--` | Prefix increment and decrement[[note 1]](#cite_note-1) | Right-to-left |
| `+` `-` | Unary plus and minus |
| `!` `~` | Logical NOT and bitwise NOT |
| `(*type*)` | Cast |
| `*` | Indirection (dereference) |
| `&` | Address-of |
| `sizeof` | Size-of[[note 2]](#cite_note-2) |
| `_Alignof` | Alignment requirement(C11) |
| 3 | `*` `/` `%` | Multiplication, division, and remainder | Left-to-right |
| 4 | `+` `-` | Addition and subtraction |
| 5 | `<<` `>>` | Bitwise left shift and right shift |
| 6 | `<` `<=` | For relational operators < and ≤ respectively |
| `>` `>=` | For relational operators > and ≥ respectively |
| 7 | `==` `!=` | For relational = and ≠ respectively |
| 8 | `&` | Bitwise AND |
| 9 | `^` | Bitwise XOR (exclusive or) |
| 10 | `|` | Bitwise OR (inclusive or) |
| 11 | `&&` | Logical AND |
| 12 | `||` | Logical OR |
| 13 | `?:` | Ternary conditional[[note 3]](#cite_note-3) | Right-to-left |
| 14[[note 4]](#cite_note-4) | `=` | Simple assignment |
| `+=` `-=` | Assignment by sum and difference |
| `*=` `/=` `%=` | Assignment by product, quotient, and remainder |
| `<<=` `>>=` | Assignment by bitwise left shift and right shift |
| `&=` `^=` `|=` | Assignment by bitwise AND, XOR, and OR |
| 15 | `,` | Comma | Left-to-right |
1. The operand of prefix `++` and `--` can't be a type cast. This rule grammatically forbids some expressions that would be semantically invalid anyway. Some compilers ignore this rule and detect the invalidity semantically.
2. The operand of `sizeof` can't be a type cast: the expression `sizeof (int) * p` is unambiguously interpreted as `(sizeof(int)) * p`, but not `sizeof((int)*p)`.
3. The expression in the middle of the conditional operator (between `?` and `:`) is parsed as if parenthesized: its precedence relative to `?:` is ignored.
4. Assignment operators' left operands must be unary (level-2 non-cast) expressions. This rule grammatically forbids some expressions that would be semantically invalid anyway. Many compilers ignore this rule and detect the invalidity semantically. For example, `e = a < d ? a++ : a = d` is an expression that cannot be parsed because of this rule. However, many compilers ignore this rule and parse it as `e = ( ((a < d) ? (a++) : a) = d )`, and then give an error because it is semantically invalid.
When parsing an expression, an operator which is listed on some row will be bound tighter (as if by parentheses) to its arguments than any operator that is listed on a row further below it. For example, the expression `*p++` is parsed as `*(p++)`, and not as `(*p)++`.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same precedence, in the given direction. For example, the expression `a=b=c` is parsed as `a=(b=c)`, and not as `(a=b)=c` because of right-to-left associativity.
### Notes
Precedence and associativity are independent from [order of evaluation](eval_order "c/language/eval order").
The standard itself doesn't specify precedence levels. They are derived from the grammar.
In C++, the conditional operator has the same precedence as assignment operators, and prefix `++` and `--` and assignment operators don't have the restrictions about their operands.
Associativity specification is redundant for unary operators and is only shown for completeness: unary prefix operators always associate right-to-left (`sizeof ++*p` is `sizeof(++(*p))`) and unary postfix operators always associate left-to-right (`a[1][2]++` is `((a[1])[2])++`). Note that the associativity is meaningful for member access operators, even though they are grouped with unary postfix operators: `a.b++` is parsed `(a.b)++` and not `a.(b++)`.
### References
* C17 standard (ISO/IEC 9899:2018):
+ A.2.1 Expressions
* C11 standard (ISO/IEC 9899:2011):
+ A.2.1 Expressions
* C99 standard (ISO/IEC 9899:1999):
+ A.2.1 Expressions
* C89/C90 standard (ISO/IEC 9899:1990):
+ A.1.2.1 Expressions
### See also
[Order of evaluation](eval_order "c/language/eval order") of operator arguments at run time.
| Common operators |
| --- |
| [assignment](operator_assignment "c/language/operator assignment") | [incrementdecrement](operator_incdec "c/language/operator incdec") | [arithmetic](operator_arithmetic "c/language/operator arithmetic") | [logical](operator_logical "c/language/operator logical") | [comparison](operator_comparison "c/language/operator comparison") | [memberaccess](operator_member_access "c/language/operator member access") | [other](operator_other "c/language/operator other") |
| `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b`. | `a[b] *a &a a->b a.b`. | `a(...) a, b (type) a ? : sizeof _Alignof` (since C11). |
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_precedence "cpp/language/operator precedence") for C++ operator precedence |
| programming_docs |
c Main function Main function
=============
Every C program coded to run in a hosted execution environment contains the definition (not the prototype) of a function named `main`, which is the designated start of the program.
| | | |
| --- | --- | --- |
| `int` `main` `(void)` `{` body `}` | (1) | |
| `int` `main` `(``int` argc`,` `char` `*`argv`[]``)` `{` body `}` | (2) | |
| `/* another implementation-defined signature */` (since C99) | (3) | |
### Parameters
| | | |
| --- | --- | --- |
| argc | - | Non-negative value representing the number of arguments passed to the program from the environment in which the program is run. |
| argv | - | Pointer to the first element of an array of `argc + 1` pointers, of which the last one is null and the previous ones, if any, point to strings that represent the arguments passed to the program from the host environment. If `argv[0]` is not a null pointer (or, equivalently, if `argc` > 0), it points to a string that represents the program name, which is empty if the program name is not available from the host environment. |
The names `argc` and `argv` stand for "argument count" and "argument vector", and are traditionally used, but other names may be chosen for the parameters, as well as different but equivalent declarations of their type: `int main(int ac, char** av)` is equally valid.
A common implementation-defined form of main is `int main(int argc, char *argv[], char *envp[])`, where a third argument, of type `char**`, pointing at [an array of pointers to the *execution environment variables*](https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html), is added.
### Return value
If the return statement is used, the return value is used as the argument to the implicit call to `[exit()](../program/exit "c/program/exit")` (see below for details). The values zero and `[EXIT\_SUCCESS](../program/exit_status "c/program/EXIT status")` indicate successful termination, the value `[EXIT\_FAILURE](../program/exit_status "c/program/EXIT status")` indicates unsuccessful termination.
### Explanation
The `main` function is called at program startup, after all objects with static storage duration are initialized. It is the designated entry point to a program that is executed in a *hosted* environment (that is, with an operating system). The name and type of the entry point to any *freestanding* program (boot loaders, OS kernels, etc) are implementation-defined.
The parameters of the two-parameter form of the main function allow arbitrary multibyte character strings to be passed from the execution environment (these are typically known as *command line arguments*). The pointers `argv[1] .. argv[argc-1]` point at the first characters in each of these strings. `argv[0]` (if non-null) is the pointer to the initial character of a null-terminated multibyte strings that represents the name used to invoke the program itself (or, if this is not supported by the host environment, argv[0][0] is guaranteed to be zero).
If the host environment cannot supply both lowercase and uppercase letters, the command line arguments are converted to lowercase.
The strings are modifiable, and any modifications made persist until program termination, although these modifications do not propagate back to the host environment: they can be used, for example, with `[strtok](../string/byte/strtok "c/string/byte/strtok")`.
The size of the array pointed to by `argv` is at least `argc+1`, and the last element, `argv[argc]`, is guaranteed to be a null pointer.
The `main` function has several special properties:
1) A prototype for this function cannot be supplied by the program.
2) If the return type of the main function is [compatible](type#Compatible_types "c/language/type") with `int`, then the return from the initial call to main (but not the return from any subsequent, recursive, call) is equivalent to executing the `[exit](../program/exit "c/program/exit")` function, with the value that the main function is returning passed as the argument (which then calls the functions registered with `[atexit](../program/atexit "c/program/atexit")`, flushes and closes all streams, and deletes the files created with `[tmpfile](../io/tmpfile "c/io/tmpfile")`, and returns control to the execution environment).
3)
| | |
| --- | --- |
| If the main function executes a `return` that specifies no value or, which is the same, reaches the terminating `}` without executing a `return`, the termination status returned to the host environment is undefined. | (until C99) |
| If the return type of the main function is not [compatible](type#Compatible_types "c/language/type") with `int` (e.g. `void main(void)`), the value returned to the host environment is unspecified. If the return type is compatible with `int` and control reaches the terminating `}`, the value returned to the environment is the same as if executing `return 0;`. | (since C99) |
### Example
Demonstrates how to inform a program about where to find its input and where to write its results. Invocation: ./a.out indatafile outdatafile.
```
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("argc = %d\n", argc);
for(int ndx = 0; ndx != argc; ++ndx)
printf("argv[%d] --> %s\n", ndx, argv[ndx]);
printf("argv[argc] = %p\n", (void*)argv[argc]);
}
```
Possible output:
```
argc = 3
argv[0] --> ./a.out
argv[1] --> indatafile
argv[2] --> outdatafile
argv[argc] = (nil)
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 5.1.2.2.1 Program startup (p: 10-11)
* C11 standard (ISO/IEC 9899:2011):
+ 5.1.2.2.1 Program startup (p: 13)
* C99 standard (ISO/IEC 9899:1999):
+ 5.1.2.2.1 Program startup (p: 12)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 5.1.2.2 Hosted environment
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/main_function "cpp/language/main function") for `main` function |
c Character constant Character constant
==================
### Syntax
| | | |
| --- | --- | --- |
| `'`c-char `'` | (1) | |
| `u8'`c-char `'` | (2) | (since C23) |
| `u'`c-char `'` | (3) | (since C11) |
| `U'`c-char `'` | (4) | (since C11) |
| `L'`c-char `'` | (5) | |
| `'`c-char-sequence `'` | (6) | |
| `L'`c-char-sequence `'` | (7) | |
| `u'`c-char-sequence `'` | (8) | (since C11)(removed in C23) |
| `U'`c-char-sequence `'` | (9) | (since C11)(removed in C23) |
where.
* c-char is either
+ a character from the basic source character set minus single-quote (`'`), backslash (`\`), or the newline character.
+ escape sequence: one of special character escapes `\'` `\"` `\?` `\\` `\a` `\b` `\f` `\n` `\r` `\t` `\v`, hex escapes `\x...` or octal escapes `\...` as defined in [escape sequences](escape "c/language/escape").
| | |
| --- | --- |
| * universal character name, `\u...` or `\U...` as defined in [escape sequences](escape "c/language/escape").
| (since C99) |
* c-char-sequence is a sequence of two or more c-chars.
1) single-byte integer character constant, e.g. `'a'` or `'\n'` or `'\13'`. Such constant has type `int` and a value equal to the representation of c-char in the execution character set as a value of type `char` mapped to `int`. If c-char is not representable as a single byte in the execution character set, the value is implementation-defined.
2) UTF-8 character constant, e.g. `u8'a'`. Such constant has type `unsigned char` and the value equal to ISO 10646 code point value of c-char, provided that the code point value is representable with a single UTF-8 code unit (that is, c-char is in the range 0x0-0x7F, inclusive). If c-char is not representable with a single UTF-8 code unit, the program is ill-formed.
| | |
| --- | --- |
| 3) 16-bit wide character constant, e.g. `u'貓'`, but not `u'🍌'` (`u'\U0001f34c'`). Such constant has type `char16_t` and a value equal to the value of c-char in the 16-bit encoding produced by `[mbrtoc16](../string/multibyte/mbrtoc16 "c/string/multibyte/mbrtoc16")` (normally UTF-16). If c-char is not representable or maps to more than one 16-bit character, the value is implementation-defined. 4) 32-bit wide character constant, e.g. `U'貓'` or `U'🍌'`. Such constant has type `char32_t` and a value equal to the value of c-char in in the 32-bit encoding produced by `[mbrtoc32](../string/multibyte/mbrtoc32 "c/string/multibyte/mbrtoc32")` (normally UTF-32). If c-char is not representable or maps to more than one 32-bit character, the value is implementation-defined. | (until C23) |
| 3) UTF-16 character constant, e.g. `u'貓'`, but not `u'🍌'` (`u'\U0001f34c'`). Such constant has type `char16_t` and the value equal to ISO 10646 code point value of c-char, provided that the code point value is representable with a single UTF-16 code unit (that is, c-char is in the range 0x0-0xD7FF or 0xE000-0xFFFF, inclusive). If c-char is not representable with a single UTF-16 code unit, the program is ill-formed. 4) UTF-32 character constant, e.g. `U'貓'` or `U'🍌'`. Such constant has type `char32_t` and the value equal to ISO 10646 code point value of c-char, provided that the code point value is representable with a single UTF-32 code unit (that is, c-char is in the range 0x0-0xD7FF or 0xE000-0x10FFFF, inclusive). If c-char is not representable with a single UTF-32 code unit, the program is ill-formed. | (since C23) |
5) wide character constant, e.g. `L'β'` or `L'貓`. Such constant has type `wchar_t` and a value equal to the value of c-char in the execution wide character set (that is, the value that would be produced by `[mbtowc](../string/multibyte/mbtowc "c/string/multibyte/mbtowc")`). If c-char is not representable or maps to more than one wide character (e.g. a non-BMP value on Windows where `wchar_t` is 16-bit), the value is implementation-defined .
6) multicharacter constant, e.g. `'AB'`, has type `int` and implementation-defined value.
7) wide multicharacter constant, e.g. `L'AB'`, has type `wchar_t` and implementation-defined value.
8) 16-bit multicharacter constant, e.g. `u'CD'`, has type `char16_t` and implementation-defined value.
9) 32-bit multicharacter constant, e.g. `U'XY'`, has type `char32_t` and implementation-defined value. ### Notes
Multicharacter constants were inherited by C from the B programming language. Although not specified by the C standard, most compilers (MSVC is a notable exception) implement multicharacter constants as specified in B: the values of each char in the constant initialize successive bytes of the resulting integer, in big-endian zero-padded right-adjusted order, e.g. the value of `'\1'` is `0x00000001` and the value of `'\1\2\3\4'` is `0x01020304`.
In C++, encodable ordinary character literals have type `char`, rather than `int`.
Unlike [integer constants](integer_constant "c/language/integer constant"), a character constant may have a negative value if `char` is signed: on such implementations `'\xFF'` is an `int` with the value `-1`.
When used in a controlling expression of [`#if`](../preprocessor/conditional "c/preprocessor/conditional") or [`#elif`](../preprocessor/conditional "c/preprocessor/conditional"), character constants may be interpreted in terms of the source character set, the execution character set, or some other implementation-defined character set.
16/32-bit multicharacter constants are not widely supported and removed in C23. Some common implementations (e.g. clang) do not accept them at all.
### Example
```
#include <stddef.h>
#include <stdio.h>
#include <uchar.h>
int main (void)
{
printf("constant value \n");
printf("-------- ----------\n");
// integer character constants,
int c1='a'; printf("'a':\t %#010x\n", c1);
int c2='🍌'; printf("'🍌':\t %#010x\n\n", c2); // implementation-defined
// multicharacter constant
int c3='ab'; printf("'ab':\t %#010x\n\n", c3); // implementation-defined
// 16-bit wide character constants
char16_t uc1 = u'a'; printf("'a':\t %#010x\n", (int)uc1);
char16_t uc2 = u'¢'; printf("'¢':\t %#010x\n", (int)uc2);
char16_t uc3 = u'猫'; printf("'猫':\t %#010x\n", (int)uc3);
// implementation-defined (🍌 maps to two 16-bit characters)
char16_t uc4 = u'🍌'; printf("'🍌':\t %#010x\n\n", (int)uc4);
// 32-bit wide character constants
char32_t Uc1 = U'a'; printf("'a':\t %#010x\n", (int)Uc1);
char32_t Uc2 = U'¢'; printf("'¢':\t %#010x\n", (int)Uc2);
char32_t Uc3 = U'猫'; printf("'猫':\t %#010x\n", (int)Uc3);
char32_t Uc4 = U'🍌'; printf("'🍌':\t %#010x\n\n", (int)Uc4);
// wide character constants
wchar_t wc1 = L'a'; printf("'a':\t %#010x\n", (int)wc1);
wchar_t wc2 = L'¢'; printf("'¢':\t %#010x\n", (int)wc2);
wchar_t wc3 = L'猫'; printf("'猫':\t %#010x\n", (int)wc3);
wchar_t wc4 = L'🍌'; printf("'🍌':\t %#010x\n\n", (int)wc4);
}
```
Possible output:
```
constant value
-------- ----------
'a': 0x00000061
'🍌': 0xf09f8d8c
'ab': 0x00006162
'a': 0x00000061
'¢': 0x000000a2
'猫': 0x0000732b
'🍌': 0x0000df4c
'a': 0x00000061
'¢': 0x000000a2
'猫': 0x0000732b
'🍌': 0x0001f34c
'a': 0x00000061
'¢': 0x000000a2
'猫': 0x0000732b
'🍌': 0x0001f34c
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.4.4.4 Character constants (p: 48-50)
* C11 standard (ISO/IEC 9899:2011):
+ 6.4.4.4 Character constants (p: 67-70)
* C99 standard (ISO/IEC 9899:1999):
+ 6.4.4.4 Character constants (p: 59-61)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.3.4 Character constants
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/character_literal "cpp/language/character literal") for Character literal |
c Character sets Character sets
==============
### Basic source character set
The *basic source character set* consists of 95 characters:
* the space character,
* the control characters representing
+ horizontal tab,
+ vertical tab,
+ and form feed,
* plus the following 91 graphical characters:
| | | | | | | | | | | | | | | | | | | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `a` | `b` | `c` | `d` | `e` | `f` | `g` | `h` | `i` | `j` | `k` | `l` | `m` | `n` | `o` | `p` | `q` | `r` | `s` | `t` | `u` | `v` | `w` | `x` | `y` | `z` |
| `A` | `B` | `C` | `D` | `E` | `F` | `G` | `H` | `I` | `J` | `K` | `L` | `M` | `N` | `O` | `P` | `Q` | `R` | `S` | `T` | `U` | `V` | `W` | `X` | `Y` | `Z` |
| `0` | `1` | `2` | `3` | `4` | `5` | `6` | `7` | `8` | `9` |
| `_` | `{` |
} | `[` | `]` | `#` | `(` | `)` | `<` | `>` | `%` | `:` | `;` | `.` | `?` | `*` | `+` | `-` | `/` | `^` | `&` | `|` | `~` | `!` | `=` | `,` | `\` | `"` | `’` |
Unlike C++, the control character representing new line is not included in basic source character set. Instead, there shall be some way of indicating the end of each line of text in the source file and the document treats such an end-of-line indicator as if it were a single new-line character.
### Basic execution character set
The *basic execution character set* and the *basic execution wide-character set* shall each contain all the members of the basic source character set, plus control characters representing alert, backspace, and carriage return, and new line, plus a null character (respectively, null wide character), whose value is 0.
For each basic execution character set, the values of the members shall be non-negative and distinct from one another. In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
The representation of each member of the source and execution basic character sets shall fit in a byte.
### See also
| |
| --- |
| [ASCII chart](ascii "c/language/ascii") |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/charset "cpp/language/charset") for Character sets and encodings |
c Struct and union initialization Struct and union initialization
===============================
When [initializing](initialization "c/language/initialization") an object of [struct](struct "c/language/struct") or [union](union "c/language/union") type, the initializer must be a non-empty, (until C23) brace-enclosed, comma-separated list of initializers for the members:
| | | |
| --- | --- | --- |
| `=` `{` expression `,` `...` `}` | (1) | |
| `=` `{` designator expression `,` `...` `}` | (2) | (since C99) |
| `=` `{` `}` | (3) | (since C23) |
where the designator is a sequence (whitespace-separated or adjacent) of individual member designators of the form `.` member and [array designators](array_initialization "c/language/array initialization") of the form `[` index `]`.
All members that are not initialized explicitly are [empty-initialized](initialization#Empty_initialization "c/language/initialization").
### Explanation
When initializing a [union](union "c/language/union"), the initializer list must have only one member, which initializes the first member of the union unless a designated initializer is used (since C99).
```
union { int x; char c[4]; }
u = {1}, // makes u.x active with value 1
u2 = { .c={'\1'} }; // makes u2.c active with value {'\1','\0','\0','\0'}
```
When initializing a [struct](struct "c/language/struct"), the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99)initialize the struct members declared after the one initialized by the previous expression.
```
struct point {double x,y,z;} p = {1.2, 1.3}; // p.x=1.2, p.y=1.3, p.z=0.0
div_t answer = {.quot = 2, .rem = -1 }; // order of elements in div_t may vary
```
| | |
| --- | --- |
| A designator causes the following initializer to initialize the struct member described by the designator. Initialization then continues forward in order of declaration, beginning with the next element declared after the one described by the designator.
```
struct {int sec,min,hour,day,mon,year;} z
= {.day=31,12,2014,.sec=30,15,17}; // initializes z to {30,15,17,31,12,2014}
```
| (since C99) |
It's an error to provide more initializers than members.
### Nested initialization
If the members of the struct or union are arrays, structs, or unions, the corresponding initializers in the brace-enclosed list of initializers are any initializers that are valid for those members, except that their braces may be omitted as follows:
If the nested initializer begins with an opening brace, the entire nested initializer up to its closing brace initializes the corresponding member object. Each left opening brace establishes a new *current object*. The members of the current object are initialized in their natural order, unless designators are used (since C99): array elements in subscript order, struct members in declaration order, only the first declared member of any union. The subobjects within the current object that are not explicitly initialized by the closing brace are [empty-initialized](initialization#Empty_initialization "c/language/initialization").
```
struct example {
struct addr_t {
uint32_t port;
} addr;
union {
uint8_t a8[4];
uint16_t a16[2];
} in_u;
};
struct example ex = { // start of initializer list for struct example
{ // start of initializer list for ex.addr
80 // initialized struct's only member
}, // end of initializer list for ex.addr
{ // start of initializer-list for ex.in_u
{127,0,0,1} // initializes first element of the union
} };
```
If the nested initializer does not begin with an opening brace, only enough initializers from the list are taken to account for the elements or members of the member array, struct or union; any remaining initializers are left to initialize the next struct member:
```
struct example ex = {80, 127, 0, 0, 1}; // 80 initializes ex.addr.port
// 127 initializes ex.in_u.a8[0]
// 0 initializes ex.in_u.a8[1]
// 0 initializes ex.in_u.a8[2]
// 1 initializes ex.in_u.a8[3]
```
| | |
| --- | --- |
| When designators are nested, the designators for the members follow the designators for the enclosing structs/unions/arrays. Within any nested bracketed initializer list, the outermost designator refers to the *current object* and selects the subobject to be initialized within the *current object* only.
```
struct example ex2 = { // current object is ex2, designators are for members of example
.in_u.a8[0]=127, 0, 0, 1, .addr=80};
struct example ex3 = {80, .in_u={ // changes current object to the union ex.in_u
127,
.a8[2]=1 // this designator refers to the member of in_u
} };
```
If any subobject is explicitly initialized twice (which may happen when designators are used), the initializer that appears later in the list is the one used (the earlier initializer may not be evaluated):
```
struct {int n;} s = {printf("a\n"), // this may be printed or skipped
.n=printf("b\n")}; // always printed
```
Although any non-initialized subobjects are initialized implicitly, implicit initialization of a subobject never overrides explicit initialization of the same subobject if it appeared earlier in the initializer list (choose clang to observe the correct output):
```
#include <stdio.h>
typedef struct { int k; int l; int a[2]; } T;
typedef struct { int i; T t; } S;
T x = {.l = 43, .k = 42, .a[1] = 19, .a[0] = 18 };
// x initialized to {42, 43, {18, 19} }
int main(void)
{
S l = { 1, // initializes l.i to 1
.t = x, // initializes l.t to {42, 43, {18, 19} }
.t.l = 41, // changes l.t to {42, 41, {18, 19} }
.t.a[1] = 17 // changes l.t to {42, 41, {18, 17} }
};
printf("l.t.k is %d\n", l.t.k); // .t = x sets l.t.k to 42 explicitly
// .t.l = 41 would zero out l.t.k implicitly
}
```
Output:
```
l.t.k is 42
```
However, when an initializer begins with a left open brace, its *current object* is fully re-initialized and any prior explicit initializers for any of its subobjects are ignored:
```
struct fred { char s[4]; int n; };
struct fred x[ ] = { { { "abc" }, 1 }, // inits x[0] to { {'a','b','c','\0'}, 1 }
[0].s[0] = 'q' // changes x[0] to { {'q','b','c','\0'}, 1 }
};
struct fred y[ ] = { { { "abc" }, 1 }, // inits y[0] to { {'a','b','c','\0'}, 1 }
[0] = { // current object is now the entire y[0] object
.s[0] = 'q'
} // replaces y[0] with { {'q','\0','\0','\0'}, 0 }
};
```
| (since C99) |
### Notes
The initializer list may have a trailing comma, which is ignored.
```
struct {double x,y;} p = {1.0,
2.0, // trailing comma OK
};
```
| | |
| --- | --- |
| In C, the braced list of initializers cannot be empty (note that C++ allows empty lists, and also note that a [struct](struct "c/language/struct") in C cannot be empty): | (until C23) |
| The initializer list can be empty in C as in C++: | (since C23) |
```
struct {int n;} s = {0}; // OK
struct {int n;} s = {}; // Error until C23: initializer-list cannot be empty
// OK since C23: s.n is initialized to 0
struct {} s = {}; // Error: struct cannot be empty
```
| | |
| --- | --- |
| Every expression in the initializer list must be a [constant expression](constant_expression "c/language/constant expression") when initializing aggregates of any storage duration. | (until C99) |
| As with all other [initialization](initialization "c/language/initialization"), every expression in the initializer list must be a [constant expression](constant_expression "c/language/constant expression") when initializing aggregates of static or thread-local (since C11) [storage duration](storage_duration "c/language/storage duration"):
```
static struct {char* p} s = {malloc(1)}; // error
```
The [order of evaluation](eval_order "c/language/eval order") of the subexpressions in any initializer is indeterminately sequenced (but not in C++ since C++11):
```
int n = 1;
struct {int x,y;} p = {n++, n++}; // unspecified, but well-defined behavior:
// n is incremented twice in arbitrary order
// p equal {1,2} and {2,1} are both valid
```
| (since C99) |
### Example
```
#include <stdio.h>
#include <time.h>
int main(void)
{
char buff[70];
// designated initializers simplify the use of structs whose
// order of members is unspecified
struct tm my_time = { .tm_year=2012-1900, .tm_mon=9, .tm_mday=9,
.tm_hour=8, .tm_min=10, .tm_sec=20 };
strftime(buff, sizeof buff, "%A %c", &my_time);
puts(buff);
}
```
Possible output:
```
Sunday Sun Oct 9 08:10:20 2012
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.9/12-39 Initialization (p: 101-105)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.9/12-38 Initialization (p: 140-144)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.8/12-38 Initialization (p: 126-130)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 6.5.7 Initialization
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/aggregate_initialization "cpp/language/aggregate initialization") for Aggregate initialization |
| programming_docs |
c Phases of translation Phases of translation
=====================
The C source file is processed by the compiler *as if* the following phases take place, in this exact order. Actual implementation may combine these actions or process them differently as long as the behavior is the same.
### Phase 1
1) The individual bytes of the source code file (which is generally a text file in some multibyte encoding such as UTF-8) are mapped, in implementation defined manner, to the characters of the *source character set*. In particular, OS-dependent end-of-line indicators are replaced by newline characters. The *source character set* is a multibyte character set which includes the *basic source character set* as a single-byte subset, consisting of the following 96 characters:
a) 5 whitespace characters (space, horizontal tab, vertical tab, form feed, new-line)
b) 10 digit characters from `'0'` to `'9'`
c) 52 letters from `'a'` to `'z'` and from `'A'` to `'Z'`
d) 29 punctuation characters: `_ { } [ ] # ( ) < > % : ; . ? * + - / ^ & | ~ ! = , \ " '`
2) [Trigraph sequences](operator_alternative "c/language/operator alternative") are replaced by corresponding single-character representations. ### Phase 2
1) Whenever backslash appears at the end of a line (immediately followed by the newline character), both backslash and newline are deleted, combining two physical source lines into one logical source line. This is a single-pass operation: a line ending in two backslashes followed by an empty line does not combine three lines into one.
2) If a non-empty source file does not end with a newline character after this step (whether it had no newline originally, or it ended with a backslash), the behavior is undefined. ### Phase 3
1) The source file is decomposed into [comments](../comment "c/comment"), sequences of whitespace characters (space, horizontal tab, new-line, vertical tab, and form-feed), and *preprocessing tokens*, which are the following
a) header names: `<stdio.h>` or `"myfile.h"`
b) [identifiers](identifier "c/language/identifier")
c) preprocessing numbers, which cover [integer constants](integer_constant "c/language/integer constant") and [floating constants](floating_constant "c/language/floating constant"), but also cover some invalid tokens such as `1..E+3.foo` or `0JBK`
d) [character constants](character_constant "c/language/character constant") and [string literals](string_literal "c/language/string literal")
e) operators and punctuators, such as `+`, `<<=`, `<%`, or `##`.
f) individual non-whitespace characters that do not fit in any other category
2) Each comment is replaced by one space character
3) Newlines are kept, and it's implementation-defined whether non-newline whitespace sequences may be collapsed into single space characters. If the input has been parsed into preprocessing tokens up to a given character, the next preprocessing token is generally taken to be the longest sequence of characters that could constitute a preprocessing token, even if that would cause subsequent analysis to fail. This is commonly known as *maximal munch*.
```
int foo = 1;
int bar = 0xE+foo; // error: invalid preprocessing number 0xE+foo
int baz = 0xE + foo; // OK
int pub = bar+++baz; // OK: bar++ + baz
int ham = bar++-++baz; // OK: bar++ - ++baz
int qux = bar+++++baz; // error: bar++ ++ +baz, not bar++ + ++baz.
```
The sole exception to the maximal munch rule is:
* Header name preprocessing tokens are only formed within a `#include` directive and in implementation-defined locations within a `#pragma` directive.
```
#define MACRO_1 1
#define MACRO_2 2
#define MACRO_3 3
#define MACRO_EXPR (MACRO_1 <MACRO_2> MACRO_3) // OK: <MACRO_2> is not a header-name
```
### Phase 4
1) [Preprocessor](../preprocessor "c/preprocessor") is executed.
2) Each file introduced with the [#include](../preprocessor/include "c/preprocessor/include") directive goes through phases 1 through 4, recursively.
3) At the end of this phase, all preprocessor directives are removed from the source. ### Phase 5
1) All characters and [escape sequences](escape "c/language/escape") in [character constants](character_constant "c/language/character constant") and [string literals](string_literal "c/language/string literal") are converted from *source character set* to *execution character set* (which may be a multibyte character set such as UTF-8, as long as all 96 characters from the *basic source character set* listed in phase 1 have single-byte representations). If the character specified by an escape sequence isn't a member of the execution character set, the result is implementation-defined, but is guaranteed to not be a null (wide) character. Note: the conversion performed at this stage can be controlled by command line options in some implementations: gcc and clang use `-finput-charset` to specify the encoding of the source character set, `-fexec-charset` and `-fwide-exec-charset` to specify the encodings of the execution character set in the string literals and character constants that don't have an encoding prefix (since C11).
### Phase 6
Adjacent [string literals](string_literal "c/language/string literal") are concatenated.
### Phase 7
Compilation takes place: the tokens are syntactically and semantically analyzed and translated as a translation unit.
### Phase 8
Linking takes place: Translation units and library components needed to satisfy external references are collected into a program image which contains information needed for execution in its execution environment (the OS).
### References
* C11 standard (ISO/IEC 9899:2011):
+ 5.1.1.2 Translation phases (p: 10-11)
+ 5.2.1 Character sets (p: 22-24)
+ 6.4 Lexical elements (p: 57-75)
* C99 standard (ISO/IEC 9899:1999):
+ 5.1.1.2 Translation phases (p: 9-10)
+ 5.2.1 Character sets (p: 17-19)
+ 6.4 Lexical elements (p: 49-66)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 2.1.1.2 Translation phases
+ 2.2.1 Character sets
+ 3.1 Lexical elements
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/translation_phases "cpp/language/translation phases") for Phases of translation |
c Member access operators Member access operators
=======================
Member access operators allow access to the members of their operands.
| Operator | Operator name | Example | Description |
| --- | --- | --- | --- |
| `[]` | array subscript | `a[b]` | access the **b**th element of array **a** |
| `*` | pointer dereference | `*a` | dereference the pointer **a** to access the object or function it refers to |
| `&` | address of | `&a` | create a pointer that refers to the object or function **a** |
| `.` | member access | `a.b` | access member **b** of [struct](struct "c/language/struct") or [union](union "c/language/union") **a** |
| `->` | member access through pointer | `a->b` | access member **b** of [struct](struct "c/language/struct") or [union](union "c/language/union") pointed to by **a** |
### Subscript
The array subscript expression has the form.
| | | |
| --- | --- | --- |
| pointer-expression `[` integer-expression `]` | (1) | |
| integer-expression `[` pointer-expression `]` | (2) | |
where.
| | | |
| --- | --- | --- |
| pointer-expression | - | an [expression](expressions "c/language/expressions") of type pointer to complete object |
| integer-expression | - | an [expression](expressions "c/language/expressions") of integer type |
The subscript operator expression is an [lvalue expression](value_category "c/language/value category") whose type is the type of the object pointed to by pointer-expression.
By definition, the subscript operator `E1[E2]` is exactly identical to `*((E1)+(E2))`. If pointer-expression is an array expression, it undergoes [lvalue-to-rvalue conversion](conversion "c/language/conversion") and becomes a pointer to the first element of the array.
Due to the definition of the [addition between a pointer and an integer](operator_arithmetic "c/language/operator arithmetic"), the result is the element of the array with the index equal to the result of integer-expression (or, if pointer-expression was pointing at ith element of some array, the index of the result is i plus the result of integer-expression).
Note: see [array](array "c/language/array") for the details on multidimensional arrays.
```
#include <stdio.h>
int main(void)
{
int a[3] = {1,2,3};
printf("%d %d\n", a[2], // n == 3
2[a]); // same, n == 3
a[2] = 7; // subscripts are lvalues
int n[2][3] = {{1,2,3},{4,5,6}};
int (*p)[3] = &n[1]; // elements of n are arrays
printf("%d %d %d\n", (*p)[0], p[0][1], p[0][2]); // access n[1][] via p
int x = n[1][2]; // applying [] again to the array n[1]
printf("%d\n", x);
printf("%c %c\n", "abc"[2], 2["abc"]); // string literals are arrays too
}
```
Output:
```
3 3
4 5 6
6
c c
```
### Dereference
The *dereference* or *indirection* expression has the form.
| | | |
| --- | --- | --- |
| `*` pointer-expression | | |
where.
| | | |
| --- | --- | --- |
| pointer-expression | - | an [expression](expressions "c/language/expressions") of any pointer type |
If pointer-expression is a pointer to function, the result of the dereference operator is a function designator for that function.
If pointer-expression is a pointer to object, the result is an [lvalue expression](value_category "c/language/value category") that designates the pointed-to object.
Dereferencing a null pointer, a pointer to an object outside of its lifetime (a dangling pointer), a misaligned pointer, or a pointer with indeterminate value is undefined behavior, except when the dereference operator is nullified by applying the address-of operator to its result, as in `&*E`.
```
#include <stdio.h>
int main(void)
{
int n = 1;
int* p = &n;
printf("*p = %d\n", *p); // the value of *p is what's stored in n
*p = 7; // *p is lvalue
printf("*p = %d\n", *p);
}
```
Output:
```
*p = 1
*p = 7
```
### Address of
The address-of expression has the form.
| | | |
| --- | --- | --- |
| `&` function | (1) | |
| `&` lvalue-expression | (2) | |
| `&` `*` expression | (3) | |
| `&` expression `[` expression `]` | (4) | |
1) address of a function
2) address of an object
3) special case: `&` and `*` cancel each other, neither one is evaluated
4) special case: `&` and the `*` that is implied in `[]` cancel each other, only the addition implied in `[]` is evaluated. where.
| | | |
| --- | --- | --- |
| lvalue-expression | - | an [lvalue](value_category "c/language/value category") expression of any type that is not a [bit field](bit_field "c/language/bit field") and does not have [register](storage_duration "c/language/storage duration") storage class |
The address-of operator produces the [non-lvalue](value_category "c/language/value category") address of its operand, suitable for initializing a pointer to the type of the operand. If the operand is a function designator (1), the result is a pointer to function. If the operand is an object (2), the result is a pointer to object.
If the operand is the dereference operator, no action is taken (so it's okay to apply &\* to a null pointer), except that the result is not an lvalue.
If the operand is an array index expression, no action is taken other than the array-to-pointer conversion and the addition, so &a[N] is valid for an array of size N (obtaining a pointer one past the end is okay, dereferencing it is not, but dereference cancels out in this expression).
```
int f(char c) { return c;}
int main(void)
{
int n = 1;
int *p = &n; // address of object n
int (*fp)(char) = &f; // address of function f
int a[3] = {1,2,3};
int *beg=a, *end=&a[3]; // same as end = a+3
}
```
### Member access
The member access expression has the form.
| | | |
| --- | --- | --- |
| expression `.` member-name | | |
where.
| | | |
| --- | --- | --- |
| expression | - | an expression of [struct](struct "c/language/struct") or [union](union "c/language/union") type |
| member-name | - | an [identifier](identifier "c/language/identifier") that names a member of the struct or union designated by expression |
The member access expression designates the named member of the [struct](struct "c/language/struct") or [union](union "c/language/union") designated by its left operand. It has the same [value category](value_category "c/language/value category") as its left operand.
If the left operand is [const](const "c/language/const") or [volatile](volatile "c/language/volatile") qualified, the result is also qualified. If the left operand is [atomic](atomic "c/language/atomic"), the behavior is undefined.
Note: besides identifiers that name objects of struct or union type, the following expressions may have struct or union types: [assignment](operator_assignment "c/language/operator assignment"), [function call](operator_other#Function_call "c/language/operator other"), [comma operator](operator_other#Comma_operator "c/language/operator other"), [conditional operator](operator_other#Conditional_operator "c/language/operator other"), and [compound literal](compound_literal "c/language/compound literal").
```
#include <stdio.h>
struct s {int x;};
struct s f(void) { return (struct s){1}; }
int main(void)
{
struct s s;
s.x = 1; // ok, changes the member of s
int n = f().x; // f() is an expression of type struct s
// f().x = 1; // Error: this member access expression is not an lvalue
const struct s sc;
// sc.x = 3; // Error: sc.x is const, can't be assigned
union { int x; double d; } u = {1};
u.d = 0.1; // changes the active member of the union
}
```
### Member access through pointer
The member access expression has the form.
| | | |
| --- | --- | --- |
| expression `->` member-name | | |
where.
| | | |
| --- | --- | --- |
| expression | - | an expression of type [pointer](pointer "c/language/pointer") to [struct](struct "c/language/struct") or [union](union "c/language/union") |
| member-name | - | an [identifier](identifier "c/language/identifier") that names a member of the struct or union pointed by expression |
The member access through pointer expression designates the named member of the [struct](struct "c/language/struct") or [union](union "c/language/union") type pointed to by its left operand. Its value category is always [lvalue](value_category "c/language/value category").
If the type pointed to by the left operand is [const](const "c/language/const") or [volatile](volatile "c/language/volatile") qualified, the result is also qualified. If the type pointed to by the left operand is [atomic](atomic "c/language/atomic"), the behavior is undefined.
```
#include <stdio.h>
struct s {int x;};
int main(void)
{
struct s s={1}, *p = &s;
p->x = 7; // changes the value of s.x through the pointer
printf("%d\n", p->x); // prints 7
}
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [DR 076](https://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_076.html) | C89 | unnessary indirection could not be cancelled by `&` | made cancellable |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.5.2.1 Array subscripting (p: 57-58)
+ 6.5.2.3 Structure and union members (p: 58-59)
+ 6.5.3.2 Address and indirection operators (p: 59-61)
* C11 standard (ISO/IEC 9899:2011):
+ 6.5.2.1 Array subscripting (p: 80)
+ 6.5.2.3 Structure and union members (p: 82-84)
+ 6.5.3.2 Address and indirection operators (p: 88-89)
* C99 standard (ISO/IEC 9899:1999):
+ 6.5.2.1 Array subscripting (p: 70)
+ 6.5.2.3 Structure and union members (p: 72-74)
+ 6.5.3.2 Address and indirection operators (p: 78-79)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.3.2.1 Array subscripting
+ 3.3.2.3 Structure and union members
+ 3.3.3.2 Address and indirection operators
### See also
* [Operator precedence](operator_precedence "c/language/operator precedence")
| Common operators |
| --- |
| [assignment](operator_assignment "c/language/operator assignment") | [incrementdecrement](operator_incdec "c/language/operator incdec") | [arithmetic](operator_arithmetic "c/language/operator arithmetic") | [logical](operator_logical "c/language/operator logical") | [comparison](operator_comparison "c/language/operator comparison") | **memberaccess** | [other](operator_other "c/language/operator other") |
| `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b`. | `a[b] *a &a a->b a.b`. | `a(...) a, b (type) a ? : sizeof _Alignof` (since C11). |
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_member_access "cpp/language/operator member access") for Member access operators |
c Predefined Boolean constants (since C23)
Predefined Boolean constants (since C23)
========================================
### Syntax
| | | |
| --- | --- | --- |
| `true` | (1) | (since C23) |
| `false` | (2) | (since C23) |
### Explanation
Keywords `true` and `false` represent predefined constants. They are [non-lvalues](value_category#Non-lvalue_object_expressions "c/language/value category") of type [`bool`](types "c/language/types").
### Notes
See [integral conversions](conversion#Integer_conversions "c/language/conversion") for implicit conversions from `bool` to other types and [boolean conversions](conversion#Boolean_conversion "c/language/conversion") for the implicit conversions from other types to `bool`.
Until C23, `true` and `false` were implemented as macros provided in [`<stdbool.h>`](../types "c/types"). An implementation may also define `bool`, `true`, and `false` as predefined macros in C23 for compatibility.
### Example
```
#include <stdio.h>
int main(void)
{
printf("%d\n%d\n", true, false);
}
```
Output:
```
1
0
```
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/bool_literal "cpp/language/bool literal") for Boolean literals |
c Lookup and name spaces Lookup and name spaces
======================
When an [identifier](identifier "c/language/identifier") is encountered in a C program, a lookup is performed to locate the [declaration](declarations "c/language/declarations") that introduced that identifier and that is currently [in scope](scope "c/language/scope"). C allows more than one declaration for the same identifier to be in scope simultaneously if these identifiers belong to different categories, called *name spaces*:
1) Label name space: all identifiers declared as [labels](statements#Labels "c/language/statements").
2) Tag names: all identifiers declared as names of [structs](struct "c/language/struct"), [unions](union "c/language/union") and [enumerated types](enum "c/language/enum"). Note that all three kinds of tags share one name space.
3) Member names: all identifiers declared as members of any one [struct](struct "c/language/struct") or [union](union "c/language/union"). Every struct and union introduces its own name space of this kind.
| | |
| --- | --- |
| 4) Global attribute name space: [attribute tokens](attributes "c/language/attributes") defined by the standard or implementation-defined attribute prefixes. 5) Non-standard attribute names: attribute names following attribute prefixes. Each attribute prefix has a separate name space for the implementation-defined attributes it introduces. | (since C23) |
6) All other identifiers, called *ordinary identifiers* to distinguish from (1-5) (function names, object names, typedef names, enumeration constants). At the point of lookup, the name space of an identifier is determined by the manner in which it is used:
1) identifier appearing as the operand of a [goto statement](goto "c/language/goto") is looked up in the label name space.
2) identifier that follows the keyword `struct`, `union`, or `enum` is looked up in the tag name space.
3) identifier that follows the [member access](operator_member_access "c/language/operator member access") or member access through pointer operator is looked up in the name space of members of the type determined by the left-hand operand of the member access operator.
| | |
| --- | --- |
| 4) identifier that directly appears in an attribute specifier (`[[...]]`) is looked up in the global attribute name space. 5) identifier that follows the `::` token following an attribute prefix is looked in the name space introduced by the attribute prefix. | (since C23) |
6) all other identifiers are looked up in the name space of ordinary identifiers. ### Notes
The names of [macros](../preprocessor/replace "c/preprocessor/replace") are not part of any name space because they are replaced by the preprocessor prior to semantic analysis.
It is common practice to inject struct/union/enum names into the name space of the ordinary identifiers using a [typedef](typedef "c/language/typedef") declaration:
```
struct A { }; // introduces the name A in tag name space
typedef struct A A; // first, lookup for A after "struct" finds one in tag name space
// then introduces the name A in the ordinary name space
struct A* p; // OK, this A is looked up in the tag name space
A* q; // OK, this A is looked up in the ordinary name space
```
A well-known example of the same identifier being used across two name spaces is the identifier `stat` from the POSIX header `sys/stat.h`. It [names a function](http://pubs.opengroup.org/onlinepubs/9699919799/) when used as an ordinary identifier and [indicates a struct](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html) when used as a tag.
Unlike in C++, enumeration constants are not struct members, and their name space is the name space of ordinary identifiers, and since there is no struct scope in C, their scope is the scope in which the struct declaration appears:
```
struct tagged_union {
enum {INT, FLOAT, STRING} type;
union {
int integer;
float floating_point;
char *string;
};
} tu;
tu.type = INT; // OK in C, error in C++
```
| | |
| --- | --- |
| If a standard attribute, an attribute prefix, or a non-standard attribute name is not supported, the invalid attribute itself is ignored without causing an error. | (since C23) |
### Example
```
void foo (void) { return; } // ordinary name space, file scope
struct foo { // tag name space, file scope
int foo; // member name space for this struct foo, file scope
enum bar { // tag name space, file scope
RED // ordinary name space, file scope
} bar; // member name space for this struct foo, file scope
struct foo* p; // OK: uses tag/file scope name "foo"
};
enum bar x; // OK: uses tag/file-scope bar
// int foo; // Error: ordinary name space foo already in scope
//union foo { int a, b; }; // Error: tag name space foo in scope
int main(void)
{
goto foo; // OK uses "foo" from label name space/function scope
struct foo { // tag name space, block scope (hides file scope)
enum bar x; // OK, uses "bar" from tag name space/file scope
};
typedef struct foo foo; // OK: uses foo from tag name space/block scope
// defines block-scope ordinary foo (hides file scope)
(foo){.x=RED}; // uses ordinary/block-scope foo and ordinary/file-scope RED
foo:; // label name space, function scope
}
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.2.3 Name spaces of identifiers (p: 29-30)
* C11 standard (ISO/IEC 9899:2011):
+ 6.2.3 Name spaces of identifiers (p: 37)
* C99 standard (ISO/IEC 9899:1999):
+ 6.2.3 Name spaces of identifiers (p: 31)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.2.3 Name spaces of identifiers
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/lookup "cpp/language/lookup") for Name lookup |
| programming_docs |
c Objects and alignment Objects and alignment
=====================
C programs create, destroy, access, and manipulate objects.
An object, in C, is region of [data storage](memory_model "c/language/memory model") in the execution environment, the contents of which can represent *values* (a value is the meaning of the contents of an object, when interpreted as having a specific [type](type "c/language/type")).
Every object has.
* size (can be determined with [`sizeof`](sizeof "c/language/sizeof"))
* alignment requirement (can be determined by [`_Alignof`](_alignof "c/language/ Alignof")) (since C11)
* [storage duration](storage_duration "c/language/storage duration") (automatic, static, allocated, thread-local)
* [lifetime](lifetime "c/language/lifetime") (equal to storage duration or temporary)
* effective type (see below)
* value (which may be indeterminate)
* optionally, an [identifier](identifier "c/language/identifier") that denotes this object
Objects are created by [declarations](declarations "c/language/declarations"), [allocation functions](../memory "c/memory"), [string literals](string_literal "c/language/string literal"), [compound literals](compound_literal "c/language/compound literal"), and by non-lvalue expressions that return [structures or unions with array members](lifetime "c/language/lifetime").
### Object representation
Except for [bit fields](bit_field "c/language/bit field"), objects are composed of contiguous sequences of one or more bytes, each consisting of `[CHAR\_BIT](../types/limits "c/types/limits")` bits, and can be copied with `[memcpy](../string/byte/memcpy "c/string/byte/memcpy")` into an object of type `unsigned char[n]`, where `n` is the size of the object. The contents of the resulting array are known as *object representation*.
If two objects have the same object representation, they compare equal (except if they are floating-point NaNs). The opposite is not true: two objects that compare equal may have different object representations because not every bit of the object representation needs to participate in the value. Such bits may be used for padding to satisfy alignment requirement, for parity checks, to indicate trap representations, etc.
If an object representation does not represent any value of the object type, it is known as *trap representation*. Accessing a trap representation in any way other than reading it through an lvalue expression of character type is undefined behavior. The value of a structure or union is never a trap representation even if any particular member is one.
For the objects of type char, signed char, and unsigned char, every bit of the object representation is required to participate in the value representation and each possible bit pattern represents a distinct value (no padding, trap bits, or multiple representations allowed).
When objects of [integer types](arithmetic_types#Integer_types "c/language/arithmetic types") (short, int, long, long long) occupy multiple bytes, the use of those bytes is implementation-defined, but the two dominant implementations are *big-endian* (POWER, Sparc, Itanium) and *little-endian* (x86, x86\_64): a big-endian platform stores the most significant byte at the lowest address of the region of storage occupied by the integer, a little-endian platform stores the least significant byte at the lowest address. See [Endianness](https://en.wikipedia.org/wiki/Endianness "enwiki:Endianness") for detail. See also example below.
Although most implementations do not allow trap representations, padding bits, or multiple representations for integer types, there are exceptions; for example a value of an integer type on Itanium [may be a trap representation](https://devblogs.microsoft.com/oldnewthing/20040119-00/?p=41003).
### Effective type
Every object has an *effective type*, which determines which [lvalue](value_category "c/language/value category") accesses are valid and which violate the strict aliasing rules.
If the object was created by a [declaration](declarations "c/language/declarations"), the declared type of that object is the object's *effective type*.
If the object was created by an [allocation function](../memory "c/memory") (including `[realloc](../memory/realloc "c/memory/realloc")`), it has no declared type. Such object acquires an effective type as follows:
* The first write to that object through an lvalue that has a type other than character type, at which time the type of that lvalue becomes this object's *effective type* for that write and all subsequent reads.
* `[memcpy](../string/byte/memcpy "c/string/byte/memcpy")` or `[memmove](../string/byte/memmove "c/string/byte/memmove")` copy another object into that object, at which time the effective type of the source object (if it had one) becomes the effective type of this object for that write and all subsequent reads.
* Any other access to the object with no declared type, the effective type is the type of the lvalue used for the access.
### Strict aliasing
Given an object with *effective type* T1, using an lvalue expression (typically, dereferencing a pointer) of a different type T2 is undefined behavior, unless:
* T2 and T1 are [compatible types](type#Compatible_types "c/language/type").
* T2 is cvr-qualified version of a type that is [compatible](type#Compatible_types "c/language/type") with T1.
* T2 is a signed or unsigned version of a type that is [compatible](type#Compatible_types "c/language/type") with T1.
* T2 is an aggregate type or union type type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union).
* T2 is a character type (char, signed char, or unsigned char).
```
int i = 7;
char* pc = (char*)(&i);
if (pc[0] == '\x7') { // aliasing through char is ok
puts("This system is little-endian");
} else {
puts("This system is big-endian");
}
float* pf = (float*)(&i);
float d = *pf; // UB: float lvalue *p cannot be used to access int
```
These rules control whether a function that receives two pointers must re-read one after writing through another:
```
// int* and double* cannot alias
void f1(int *pi, double *pd, double d)
{
// the read from *pi can be done only once, before the loop
for (int i = 0; i < *pi; i++) *pd++ = d;
}
```
```
struct S { int a, b; };
// int* and struct S* may alias because S is an aggregate type with a member of type int
void f2(int *pi, struct S *ps, struct S s)
{
// read from *pi must take place after every write through *ps
for (int i = 0; i < *pi; i++) *ps++ = s;
}
```
Note that [restrict qualifier](restrict "c/language/restrict") can be used to indicate that two pointers do not alias even if the rules above permit them to be.
Note that type-punning may also be performed through the inactive member of a [union](union "c/language/union").
### Alignment
Every complete [object type](types#Type_groups "c/language/types") has a property called *alignment requirement*, which is an integer value of type `[size\_t](../types/size_t "c/types/size t")` representing the number of bytes between successive addresses at which objects of this type can be allocated. The valid alignment values are non-negative integral powers of two.
| | |
| --- | --- |
| The alignment requirement of a type can be queried with [`_Alignof`](_alignof "c/language/ Alignof"). | (since C11) |
In order to satisfy alignment requirements of all members of a struct, padding may be inserted after some of its members.
```
#include <stdio.h>
#include <stdalign.h>
// objects of struct S can be allocated at any address
// because both S.a and S.b can be allocated at any address
struct S {
char a; // size: 1, alignment: 1
char b; // size: 1, alignment: 1
}; // size: 2, alignment: 1
// objects of struct X must be allocated at 4-byte boundaries
// because X.n must be allocated at 4-byte boundaries
// because int's alignment requirement is (usually) 4
struct X {
int n; // size: 4, alignment: 4
char c; // size: 1, alignment: 1
// three bytes padding
}; // size: 8, alignment: 4
int main(void)
{
printf("sizeof(struct S) = %zu\n", sizeof(struct S));
printf("alignof(struct S) = %zu\n", alignof(struct S));
printf("sizeof(struct X) = %zu\n", sizeof(struct X));
printf("alignof(struct X) = %zu\n", alignof(struct X));
}
```
Possible output:
```
sizeof(struct S) = 2
alignof(struct S) = 1
sizeof(struct X) = 8
alignof(struct X) = 4
```
Each object type imposes its alignment requirement on every object of that type. The strictest (largest) fundamental alignment of any type is the alignment of `[max\_align\_t](../types/max_align_t "c/types/max align t")`. The weakest (smallest) alignment is the alignment of the types `char`, `signed char`, and `unsigned char`, and equals 1.
| | |
| --- | --- |
| If an object's alignment is made stricter (larger) than `[max\_align\_t](../types/max_align_t "c/types/max align t")` using [`_Alignas`](_alignas "c/language/ Alignas"), it has *extended alignment requirement*. A struct or union type whose member has extended alignment is an *over-aligned type*. It is implementation-defined if over-aligned types are supported, and their support may be different in each kind of [storage duration](storage_duration "c/language/storage duration"). | (since C11) |
### References
* C11 standard (ISO/IEC 9899:2011):
+ 3.15 object (p: 6)
+ 6.2.6 Representations of types (p: 44-46)
+ 6.5/6-7 Expressions (p: 77)
+ 6.2.8 Alignment of objects (p: 48-49)
* C99 standard (ISO/IEC 9899:1999):
+ 3.2 alignment (p: 3)
+ 3.14 object (p: 5)
+ 6.2.6 Representations of types (p: 37-39)
+ 6.5/6-7 Expressions (p: 67-68)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 1.6 Definitions of terms
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/object "cpp/language/object") for Object |
c Type Type
====
(See also [arithmetic types](arithmetic_types "c/language/arithmetic types") for the details on most built-in types and [the list of type-related utilities](../types "c/types") that are provided by the C library).
[Objects](object "c/language/object"), [functions](functions "c/language/functions"), and [expressions](expressions "c/language/expressions") have a property called *type*, which determines the interpretation of the binary value stored in an object or evaluated by the expression.
### Type classification
The C type system consists of the following types:
* the type `void`
* basic types
* the type `char`
* signed integer types
+ standard: `signed char`, `short`, `int`, `long`, `long long` (since C99)
| | |
| --- | --- |
| * extended: implementation defined, e.g. `__int128`
| (since C99) |
* unsigned integer types
+ standard: `_Bool`, (since C99) `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long` (since C99)
| | |
| --- | --- |
| * extended: implementation-defined, e.g. `__uint128`
| (since C99) |
* floating-point types
+ real floating-point types: `float`, `double`, `long double`
| | |
| --- | --- |
| * decimal real floating-point types: `_Decimal32`, `_Decimal64`, `_Decimal128`
| (since C23) |
| * complex types: `float _Complex`, `double _Complex`, `long double _Complex`
* imaginary types: `float _Imaginary`, `double _Imaginary`, `long double _Imaginary`
| (since C99) |
* [enumerated types](enum "c/language/enum")
* derived types
+ [array types](array "c/language/array")
+ [structure types](struct "c/language/struct")
+ [union types](union "c/language/union")
+ [function types](functions "c/language/functions")
+ [pointer types](pointer "c/language/pointer")
| | |
| --- | --- |
| * [atomic types](atomic "c/language/atomic")
| (since C11) |
For every type listed above several qualified versions of its type may exist, corresponding to the combinations of one, two, or all three of the [`const`](const "c/language/const"), [`volatile`](volatile "c/language/volatile"), and [`restrict`](restrict "c/language/restrict") qualifiers (where allowed by the qualifier's semantics).
#### Type groups
* *object types*: all types that aren't function types
* *character types*: `char`, `signed char`, `unsigned char`
* *integer types*: `char`, signed integer types, unsigned integer types, enumerated types
* *real types*: integer types and real floating types
* [arithmetic types](arithmetic_types "c/language/arithmetic types"): integer types and floating types
* *scalar types*: arithmetic types, pointer types, and `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` (since C23)
* *aggregate types*: array types and structure types
* *derived declarator types*: array types, function types, and pointer types
### Compatible types
In a C program, the declarations referring to the same object or function in *different translation units* do not have to use the same type. They only have to use sufficiently similar types, formally known as *compatible types*. Same applies to function calls and lvalue accesses; argument types must be *compatible* with parameter types and lvalue expression type must be *compatible* with the object type that is accessed.
The types `T` and `U` are compatible, if.
* they are the same type (same name or aliases introduced by a [typedef](typedef "c/language/typedef"))
* they are identically cvr-qualified versions of compatible unqualified types
* they are pointer types and are pointing to compatible types
* they are array types, and
+ their element types are compatible, and
+ if both have constant size, that size is the same. Note: arrays of unknown bound are compatible with any array of compatible element type. VLA is compatible with any array of compatible element type. (since C99)
* they are both structure/union/enumeration types, and
* (C99)if one is declared with a tag, the other must also be declared with the same tag.
* if both are completed types, their members must correspond exactly in number, be declared with compatible types, and have matching names.
* additionally, if they are enumerations, corresponding members must also have the same values.
* additionally, if they are structures or unions,
+ Corresponding members must be declared in the same order (structures only)
+ Corresponding bit fields must have the same widths.
* one is an enumerated type and the other is that enumeration's underlying type
* they are function types, and
+ their return types are compatible
+ they both use parameter lists, the number of parameters (including the use of the ellipsis) is the same, and the corresponding parameter, after applying array-to-pointer and function-to-pointer type adjustments and after stripping top-level qualifiers, have compatible types
+ one is an old-style (parameter-less) definition, the other has a parameter list, the parameter list does not use an ellipsis and each parameter is compatible (after function parameter type adjustment) with the corresponding old-style parameter after default argument promotions
+ one is an old-style (parameter-less) declaration, the other has a parameter list, the parameter list does not use an ellipsis, and all parameters (after function parameter type adjustment) are unaffected by default argument promotions
The type `char` is not compatible with `signed char` and not compatible with `unsigned char`.
If two declarations refer to the same object or function and do not use compatible types, the behavior of the program is undefined.
```
// Translation Unit 1
struct S {int a;};
extern struct S *x; // compatible with TU2's x, but not with TU3's x
// Translation Unit 2
struct S;
extern struct S *x; // compatible with both x's
// Translation Unit 3
struct S {float a;};
extern struct S *x; // compatible with TU2's x, but not with TU1's x
// the behavior is undefined
```
```
// Translation Unit 1
#include <stdio.h>
struct s {int i;}; // compatible with TU3's s, but not TU2's
extern struct s x = {0}; // compatible with TU3's x
extern void f(void); // compatible with TU2's f
int main()
{
f();
return x.i;
}
// Translation Unit 2
struct s {float f;}; // compatible with TU4's s, but not TU1's s
extern struct s y = {3.14}; // compatible with TU4's y
void f() // compatible with TU1's f
{
return;
}
// Translation Unit 3
struct s {int i;}; // compatible with TU1's s, but not TU2's s
extern struct s x; // compatible with TU1's x
// Translation Unit 4
struct s {float f;}; // compatible with TU2's s, but not TU1's s
extern struct s y; // compatible with TU2's y
// the behavior is well-defined: only multiple declarations
// of objects and functions must have compatible types, not the types themselves
```
Note: C++ has no concept of compatible types. A C program that declares two types that are compatible but not identical in different translation units is not a valid C++ program.
### Composite types
A composite type can be constructed from two types that are compatible; it is a type that is compatible with both of the two types and satisfies the following conditions:
* If both types are array types, the following rules are applied:
+ If one type is an array of known constant size, the composite type is an array of that size.
| | |
| --- | --- |
| * Otherwise, if one type is a VLA whose size is specified by an expression that is not evaluated, the behavior is undefined.
* Otherwise, if one type is a VLA whose size is specified, the composite type is a VLA of that size.
* Otherwise, if one type is a VLA of unspecified size, the composite type is a VLA of unspecified size.
| (since C99) |
* Otherwise, both types are arrays of unknown size and the composite type is an array of unknown size.
* If only one type is a function type with a parameter type list (a function prototype), the composite type is a function prototype with the parameter type list.
* If both types are function types with parameter type lists, the type of each parameter in the composite parameter type list is the composite type of the corresponding parameters.
The element type of the composite type is the composite type of the two element types. These rules apply recursively to the types from which the two types are derived.
```
// Given the following two file scope declarations:
int f(int (*)(), double (*)[3]);
int f(int (*)(char *), double (*)[]);
// The resulting composite type for the function is:
int f(int (*)(char *), double (*)[3]);
```
For an identifier with internal or external [linkage](storage_duration "c/language/storage duration") declared in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the type of the identifier at the later declaration becomes the composite type.
### Incomplete types
An incomplete type is an object type that lacks sufficient information to determine the size of the objects of that type. An incomplete type may be completed at some point in the translation unit.
The following types are incomplete:
* the type `void`. This type cannot be completed.
* array type of unknown size. It can be completed by a later declaration that specifies the size.
```
extern char a[]; // the type of a is incomplete (this typically appears in a header)
char a[10]; // the type of a is now complete (this typically appears in a source file)
```
* structure or union type of unknown content. It can be completed by a declaration of the same structure or union that defines its content later in the same scope.
```
struct node {
struct node *next; // struct node is incomplete at this point
}; // struct node is complete at this point
```
### Type names
A type may have to be named in context other than the [declaration](declarations "c/language/declarations"). In these situations, *type name* is used, which is, grammatically, exactly the same as a list of *type-specifiers* and *type-qualifiers*, followed by the *declarator* (see [declarations](declarations "c/language/declarations")) as would be used to declare a single object or function of this type, except that the identifier is omitted:
```
int n; // declaration of an int
sizeof(int); // use of type name
int *a[3]; // declaration of an array of 3 pointers to int
sizeof(int *[3]); // use of type name
int (*p)[3]; // declaration of a pointer to array of 3 int
sizeof(int (*)[3]); // use of type name
int (*a)[*] // declaration of pointer to VLA (in a function parameter)
sizeof(int (*)[*]) // use of type name (in a function parameter)
int *f(void); // declaration of function
sizeof(int *(void)); // use of type name
int (*p)(void); // declaration of pointer to function
sizeof(int (*)(void)); // use of type name
int (*const a[])(unsigned int, ...) = {0}; // array of pointers to functions
sizeof(int (*const [])(unsigned int, ...)); // use of type name
```
Except the redundant parentheses around the identifier are meaningful in a type-name and represent "function with no parameter specification":
```
int (n); // declares n of type int
sizeof(int ()); // uses type "function returning int"
```
Type names are used in the following situations:
* [cast](cast "c/language/cast")
* [sizeof](sizeof "c/language/sizeof")
| | |
| --- | --- |
| * [compound literal](compound_literal "c/language/compound literal")
| (since C99) |
| * [generic selection](generic "c/language/generic")
* [\_Alignof](_alignof "c/language/ Alignof")
* [\_Alignas](_alignas "c/language/ Alignas")
* [\_Atomic](atomic "c/language/atomic") (when used as a type specifier)
| (since C11) |
A type name may introduce a new type:
```
void* p = (void*)(struct X {int i;} *)0;
// type name "struct X {int i;}*" used in the cast expression
// introduces the new type "struct X"
struct X x = {1}; // struct X is now in scope
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.2.5 Types (p: 31-33)
+ 6.2.6 Representations of types (p: 31-35)
+ 6.2.7 Compatible type and composite type (p: 35-36)
* C11 standard (ISO/IEC 9899:2011):
+ 6.2.5 Types (p: 39-43)
+ 6.2.6 Representations of types (p: 44-46)
+ 6.2.7 Compatible type and composite type (p: 47-48)
* C99 standard (ISO/IEC 9899:1999):
+ 6.2.5 Types (p: 33-37)
+ 6.2.6 Representations of types (p: 37-40)
+ 6.2.7 Compatible type and composite type (p: 40-41)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.2.5 Types
+ 3.1.2.6 Compatible type and composite type
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/type "cpp/language/type") for Type |
| programming_docs |
c Predefined null pointer constant (since C23)
Predefined null pointer constant (since C23)
============================================
### Syntax
| | | |
| --- | --- | --- |
| `nullptr` | | (since C23) |
### Explanation
The keyword `nullptr` denotes a predefined null pointer constant. It is a [non-lvalue](value_category#Non-lvalue_object_expressions "c/language/value category") of type `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")`. `nullptr` can be [converted](conversion "c/language/conversion") to a pointer types or `bool`, where the result is the null pointer value of that type or `false` respectively.
### Example
Demonstrates that a copy of `nullptr` can also be used as a null pointer constant.
```
#include <stddef.h>
#include <stdio.h>
void g(int*)
{
puts("Function g called");
}
#define DETECT_NULL_POINTER_CONSTANT(e) \
_Generic(e, \
void* : puts("void*"), \
nullptr_t : puts("nullptr_t"), \
default : puts("integer") \
)
int main()
{
g(nullptr); // Fine
g(NULL); // Fine
g(0); // Fine
puts("----------------");
auto cloned_nullptr = nullptr;
auto cloned_NULL = NULL;
auto cloned_zero = 0;
g(cloned_nullptr); // Fine
// g(cloned_NULL); // ERROR
// g(cloned_zero); // ERROR
puts("----------------");
DETECT_NULL_POINTER_CONSTANT(((void*)0));
DETECT_NULL_POINTER_CONSTANT(0);
DETECT_NULL_POINTER_CONSTANT(nullptr);
DETECT_NULL_POINTER_CONSTANT(NULL); // implementation-defined
}
```
Possible output:
```
Function g called
Function g called
Function g called
----------------
Function g called
----------------
void*
integer
nullptr_t
void*
```
### Keywords
[`nullptr`](https://en.cppreference.com/mwiki/index.php?title=c/keyword/nullptr&action=edit&redlink=1 "c/keyword/nullptr (page does not exist)").
### References
* C23 standard (ISO/IEC 9899:2023):
### See also
| | |
| --- | --- |
| [NULL](../types/null "c/types/NULL") | implementation-defined null pointer constant (macro constant) |
| [nullptr\_t](../types/nullptr_t "c/types/nullptr t")
(C23) | the type of the predefined null pointer constant **`nullptr`** (typedef) |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/nullptr "cpp/language/nullptr") for `nullptr` |
c Arithmetic operators Arithmetic operators
====================
Arithmetic operators apply standard mathematical operations to their operands.
| Operator | Operator name | Example | Result |
| --- | --- | --- | --- |
| `+` | unary plus | `+a` | the value of **a** after promotions |
| `-` | unary minus | `-a` | the negative of **a** |
| `+` | addition | `a + b` | the addition of **a** and **b** |
| `-` | subtraction | `a - b` | the subtraction of **b** from **a** |
| `*` | product | `a * b` | the product of **a** and **b** |
| `/` | division | `a / b` | the division of **a** by **b** |
| `%` | remainder | `a % b` | the remainder of **a** divided by **b** |
| `~` | bitwise NOT | `~a` | the bitwise NOT of **a** |
| `&` | bitwise AND | `a & b` | the bitwise AND of **a** and **b** |
| `|` | bitwise OR | `a | b` | the bitwise OR of **a** and **b** |
| `^` | bitwise XOR | `a ^ b` | the bitwise XOR of **a** and **b** |
| `<<` | bitwise left shift | `a << b` | **a** left shifted by **b** |
| `>>` | bitwise right shift | `a >> b` | **a** right shifted by **b** |
### Overflows
Unsigned integer arithmetic is always performed modulo 2n
where n is the number of bits in that particular integer. E.g. for `unsigned int`, adding one to `[UINT\_MAX](../types/limits "c/types/limits")` gives `0`, and subtracting one from `0` gives `[UINT\_MAX](../types/limits "c/types/limits")`.
When signed integer arithmetic operation overflows (the result does not fit in the result type), the behavior is undefined: it may wrap around according to the rules of the representation (typically 2's complement), it may trap on some platforms or due to compiler options (e.g. `-ftrapv` in GCC and Clang), or may be completely [optimized out by the compiler](http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html).
#### Floating-point environment
If [`#pragma STDC FENV_ACCESS`](../preprocessor/impl "c/preprocessor/impl") is set to `ON`, all floating-point arithmetic operators obey the current floating-point [rounding direction](../numeric/fenv/fe_round "c/numeric/fenv/FE round") and report floating-point arithmetic errors as specified in [`math_errhandling`](../numeric/math/math_errhandling "c/numeric/math/math errhandling") unless part of a [static initializer](initialization "c/language/initialization") (in which case floating-point exceptions are not raised and the rounding mode is to nearest).
#### Floating-point contraction
Unless [`#pragma STDC FP_CONTRACT`](../preprocessor/impl "c/preprocessor/impl") is set to `OFF`, all floating-point arithmetic may be performed as if the intermediate results have infinite range and precision, that is optimizations that omit rounding errors and floating-point exceptions that would be observed if the expression was evaluated exactly as written. For example, allows the implementation of `(x*y) + z` with a single fused multiply-add CPU instruction or optimization of `a = x*x*x*x;` as `tmp = x*x; a = tmp*tmp`.
Unrelated to contracting, intermediate results of floating-point arithmetic may have range and precision that is different from the one indicated by its type, see `[FLT\_EVAL\_METHOD](../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")`.
### Unary arithmetic
The unary arithmetic operator expressions have the form.
| | | |
| --- | --- | --- |
| `+` expression | (1) | |
| `-` expression | (2) | |
1) unary plus (promotion)
2) unary minus (negation) where.
| | | |
| --- | --- | --- |
| expression | - | expression of any [arithmetic type](arithmetic_types "c/language/arithmetic types") |
Both unary plus and unary minus first apply [integral promotions](conversion "c/language/conversion") to their operand, and then.
* unary plus returns the value after promotion
* unary minus returns the negative of the value after promotion (except that the negative of a NaN is another NaN)
The type of the expression is the type after promotion, and the [value category](value_category "c/language/value category") is non-lvalue.
#### Notes
The unary minus invokes undefined behavior due to signed integer overflow when applied to `[INT\_MIN](../types/limits "c/types/limits")`, `[LONG\_MIN](../types/limits "c/types/limits")`, or `[LLONG\_MIN](../types/limits "c/types/limits")`, on typical (2's complement) platforms.
In C++, unary operator `+` can also be used with other built-in types such as arrays and functions, not so in C.
```
#include <stdio.h>
#include <complex.h>
#include <limits.h>
int main(void)
{
char c = 'a';
printf("sizeof char: %zu sizeof int: %zu\n", sizeof c, sizeof +c);
printf("-1, where 1 is signed: %d\n", -1);
// Defined behavior since arithmetic is performed for unsigned integer.
// Hence, the calculation is (-1) modulo (2 raised to n) = UINT_MAX, where n is
// the number of bits of unsigned int. If unsigned int is 32-bit long, then this
// gives (-1) modulo (2 raised to 32) = 4294967295
printf("-1, where 1 is unsigned: %u\n", -1u);
// Undefined behavior because the mathematical value of -INT_MIN = INT_MAX + 1
// (i.e. 1 more than the maximum possible value for signed int)
//
// printf("%d\n", -INT_MIN);
// Undefined behavior because the mathematical value of -LONG_MIN = LONG_MAX + 1
// (i.e. 1 more than the maximum possible value for signed long)
//
// printf("%ld\n", -LONG_MIN);
// Undefined behavior because the mathematical value of -LLONG_MIN = LLONG_MAX + 1
// (i.e. 1 more than the maximum possible value for signed long long)
//
// printf("%lld\n", -LLONG_MIN);
double complex z = 1 + 2*I;
printf("-(1+2i) = %.1f%+.1f\n", creal(-z), cimag(-z));
}
```
Possible output:
```
sizeof char: 1 sizeof int: 4
-1, where 1 is signed: -1
-1, where 1 is unsigned: 4294967295
-(1+2i) = -1.0-2.0
```
### Additive operators
The binary additive arithmetic operator expressions have the form.
| | | |
| --- | --- | --- |
| lhs `+` rhs | (1) | |
| lhs `-` rhs | (2) | |
1) addition: lhs and rhs must be one of the following * both have [arithmetic types](arithmetic_types "c/language/arithmetic types"), including complex and imaginary
* one is a pointer to complete object type, the other has integer type
2) subtraction: lhs and rhs must be one of the following * both have [arithmetic types](arithmetic_types "c/language/arithmetic types"), including complex and imaginary
* lhs has pointer to complete object type, rhs has integer type
* both are pointers to complete objects of [compatible](type#Comparible_types "c/language/type") types, ignoring qualifiers
#### Arithmetic addition and subtraction
If both operands have [arithmetic types](arithmetic_types "c/language/arithmetic types"), then.
* first, [usual arithmetic conversions](conversion#Usual_arithmetic_conversions "c/language/conversion") are performed
* then, the values of the operands after conversions are added or subtracted following the usual rules of mathematics (for subtraction, rhs is subtracted from lhs), except that
+ if one operand is NaN, the result is NaN
+ infinity minus infinity is NaN and `[FE\_INVALID](../numeric/fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
+ infinity plus the negative infinity is NaN and `[FE\_INVALID](../numeric/fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
Complex and imaginary addition and subtraction are defined as follows (note the result type is imaginary if both operands are imaginary and complex if one operand is real and the other imaginary, as specified by the usual arithmetic conversions):
| + or - | u | iv | u + iv |
| --- | --- | --- | --- |
| x | x ± u | x ± iv | (x ± u) ± iv |
| iy | ±u + iy | i(y ± v) | ±u + i(y ± v) |
| x + iy | (x ± u) + iy | x + i(y ± v) | (x ± u) + i(y ± v) |
```
// work in progress
// note: take part of the c/language/conversion example
```
#### Pointer arithmetic
* If the pointer `P` points at an element of an array with index `I`, then
+ `P+N` and `N+P` are pointers that point at an element of the same array with index `I+N`
+ `P-N` is a pointer that points at an element of the same array with index `I-N`
The behavior is defined only if both the original pointer and the result pointer are pointing at elements of the same array or one past the end of that array. Note that executing p-1 when p points at the first element of an array is undefined behavior and may fail on some platforms.
* If the pointer `P1` points at an element of an array with index `I` (or one past the end) and `P2` points at an element of the same array with index `J` (or one past the end), then
+ `P1-P2` has the value equal to `I-J` and the type `[ptrdiff\_t](../types/ptrdiff_t "c/types/ptrdiff t")` (which is a signed integer type, typically half as large as the size of the largest object that can be declared)
The behavior is defined only if the result fits in `[ptrdiff\_t](../types/ptrdiff_t "c/types/ptrdiff t")`.
For the purpose of pointer arithmetic, a pointer to an object that is not an element of any array is treated as a pointer to the first element of an array of size 1.
```
// work in progress
int n = 4, m = 3;
int a[n][m]; // VLA of 4 VLAs of 3 ints each
int (*p)[m] = a; // p == &a[0]
p = p + 1; // p == &a[1] (pointer arithmetic works with VLAs just the same)
(*p)[2] = 99; // changes a[1][2]
```
### Multiplicative operators
The binary multiplicative arithmetic operator expressions have the form.
| | | |
| --- | --- | --- |
| lhs `*` rhs | (1) | |
| lhs `/` rhs | (2) | |
| lhs `%` rhs | (3) | |
1) multiplication. lhs and rhs must have [arithmetic types](arithmetic_types "c/language/arithmetic types")
2) division. lhs and rhs must have [arithmetic types](arithmetic_types "c/language/arithmetic types")
3) remainder. lhs and rhs must have [integer types](arithmetic_types "c/language/arithmetic types")
* first, [usual arithmetic conversions](conversion#Usual_arithmetic_conversions "c/language/conversion") are performed. Then...
#### Multiplication
The binary operator \* performs multiplication of its operands (after usual arithmetic conversions) following the usual arithmetic definitions, except that.
* if one operand is a NaN, the result is a NaN
* multiplication of infinity by zero gives NaN and `[FE\_INVALID](../numeric/fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* multiplication of infinity by a nonzero gives infinity (even for complex arguments)
Because in C, any [complex value](arithmetic_types "c/language/arithmetic types") with at least one infinite part is an infinity even if its other part is a NaN, the usual arithmetic rules do not apply to complex-complex multiplication. Other combinations of floating operands follow the following table:
| \* | u | iv | u + iv |
| --- | --- | --- | --- |
| x | xu | i(xv) | (xu) + i(xv) |
| iy | i(yu) | −yv | (−yv) + i(yu) |
| x + iy | (xu) + i(yu) | (−yv) + i(xv) | *special rules* |
Besides infinity handling, complex multiplication is not allowed to overflow intermediate results, except when [`#pragma STDC CX_LIMITED_RANGE`](../preprocessor/impl "c/preprocessor/impl") is set to `ON`, in which case the value may be calculated as if by (x+iy)×(u+iv) = (xu-yv)+i(yu+xv), as the programmer assumes the responsibility of limiting the range of the operands and dealing with the infinities.
Despite disallowing undue overflow, complex multiplication may raise spurious floating-point exceptions (otherwise it is prohibitively difficult to implement non-overflowing versions).
```
#include <stdio.h>
#include <stdio.h>
#include <complex.h>
#include <math.h>
int main(void)
{
// TODO simpler cases, take some from C++
double complex z = (1 + 0*I) * (INFINITY + I*INFINITY);
// textbook formula would give
// (1+i0)(∞+i∞) ⇒ (1×∞ – 0×∞) + i(0×∞+1×∞) ⇒ NaN + I*NaN
// but C gives a complex infinity
printf("%f + i*%f\n", creal(z), cimag(z));
// textbook formula would give
// cexp(∞+iNaN) ⇒ exp(∞)×(cis(NaN)) ⇒ NaN + I*NaN
// but C gives ±∞+i*nan
double complex y = cexp(INFINITY + I*NAN);
printf("%f + i*%f\n", creal(y), cimag(y));
}
```
Possible output:
```
inf + i*inf
inf + i*nan
```
#### Division
The binary operator / divides the first operand by the second (after usual arithmetic conversions) following the usual arithmetics definitions, except that.
* when the type after usual arithmetic conversions is an integer type, the result is the algebraic quotient (not a fraction), rounded in implementation-defined direction (until C99)truncated towards zero (since C99)
* if one operand is a NaN, the result is a NaN
* if the first operand is a complex infinity and the second operand is finite, then the result of the / operator is a complex infinity
* if the first operand is finite and the second operand is a complex infinity, then the result of the / operator is a zero
Because in C, any [complex value](arithmetic_types "c/language/arithmetic types") with at least one infinite part as an infinity even if its other part is a NaN, the usual arithmetic rules do not apply to complex-complex division. Other combinations of floating operands follow the following table:
| / | u | iv |
| --- | --- | --- |
| x | x/u | i(−x/v) |
| iy | i(y/u) | y/v |
| x + iy | (x/u) + i(y/u) | (y/v) + i(−x/v) |
Besides infinity handling, complex division is not allowed to overflow intermediate results, except when [`#pragma STDC CX_LIMITED_RANGE`](../preprocessor/impl "c/preprocessor/impl") is set to `ON`, in which case the value may be calculated as if by (x+iy)/(u+iv) = [(xu+yv)+i(yu-xv)]/(u2
+v2
), as the programmer assumes the responsibility of limiting the range of the operands and dealing with the infinities.
Despite disallowing undue overflow, complex division may raise spurious floating-point exceptions (otherwise it is prohibitively difficult to implement non-overflowing versions).
If the second operand is zero, the behavior is undefined, except that if the IEEE floating-point arithmetic is supported, and the floating-point division is taking place, then.
* Dividing a non-zero number by ±0.0 gives the correctly-signed infinity and `[FE\_DIVBYZERO](../numeric/fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* Dividing 0.0 by 0.0 gives NaN and `[FE\_INVALID](../numeric/fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
#### Remainder
The binary operator % yields the remainder of the division of the first operand by the second (after usual arithmetic conversions).
The sign of the remainder is defined in such a way that if the quotient `a/b` is representable in the result type, then `(a/b)*b + a%b == a`.
If the second operand is zero, the behavior is undefined.
If the quotient `a/b` is not representable in the result type, the behavior of both `a/b` and `a%b` is undefined (that means `INT_MIN%-1` is undefined on 2's complement systems).
Note: the remainder operator does not work on floating-point types, the library function `[fmod](../numeric/math/fmod "c/numeric/math/fmod")` provides that functionality.
### Bitwise logic
The bitwise arithmetic operator expressions have the form.
| | | |
| --- | --- | --- |
| `~` rhs | (1) | |
| lhs `&` rhs | (2) | |
| lhs `|` rhs | (3) | |
| lhs `^` rhs | (4) | |
1) bitwise NOT
2) bitwise AND
3) bitwise OR
4) bitwise XOR where.
| | | |
| --- | --- | --- |
| lhs, rhs | - | expressions of integer type |
First, operators &, ^, and | perform [usual arithmetic conversions](conversion#Usual_arithmetic_conversions "c/language/conversion") on both operands and the operator ~ performs [integer promotions](conversion#Integer_promotions "c/language/conversion") on its only operand.
Then, the corresponding binary logic operators are applied bitwise; that is, each bit of the result is set or cleared according to the logic operation (NOT, AND, OR, or XOR), applied to the corresponding bits of the operands.
Note: bitwise operators are commonly used to manipulate bit sets and bit masks.
Note: for unsigned types (after promotion), the expression ~E is equivalent to the maximum value representable by the result type minus the original value of E.
```
#include <stdio.h>
#include <stdint.h>
int main(void)
{
uint16_t mask = 0x00f0;
uint32_t a = 0x12345678;
printf("Value: %#x mask: %#x\n"
"Setting bits: %#x\n"
"Clearing bits: %#x\n"
"Selecting bits: %#x\n",
a,mask,(a|mask),(a&~mask),(a&mask));
}
```
Possible output:
```
Value: 0x12345678 mask: 0xf0
Setting bits: 0x123456f8
Clearing bits: 0x12345608
Selecting bits: 0x70
```
### Shift operators
The bitwise shift operator expressions have the form.
| | | |
| --- | --- | --- |
| lhs `<<` rhs | (1) | |
| lhs `>>` rhs | (2) | |
1) left shift of lhs by rhs bits
2) right shift of lhs by rhs bits where.
| | | |
| --- | --- | --- |
| lhs, rhs | - | expressions of integer type |
First, [integer promotions](conversion "c/language/conversion") are performed, individually, on each operand (Note: this is unlike other binary arithmetic operators, which all perform usual arithmetic conversions). The type of the result is the type of lhs after promotion.
The behavior is undefined if rhs is negative or is greater or equal the number of bits in the promoted lhs.
For unsigned lhs, the value of `LHS << RHS` is the value of LHS \* 2RHS
, reduced modulo maximum value of the return type plus 1 (that is, bitwise left shift is performed and the bits that get shifted out of the destination type are discarded). For signed lhs with nonnegative values, the value of `LHS << RHS` is LHS \* 2RHS
if it is representable in the promoted type of lhs, otherwise the behavior is undefined.
For unsigned lhs and for signed lhs with nonnegative values, the value of `LHS >> RHS` is the integer part of LHS / 2RHS
. For negative `LHS`, the value of `LHS >> RHS` is implementation-defined where in most implementations, this performs arithmetic right shift (so that the result remains negative). Thus in most implementations, right shifting a signed `LHS` fills the new higher-order bits with the original sign bit (i.e. with 0 if it was non-negative and 1 if it was negative).
```
#include <stdio.h>
enum {ONE=1, TWO=2};
int main(void)
{
char c = 0x10;
unsigned long long ulong_num = 0x123;
printf("0x123 << 1 = %#llx\n"
"0x123 << 63 = %#llx\n" // overflow truncates high bits for unsigned numbers
"0x10 << 10 = %#x\n", // char is promoted to int
ulong_num << 1, ulong_num << 63, c << 10);
long long long_num = -1000;
printf("-1000 >> 1 = %lld\n", long_num >> ONE); // implementation defined
}
```
Possible output:
```
0x123 << 1 = 0x246
0x123 << 63 = 0x8000000000000000
0x10 << 10 = 0x4000
-1000 >> 1 = -500
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.5.3.3 Unary arithmetic operators (p: 64)
+ 6.5.5 Multiplicative operators (p: 66)
+ 6.5.6 Additive operators (p: 66-68)
+ 6.5.7 Bitwise shift operators (p: 68)
+ 6.5.10 Bitwise AND operator (p: 70)
+ 6.5.11 Bitwise exclusive OR operator (p: 70)
+ 6.5.12 Bitwise inclusive OR operator (p: 70-71)
* C11 standard (ISO/IEC 9899:2011):
+ 6.5.3.3 Unary arithmetic operators (p: 89)
+ 6.5.5 Multiplicative operators (p: 92)
+ 6.5.6 Additive operators (p: 92-94)
+ 6.5.7 Bitwise shift operators (p: 94-95)
+ 6.5.10 Bitwise AND operator (p: 97)
+ 6.5.11 Bitwise exclusive OR operator (p: 98)
+ 6.5.12 Bitwise inclusive OR operator (p: 98)
* C99 standard (ISO/IEC 9899:1999):
+ 6.5.3.3 Unary arithmetic operators (p: 79)
+ 6.5.5 Multiplicative operators (p: 82)
+ 6.5.6 Additive operators (p: 82-84)
+ 6.5.7 Bitwise shift operators (p: 84-85)
+ 6.5.10 Bitwise AND operator (p: 87)
+ 6.5.11 Bitwise exclusive OR operator (p: 88)
+ 6.5.12 Bitwise inclusive OR operator (p: 88)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.3.3.3 Unary arithmetic operators
+ 3.3.5 Multiplicative operators
+ 3.3.6 Additive operators
+ 3.3.7 Bitwise shift operators
+ 3.3.10 Bitwise AND operator
+ 3.3.11 Bitwise exclusive OR operator
+ 3.3.12 Bitwise inclusive OR operator
### See also
[Operator precedence](operator_precedence "c/language/operator precedence").
| Common operators |
| --- |
| [assignment](operator_assignment "c/language/operator assignment") | [incrementdecrement](operator_incdec "c/language/operator incdec") | **arithmetic** | [logical](operator_logical "c/language/operator logical") | [comparison](operator_comparison "c/language/operator comparison") | [memberaccess](operator_member_access "c/language/operator member access") | [other](operator_other "c/language/operator other") |
| `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b`. | `a[b] *a &a a->b a.b`. | `a(...) a, b (type) a ? : sizeof _Alignof` (since C11). |
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_arithmetic "cpp/language/operator arithmetic") for Arithmetic operators |
| programming_docs |
c History of C History of C
============
Early C
--------
* 1969: B created, based on BCPL, to replace PDP-7 assembler as the system programming language for Unix
+ added operators `++`, `--`, compound assignment, remained a typeless language like BCPL
* 1971: NB ("new B") created when porting B to PDP-11
+ types (`int`, `char`, arrays and pointers), array-to-pointer conversion, compilation to machine code
* 1972: Language renamed to C
+ `struct`, operators `&&` and `||`, preprocessor, portable I/O
* 1973: Unix re-written in C
+ `unsigned`, `long`, `union`, enumerations, increased type safety
* 1978: The C Programming Language, 1st edition
Standard C
-----------
* 1983: ANSI established X3J11 committee
* 1988: The C Programming Language, 2nd edition
* 1989: **C89**, the ANSI C standard published
1. codified existing practices
2. new features: `volatile`, `enum`, `signed`, `void`, locales
3. From C++: `const`, function prototypes
* 1990: **C90**, the ANSI C standard accepted as ISO/IEC 9899:1990
* 1994: Technical corrigendum 1 (ISO/IEC 9899:1990/Cor.1:1994)
+ [44 small changes](https://open-std.org/JTC1/SC22/WG14/www/docs/tc1.htm)
* 1995: **C95** (ISO/IEC 9899:1990/Amd.1:1995) ([online store](https://infostore.saiglobal.com/store/Details.aspx?DocN=isoc000767513))
1. greatly expanded wide and multibyte character support (`<wctype.h>`, `<wchar.h>`, additions and changes to stream I/O, etc)
2. digraphs, `<iso646.h>`,
* 1996: Technical corrigendum 2 (ISO/IEC 9899:1990/Cor.2:1996)
+ [24 small changes](https://open-std.org/JTC1/SC22/WG14/www/docs/tc2.htm)
* 1999: **C99** (ISO/IEC 9899:1999)
1. new features: `bool`, `long long`, `<stdint.h>`, `<inttypes.h>`, `restrict`, compound literals, variable length arrays, flexible array members, designated initializers, `<fenv.h>`, variadic macros, complex numbers, `__func__`, hexadecimal floating point format (`%a`), monetary formatting in `[lconv](../locale/lconv "c/locale/lconv")`, `[isblank](../string/byte/isblank "c/string/byte/isblank")`, concatenation of narrow and wide string literals, trailing comma in enumerations, empty arguments in function-like macros, `STDC_*` pragmas, `va_copy`, null return of `[tmpnam](../io/tmpnam "c/io/tmpnam")`, null pointer in `[setvbuf](../io/setvbuf "c/io/setvbuf")`, `hh` and `ll` length-specifiers in `[printf](../io/fprintf "c/io/fprintf")`, `[snprintf](../io/fprintf "c/io/fprintf")`, `[\_Exit](../program/_exit "c/program/ Exit")`, `<tgmath.h>`, POSIX-like `[strftime](../chrono/strftime "c/chrono/strftime")` specifiers
2. from C++: `inline`, mix declarations and code, declarations in the init-clause of the for loop, `//` comments, universal character names in source code
3. removed implicit functions and implicit `int`
* 2001: Technical corrigendum 1 (ISO/IEC 9899:1999/Cor.1:2001)
+ [11 defects fixed](https://open-std.org/JTC1/SC22/WG14/www/docs/9899tc1/.)
* 2004: Technical corrigendum 2 (ISO/IEC 9899:1999/Cor.2:2004)
* 2004: Unicode TR (ISO/IEC TR 19769:2004) ([ISO store](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=33907)) ([N1040](https://open-std.org/JTC1/SC22/WG14/www/docs/n1040.pdf) November 7, 2003 draft)
* 2007: Technical corrigendum 3 (ISO/IEC 9899:1999/Cor.3:2007) ([N1256](https://open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf) September 7, 2007 draft)
+ deprecated `[gets](../io/gets "c/io/gets")`
* 2007: Bounds-checking interfaces TR (ISO/IEC TR 24731-1:2007) ([ISO store](https://www.iso.org/iso/catalogue_detail.htm?csnumber=38841)) ([N1225](https://open-std.org/JTC1/SC22/WG14/www/docs/n1225.pdf) March 28, 2007 draft)
* 2008: Embedded TR (ISO/IEC TR 18037:2008) ([ISO store](https://www.iso.org/iso/catalogue_detail.htm?csnumber=51126)) ([N1021](https://open-std.org/JTC1/SC22/WG14/www/docs/n1021.pdf) September 24, 2003 draft)
* 2009: Decimal floating-point TR (ISO/IEC TR 24732:2009) ([ISO store](https://www.iso.org/iso/catalogue_detail.htm?csnumber=38842)) ([N1241](https://open-std.org/JTC1/SC22/WG14/www/docs/n1241.pdf) July 5, 2007 draft)
* 2009: Mathematical special functions TR (ISO/IEC TR 24747:2009) ([ISO store](https://www.iso.org/iso/catalogue_detail.htm?csnumber=38857)) ([N1182](https://open-std.org/JTC1/SC22/WG14/www/docs/n1182.pdf) August 2, 2006 draft)
* 2010: Dynamic allocations functions TR (ISO/IEC TR 24731-2:2010) ([ISO store](https://www.iso.org/iso/catalogue_detail.htm?csnumber=51678)) ([N1388](https://open-std.org/JTC1/SC22/WG14/www/docs/n1388.pdf) June 1, 2009 draft)
* 2011: **C11** (ISO/IEC 9899:2011) ([ISO store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=57853)) ([ANSI store](https://webstore.ansi.org/RecordDetail.aspx?sku=INCITS%2fISO%2fIEC+9899-2012#.UGCvLIHyaHM)) ([N1570](https://open-std.org/JTC1/SC22/WG14/www/docs/n1570.pdf) April 12, 2011 draft)
1. thread-aware memory model, `<stdatomic.h>`, `<threads.h>`, type-generic functions, `alignas`/`alignof`, `noreturn`, `static_assert`, analyzability extensions, extensions to complex and imaginary types, anonymous structures and unions, exclusive file open mode, `[quick\_exit](../program/quick_exit "c/program/quick exit")`
2. removed `[gets](../io/gets "c/io/gets")`
3. from Bounds-checking interfaces TR: bounds-checking interfaces,
4. from Unicode TR: `char16_t`, `char32_t`, and `<uchar.h>`
* 2012: Technical corrigendum 1 (ISO/IEC 9899:2011/Cor 1:2012) ([ISO store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=61717))
+ Fixes [DR 411](https://open-std.org/JTC1/SC22/WG14/www/docs/n2244.htm#dr_411)
* 2013: Secure Coding Rules TS (ISO/IEC TS 17961:2013) ([ISO store](https://www.iso.org/iso/catalogue_detail.htm?csnumber=61134)) ([N1718](https://open-std.org/JTC1/SC22/WG14/www/docs/n1718.pdf) May 30, 2013)
* 2014: FP TS part 1: Binary floating-point arithmetic (ISO/IEC TS 18661-1:2014) ([ISO store](https://www.iso.org/iso/catalogue_detail.htm?csnumber=63146)) ([N1778](https://open-std.org/JTC1/SC22/WG14/www/docs/n1778.pdf) 2013 draft)
1. provides changes to C11 (mostly to Annex F) that cover all basic requirements and some recommendations of IEC 60559:2011 (C11 was built on IEC 60559:1989)
* 2015: FP TS part 2: Decimal floating-point arithmetic (ISO/IEC TS 18661-2:2015) ([ISO store](https://www.iso.org/iso/home/store/catalogue_ics/catalogue_detail_ics.htm?csnumber=68882)) ([N1912](https://open-std.org/JTC1/SC22/WG14/www/docs/n1912.pdf) 2015 draft)
1. provides changes to C11 to support all the requirements, plus some basic recommendations, of IEC 60559:2011 for decimal floating-point arithmetic. This supersedes ISO/IEC TR 24732:2009.
* 2015: FP TS part 3: Interchange and extended types (ISO/IEC TS 18661-3:2015) ([ISO store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=65615)) ([N1945](https://open-std.org/JTC1/SC22/WG14/www/docs/n1945.pdf) 2015 draft)
1. provides changes to C11 to support the recommendations of IEC 60559:2011 for extended floating‐point formats and the interchange formats, both arithmetic and non-arithmetic.
* 2015: FP TS part 4: Supplementary functions (ISO/IEC TS 18661-4:2015) ([ISO store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=65616)) ([N1950](https://open-std.org/JTC1/SC22/WG14/www/docs/n1950.pdf) 2015 draft)
1. provides changes to C11 to support all mathematical operations recommended by IEC 60559:2011, including trigonometry in π units, inverse square root, compounded interest, etc.
* 2016: FP TS part 5: Supplementary attributes (ISO/IEC TS 18661-5:2016) ([ISO store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=65617)) ([N2004](https://open-std.org/JTC1/SC22/WG14/www/docs/n2004.pdf) 2016 draft)
1. provides changes to C11 to support all supplementary attributes (evaluation model, exception handling, reproducibility, etc) recommended by IEC 60559:2011
* 2018: **C17** (ISO/IEC 9899:2018) ([ISO Store](https://www.iso.org/standard/74528.html)) ([Final draft](https://files.lhmouse.com/standards/ISO%20C%20N2176.pdf))
[Main Article: C17](../17 "c/17")
| Defect Reports fixed in C17 (54 defects) |
| --- |
| * [DR 400](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_400)
* [DR 401](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_401)
* [DR 402](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_402)
* [DR 403](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_403)
* [DR 404](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_404)
* [DR 405](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_405)
* [DR 406](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_406)
* [DR 407](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_407)
* [DR 410](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_410)
* [DR 412](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_412)
* [DR 414](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_414)
* [DR 415](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_415)
* [DR 416](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_416)
* [DR 417](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_417)
* [DR 419](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_419)
* [DR 423](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_423)
* [DR 426](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_426)
* [DR 428](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_428)
* [DR 429](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_429)
* [DR 430](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_430)
* [DR 431](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_431)
* [DR 433](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_433)
* [DR 434](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_434)
* [DR 436](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_436)
* [DR 437](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_437)
* [DR 438](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_438)
* [DR 439](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_439)
* [DR 441](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_441)
* [DR 444](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_444)
* [DR 445](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_445)
* [DR 447](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_447)
* [DR 448](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_448)
* [DR 450](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_450)
* [DR 452](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_452)
* [DR 453](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_453)
* [DR 457](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_457)
* [DR 458](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_458)
* [DR 459](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_459)
* [DR 460](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_460)
* [DR 462](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_462)
* [DR 464](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_464)
* [DR 465](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_465)
* [DR 468](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_468)
* [DR 470](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_470)
* [DR 471](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_471)
* [DR 472](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_472)
* [DR 473](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_473)
* [DR 475](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_475)
* [DR 477](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_477)
* [DR 480](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_480)
* [DR 481](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_481)
* [DR 485](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_485)
* [DR 487](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_487)
* [DR 491](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_491)
|
### Future development
* Parallelism TS (Draft [N2017](https://open-std.org/JTC1/SC22/WG14/www/docs/n2017.pdf) 2016-03-10)
* Transactional Memory TS (Draft [N1961](https://open-std.org/JTC1/SC22/WG14/www/docs/n1961.pdf) 2015-09-23)
* **C23** (Latest draft [n3054](https://open-std.org/JTC1/SC22/WG14/www/docs/n3054.pdf) 2022-09-03)
1. List of issues that were not granted DR status: ([N2556](https://open-std.org/JTC1/SC22/WG14/www/docs/n2556.pdf) 2020-08-02)
[Main Article: C23](../23 "c/23")
Next major C language standard revision
| Defect Reports fixed in C23 (? defects) |
| --- |
| * [DR 440](https://open-std.org/JTC1/SC22/WG14/www/docs/n2379.htm)
* [DR 432](https://open-std.org/JTC1/SC22/WG14/www/docs/n2326.htm)
* [DR 467](https://open-std.org/JTC1/SC22/WG14/www/docs/n2326.htm)
* [DR 476](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_476)
* [DR 482](https://open-std.org/JTC1/SC22/WG14/www/docs/n2324.htm)
* [DR 488](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_488)
* [DR 489](https://open-std.org/JTC1/SC22/WG14/www/docs/n2713.htm)
* [DR 494](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_494)
* [DR 496](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_496)
* [DR 497](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_497)
* [DR 499](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_499)
* [DR 500](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_500)
* [DR 501](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_501)
|
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/history "cpp/language/history") for History of C++ |
### External links
* [The Development of the C Language](https://www.bell-labs.com/usr/dmr/www/chist.html) by Dennis M. Ritchie
* [Rationale for the C99 standard](https://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf)
c cast operator cast operator
=============
Performs explicit type conversion.
### Syntax
| | | |
| --- | --- | --- |
| `(` type-name `)` expression | | |
where.
| | | |
| --- | --- | --- |
| type-name | - | either the type `void` or any [scalar type](type#Type_groups "c/language/type") |
| expression | - | any [expression](expressions "c/language/expressions") of [scalar type](type#Type_groups "c/language/type") (unless type-name is void, in which case it can be anything) |
### Explanation
If type-name is `void`, then expression is evaluated for its side-effects and its returned value is discarded, same as when expression is used on its own, as an [expression statement](statements#Expression_statements "c/language/statements").
Otherwise, if type-name is exactly the type of expression, nothing is done (except that if expression has floating type and is represented with greater range and precision than its type indicates -- see below).
Otherwise, the value of expression is converted to the type named by type-name, as follows:
Every [implicit conversion as if by assignment](conversion "c/language/conversion") is allowed.
In addition to the implicit conversions, the following conversions are allowed:
* Any integer can be cast to any pointer type. Except for the null pointer constants such as `[NULL](../types/null "c/types/NULL")` (which [doesn't need a cast](conversion "c/language/conversion")), the result is implementation-defined, may not be correctly aligned, may not point to an object of the referenced type, and may be a [trap representation](object "c/language/object").
* Any pointer type can be cast to any integer type. The result is implementation-defined, even for null pointer values (they do not necessarily result in the value zero). If the result cannot be represented in the target type, the behavior is undefined (unsigned integers do not implement modulo arithmetic on a cast from pointer)
* Any pointer to object can be cast to any other pointer to object. If the value is not correctly aligned for the target type, the behavior is undefined. Otherwise, if the value is converted back to the original type, it compares equal to the original value. If a pointer to object is cast to pointer to any character type, the result points at the lowest byte of the object and may be incremented up to sizeof the target type (in other words, can be used to examine [object representation](object "c/language/object") or to make a copy via `[memcpy](../string/byte/memcpy "c/string/byte/memcpy")` or `[memmove](../string/byte/memmove "c/string/byte/memmove")`).
* Any pointer to function can be cast to a pointer to any other function type. If the resulting pointer is converted back to the original type, it compares equal to the original value. If the converted pointer is used to make a function call, the behavior is undefined (unless the function types are [compatible](type#Compatible_types "c/language/type"))
* When casting between pointers (either object or function), if the original value is a null pointer value of its type, the result is the correct null pointer value for the target type.
In any case (both when executing an implicit conversion and in the same-type cast), if expression and type-name are floating types and expression is represented with greater range and precision than its type indicates (see `[FLT\_EVAL\_METHOD](../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")`, the range and precision are stripped off to match the target type.
The [value category](value_category "c/language/value category") of the cast expression is always non-lvalue.
### Notes
Because [`const`](const "c/language/const"), [`volatile`](volatile "c/language/volatile"), [`restrict`](restrict "c/language/restrict"), and [`_Atomic`](atomic "c/language/atomic") qualifiers have effect on [lvalues](value_category "c/language/value category") only, a cast to a cvr-qualified or atomic type is exactly equivalent to the cast to the corresponding unqualified type.
The cast to `void` is sometimes useful to silence compiler warnings about unused results.
The conversions not listed here are not allowed. In particular,
* there are no conversions between pointers and floating types
* there are no conversions between pointers to functions and pointers to objects (including `void*`)
| | |
| --- | --- |
| If the implementation provides `[intptr\_t](../types/integer "c/types/integer")` and/or `[uintptr\_t](../types/integer "c/types/integer")`, then a cast from a pointer to an object type (including *cv* `void`) to these types is always well-defined. However, this is not guaranteed for a function pointer. | (since C99) |
Note that conversions between function pointers and object pointers are accepted as extensions by many compilers, and expected by some usages of [POSIX `dlsym()` function](https://pubs.opengroup.org/onlinepubs/9699919799/functions/dlsym.html).
### Example
```
#include <stdio.h>
int main(void)
{
// examining object representation is a legitimate use of cast
double d = 3.14;
printf("The double %.2f(%a) is: ", d, d);
for(size_t n = 0; n < sizeof d; ++n)
printf("0x%02x ", ((unsigned char*)&d)[n]);
// edge cases
struct S {int x;} s;
// (struct S)s; // error; not a scalar type
// even though casting to the same type does nothing
(void)s; // okay to cast any type to void
}
```
Possible output:
```
The double 3.14(0x1.91eb851eb851fp+1) is: 0x1f 0x85 0xeb 0x51 0xb8 0x1e 0x09 0x40
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.5.4 Cast operators (p: 65-66)
* C11 standard (ISO/IEC 9899:2011):
+ 6.5.4 Cast operators (p: 91)
* C99 standard (ISO/IEC 9899:1999):
+ 6.5.4 Cast operators (p: 81)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.3.4 Cast operators
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/explicit_cast "cpp/language/explicit cast") for explicit type conversion |
| programming_docs |
c Alternative operators and tokens Alternative operators and tokens
================================
C source code may be written in any 8-bit character set that includes the [ISO 646:1983](https://en.wikipedia.org/wiki/ISO_646 "enwiki:ISO 646") invariant character set, even non-ASCII ones. However, several C operators and punctuators require characters that are outside of the ISO 646 codeset: `{, }, [, ], #, \, ^, |, ~`. To be able to use character encodings where some or all of these symbols do not exist (such as the German [DIN 66003](http://de.wikipedia.org/wiki/DIN_66003)), there are two possibilities: alternative spellings of operators that use these characters or special combinations of two or three ISO 646 compatible characters that are interpreted as if they were a single non-ISO 646 character.
Operator macros(C95)
---------------------
There are alternative spellings for the operators that use non-ISO646 characters, defined in `<iso646.h>` as macros:
| Defined in header `<iso646.h>` |
| --- |
| Primary | Alternative |
| `&&` | `and` (operator macro) |
| `&=` | `and_eq` (operator macro) |
| `&` | `bitand` (operator macro) |
| `|` | `bitor` (operator macro) |
| `~` | `compl` (operator macro) |
| `!` | `not` (operator macro) |
| `!=` | `not_eq` (operator macro) |
| `||` | `or` (operator macro) |
| `|=` | `or_eq` (operator macro) |
| `^` | `xor` (operator macro) |
| `^=` | `xor_eq` (operator macro) |
The characters `&` and `!` are invariant under ISO-646, but alternatives are provided for the operators that use these characters anyway to accommodate even more restrictive historical charsets.
There is no alternative spelling (such as `eq`) for the equality operator `==` because the character `=` was present in all supported charsets.
Alternative tokens(C95)
------------------------
The following alternative tokens are part of the core language, and, in all respects of the language, each alternative token behaves exactly the same as its primary token, except for its spelling (the [stringification operator](../preprocessor/replace "c/preprocessor/replace") can make the spelling visible). The two-letter alternative tokens are sometimes called "digraphs"
| Primary | Alternative |
| --- | --- |
| `{` | `<%` |
| } | `%>` |
| `[` | `<:` |
| `]` | `:>` |
| `#` | `%:` |
| `##` | `%:%:` |
Trigraphs
----------
The following three-character groups (trigraphs) are [parsed before comments and string literals are recognized](translation_phases "c/language/translation phases"), and each appearance of a trigraph is replaced by the corresponding primary character:
| Primary | Trigraph |
| --- | --- |
| `{` | `??<` |
| } | `??>` |
| `[` | `??(` |
| `]` | `??)` |
| `#` | `??=` |
| `\` | `??/` |
| `^` | `??'` |
| `|` | `??!` |
| `~` | `??-` |
Because trigraphs are processed early, a comment such as `// Will the next line be executed?????/` will effectively comment out the following line, and the string literal such as `"What's going on??!"` is parsed as `"What's going on|"`.
### Example
The following example demonstrates alternative operator spellings from the `<iso646.h>` header as well as use of digraphs and trigraphs. The space character in the first command-line argument, argv[1], requires the quotation marks: ", World!".
```
%:include <stdlib.h>
%:include <stdio.h>
%:include <iso646.h>
int main(int argc, char** argv)
??<
if (argc > 1 and argv<:1:> not_eq NULL)
<%
printf("Hello%s\n", argv<:1:>);
%>
return EXIT_SUCCESS;
??>
```
Possible output:
```
Hello, World!
```
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_alternative "cpp/language/operator alternative") for Alternative operator representations |
c Scalar initialization Scalar initialization
=====================
When [initializing](initialization "c/language/initialization") an object of [scalar type](type#Type_groups "c/language/type"), the initializer must be a single expression.
The initializer for a scalar (an object of integer type including booleans and enumerated types, floating type including complex and imaginary, and pointer type including pointer to function) must be a single expression, optionally enclosed in braces, or an empty initializer (since C23):
| | | |
| --- | --- | --- |
| `=` expression | (1) | |
| `=` `{` expression `}` | (2) | |
| `=` `{` `}` | (3) | (since C23) |
1,2) The expression is evaluated, and its value, after [conversion as if by assignment](conversion "c/language/conversion") to the type of the object, becomes the initial value of the object being initialized.
3) The object is [empty-initialized](initialization#Empty_initialization "c/language/initialization"), i.e. initialized to numeric zero for an object of an arithmetic or enumeration type, or null pointer value for an object of a pointer type. ### Notes
Because of the rules that apply to conversions as if by assignment, [`const`](const "c/language/const") and [`volatile`](volatile "c/language/volatile") qualifiers on the declared type are ignored when determining which type to convert the expression to.
See [initialization](initialization "c/language/initialization") for the rules that apply when no initializer is used.
As with all other initializations, expression must be a [constant expression](constant_expression "c/language/constant expression") when initializing objects of static or thread-local [storage duration](storage_duration "c/language/storage duration").
The expression cannot be a [comma operator](operator_other#Comma_operator "c/language/operator other") (unless parenthesized) because the comma at the top level would be interpreted as the beginning of the next declarator.
When initializing objects of floating-point type, all computations for the objects with automatic [storage duration](storage_duration "c/language/storage duration") are done as-if at execution time and are affected by the [current rounding](../numeric/fenv/fe_round "c/numeric/fenv/FE round"); floating-point errors are reported as specified in [`math_errhandling`](../numeric/math/math_errhandling "c/numeric/math/math errhandling"). For objects of static and thread-local storage duration, computations are done as-if at compile time, and no exceptions are raised:
```
void f(void)
{
#pragma STDC FENV_ACCESS ON
static float v = 1.1e75; // does not raise exceptions: static init
float u[] = { 1.1e75 }; // raises FE_INEXACT
float w = 1.1e75; // raises FE_INEXACT
double x = 1.1e75; // may raise FE_INEXACT (depends on FLT_EVAL_METHOD)
float y = 1.1e75f; // may raise FE_INEXACT (depends on FLT_EVAL_METHOD)
long double z = 1.1e75; // does not raise exceptions (conversion is exact)
}
```
### Example
```
#include <stdbool.h>
int main(void)
{
bool b = true;
const double d = 3.14;
int k = 3.15; // conversion from double to int
int n = {12}, // optional braces
*p = &n, // non-constant expression OK for automatic variable
(*fp)(void) = main;
enum {RED, BLUE} e = RED; // enumerations are scalar types as well
}
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.9/11 Initialization (p: 101)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.9/11 Initialization (p: 140)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.8/11 Initialization (p: 126)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 6.5.7 Initialization
c Value categories Value categories
================
Each [expression](expressions "c/language/expressions") in C (an operator with its arguments, a function call, a constant, a variable name, etc) is characterized by two independent properties: a [type](type#Type "c/language/type") and a [value category](expressions#General "c/language/expressions").
Every expression belongs to one of three value categories: lvalue, non-lvalue object (rvalue), and function designator.
### Lvalue expressions
Lvalue expression is any expression with [object type](type#Type_groups "c/language/type") other than the type `void`, which potentially designates an [object](object "c/language/object") (the behavior is undefined if an lvalue does not actually designate an object when it is evaluated). In other words, lvalue expression evaluates to the *object identity*. The name of this value category ("left value") is historic and reflects the use of lvalue expressions as the left-hand operand of the assignment operator in the CPL programming language.
Lvalue expressions can be used in the following *lvalue contexts*:
* as the operand of the [address-of operator](operator_member_access "c/language/operator member access") (except if the lvalue designates a [bit field](bit_field "c/language/bit field") or was declared [register](storage_duration "c/language/storage duration")).
* as the operand of the pre/post [increment and decrement operators](operator_incdec "c/language/operator incdec").
* as the left-hand operand of the [member access](operator_member_access "c/language/operator member access") (dot) operator.
* as the left-hand operand of the [assignment and compound assignment](operator_assignment "c/language/operator assignment") operators.
If an lvalue expression is used in any context other than [`sizeof`](sizeof "c/language/sizeof"), [`_Alignof`](_alignof "c/language/ Alignof"), or the operators listed above, non-array lvalues of any complete type undergo [lvalue conversion](conversion "c/language/conversion"), which models the memory load of the value of the object from its location. Similarly, array lvalues undergo [array-to-pointer conversion](conversion "c/language/conversion") when used in any context other than `sizeof`, `_Alignof`, address-of operator, or array initialization from a string literal.
The semantics of [`const`](const "c/language/const")/[`volatile`](volatile "c/language/volatile")/[`restrict`](restrict "c/language/restrict")-qualifiers and [atomic](atomic "c/language/atomic") types apply to lvalues only (lvalue conversion strips the qualifiers and removes atomicity).
The following expressions are lvalues:
* identifiers, including function named parameters, provided they were declared as designating objects (not functions or enumeration constants)
* [string literals](string_literal "c/language/string literal")
* (C99) [compound literals](compound_literal "c/language/compound literal")
* parenthesized expression if the unparenthesized expression is an lvalue
* the result of a member access (dot) operator if its left-hand argument is lvalue
* the result of a member access through pointer `->` operator
* the result of the indirection (unary `*`) operator applied to a pointer to object
* the result of the subscription operator (`[]`)
#### Modifiable lvalue expressions
A *modifiable lvalue* is any lvalue expression of complete, non-array type which is not [const](const "c/language/const")-qualified, and, if it's a struct/union, has no members that are [const](const "c/language/const")-qualified, recursively.
Only modifiable lvalue expressions may be used as arguments to increment/decrement, and as left-hand arguments of assignment and compound assignment operators.
### Non-lvalue object expressions
Colloquially known as *rvalues*, non-lvalue object expressions are the expressions of object types that do not designate objects, but rather values that have no object identity or storage location. The address of a non-lvalue object expression cannot be taken.
The following expressions are non-lvalue object expressions:
* integer, character, and floating constants
* all operators not specified to return lvalues, including
+ any function call expression
+ any cast expression (note that compound literals, which look similar, are lvalues)
+ member access operator (dot) applied to a non-lvalue structure/union, `f().x`, `(x,s1).a`, `(s1=s2).m`
+ all arithmetic, relational, logical, and bitwise operators
+ increment and decrement operators (note: pre- forms are lvalues in C++)
+ assignment and compound assignment operators (note: they are lvalues in C++)
+ the conditional operator (note: may be lvalue in C++)
+ the comma operator (note: may be lvalue in C++)
+ the address-of operator, even it if is neutralized by being applied to the result of the unary `*` operator
As a special case, expressions of type `void` are assumed to be non-lvalue object expressions that yield a value which has no representation and requires no storage.
Note that a struct/union rvalue that has a member (possibly nested) of array type does in fact designate an object with [temporary lifetime](lifetime "c/language/lifetime"). This object can be accessed through lvalue expressions that form by indexing the array member or by indirection through the pointer obtained by array-to-pointer conversion of the array member.
### Function designator expression
A function designator (the identifier introduced by a [function declaration](function_declaration "c/language/function declaration")) is an expression of function type. When used in any context other than the address-of operator, [`sizeof`](sizeof "c/language/sizeof"), and [`_Alignof`](_alignof "c/language/ Alignof") (the last two generate compile errors when applied to functions), the function designator is always converted to a non-lvalue pointer to function. Note that the function-call operator is defined for pointers to functions and not for function designators themselves.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.3.2.1 Lvalues, arrays, and function designators (p: 40)
* C11 standard (ISO/IEC 9899:2011):
+ 6.3.2.1 Lvalues, arrays, and function designators (p: 54-55)
* C99 standard (ISO/IEC 9899:1999):
+ 6.3.2.1 Lvalues, arrays, and function designators (p: 46)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.2.2.1 Lvalues and function designators
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/value_category "cpp/language/value category") for Value categories |
c Logical operators Logical operators
=================
Logical operators apply standard boolean algebra operations to their operands.
| Operator | Operator name | Example | Result |
| --- | --- | --- | --- |
| `!` | logical NOT | `!a` | the logical negation of **a** |
| `&&` | logical AND | `a && b` | the logical AND of **a** and **b** |
| `||` | logical OR | `a || b` | the logical OR of **a** and **b** |
### Logical NOT
The logical NOT expression has the form.
| | | |
| --- | --- | --- |
| `!` expression | | |
where.
| | | |
| --- | --- | --- |
| expression | - | an expression of any [scalar type](type#Type_groups "c/language/type") |
The logical NOT operator has type `int`. Its value is `0` if expression evaluates to a value that compares unequal to zero. Its value is `1` if expression evaluates to a value that compares equal to zero. (so `!E` is the same as `(0==E)`).
```
#include <stdbool.h>
#include <stdio.h>
#include <ctype.h>
int main(void)
{
bool b = !(2+2 == 4); // not true
printf("!(2+2==4) = %s\n", b ? "true" : "false");
int n = isspace('a'); // zero if 'a' is a space, nonzero otherwise
int x = !!n; // "bang-bang", common C idiom for mapping integers to [0,1]
// (all non-zero values become 1)
char *a[2] = {"nonspace", "space"};
printf("%s\n", a[x]); // now x can be safely used as an index to array of 2 ints
}
```
Output:
```
!(2+2==4) = false
nonspace
```
### Logical AND
The logical AND expression has the form.
| | | |
| --- | --- | --- |
| lhs `&&` rhs | | |
where.
| | | |
| --- | --- | --- |
| lhs | - | an expression of any scalar type |
| rhs | - | an expression of any scalar type, which is only evaluated if lhs does not compare equal to `0` |
The logical-AND operator has type `int` and the value `1` if both lhs and rhs compare unequal to zero. It has the value `0` otherwise (if either lhs or rhs or both compare equal to zero).
There is a [sequence point](eval_order "c/language/eval order") after the evaluation of lhs. If the result of lhs compares equal to zero, then rhs is not evaluated at all (so-called *short-circuit evaluation*).
```
#include <stdbool.h>
#include <stdio.h>
int main(void)
{
bool b = 2+2==4 && 2*2==4; // b == true
1 > 2 && puts("this won't print");
char *p = "abc";
if(p && *p) // common C idiom: if p is not null
// AND if p does not point at the end of the string
{ // (note that thanks to short-circuit evaluation, this
// will not attempt to dereference a null pointer)
// ... // ... then do some string processing
}
}
```
### Logical OR
The logical OR expression has the form.
| | | |
| --- | --- | --- |
| lhs `||` rhs | | |
where.
| | | |
| --- | --- | --- |
| lhs | - | an expression of any scalar type |
| rhs | - | an expression of any scalar type, which is only evaluated if lhs compares equal to `0` |
The logical-OR operator has type `int` and the value `1` if either lhs or rhs compare unequal to zero. It has value `0` otherwise (if both lhs and rhs compare equal to zero).
There is a [sequence point](eval_order "c/language/eval order") after the evaluation of lhs. If the result of lhs compares unequal to zero, then rhs is not evaluated at all (so-called *short-circuit evaluation*).
```
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(void)
{
bool b = 2+2 == 4 || 2+2 == 5; // true
printf("true or false = %s\n", b ? "true" : "false");
// logical OR can be used simialar to perl's "or die", as long as rhs has scalar type
fopen("test.txt", "r") || printf("could not open test.txt: %s\n", strerror(errno));
}
```
Possible output:
```
true or false = true
could not open test.txt: No such file or directory
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 6.5.3.3 Unary arithmetic operators (p: 89)
+ 6.5.13 Logical AND operator (p: 99)
+ 6.5.14 Logical OR operator (p: 99)
* C99 standard (ISO/IEC 9899:1999):
+ 6.5.3.3 Unary arithmetic operators (p: 79)
+ 6.5.13 Logical AND operator (p: 89)
+ 6.5.14 Logical OR operator (p: 89)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.3.3.3 Unary arithmetic operators
+ 3.3.13 Logical AND operator
+ 3.3.14 Logical OR operator
### See Also
[Operator precedence](operator_precedence "c/language/operator precedence").
| Common operators |
| --- |
| [assignment](operator_assignment "c/language/operator assignment") | [incrementdecrement](operator_incdec "c/language/operator incdec") | [arithmetic](operator_arithmetic "c/language/operator arithmetic") | **logical** | [comparison](operator_comparison "c/language/operator comparison") | [memberaccess](operator_member_access "c/language/operator member access") | [other](operator_other "c/language/operator other") |
| `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b`. | `a[b] *a &a a->b a.b`. | `a(...) a, b (type) a ? : sizeof _Alignof` (since C11). |
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_logical "cpp/language/operator logical") for Logical operators |
c External and tentative definitions External and tentative definitions
==================================
At the top level of a [translation unit](translation_phases "c/language/translation phases") (that is, a source file with all the #includes after the preprocessor), every C program is a sequence of [declarations](declarations "c/language/declarations"), which declare functions and objects with [external or internal linkage](storage_duration "c/language/storage duration"). These declarations are known as *external declarations* because they appear outside of any function.
```
extern int n; // external declaration with external linkage
int b = 1; // external definition with external linkage
static const char *c = "abc"; // external definition with internal linkage
int f(void) { // external definition with external linkage
int a = 1; // non-external
return b;
}
static void x(void) { // external definition with internal linkage
}
```
Objects declared with an external declaration have static [storage duration](storage_duration "c/language/storage duration"), and as such cannot use `auto` or `register` specifiers. The identifiers introduced by external declarations have [file scope](scope "c/language/scope").
### Tentative definitions
A *tentative definition* is an external declaration without an initializer, and either without a [storage-class specifier](storage_duration "c/language/storage duration") or with the specifier `static`.
A *tentative definition* is a declaration that may or may not act as a definition. If an actual external definition is found earlier or later in the same translation unit, then the tentative definition just acts as a declaration.
```
int i1 = 1; // definition, external linkage
int i1; // tentative definition, acts as declaration because i1 is defined
extern int i1; // declaration, refers to the earlier definition
extern int i2 = 3; // definition, external linkage
int i2; // tentative definition, acts as declaration because i2 is defined
extern int i2; // declaration, refers to the external linkage definition
```
If there are no definitions in the same translation unit, then the tentative definition acts as an actual definition that [zero-initializes](initialization#Zero_initialization "c/language/initialization") the object.
```
int i3; // tentative definition, external linkage
int i3; // tentative definition, external linkage
extern int i3; // declaration, external linkage
// in this translation unit, i3 is defined as if by "int i3 = 0;"
```
Unlike the [extern](storage_duration "c/language/storage duration") declarations, which don't change the linkage of an identifier if a previous declaration established it, tentative definitions may disagree in linkage with another declaration of the same identifier. If two declarations for the same identifier are in scope and have different linkage, the behavior is undefined:
```
static int i4 = 2; // definition, internal linkage
int i4; // Undefined behavior: linkage disagreement with previous line
extern int i4; // declaration, refers to the internal linkage definition
static int i5; // tentative definition, internal linkage
int i5; // Undefined behavior: linkage disagreement with previous line
extern int i5; // refers to previous, whose linkage is internal
```
A tentative definition with internal linkage must have complete type.
```
static int i[]; // Error, incomplete type in a static tentative definition
int i[]; // OK, equivalent to int i[1] = {0}; unless redeclared later in this file
```
### One definition rule
Each translation unit may have zero or one external definition of every identifier with [internal linkage](storage_duration "c/language/storage duration") (a `static` global).
If an identifier with internal linkage is used in any expression other than a non-VLA, (since C99) [`sizeof`](sizeof "c/language/sizeof"), or [`_Alignof`](_alignof "c/language/ Alignof") (since C11), there must be one and only one external definition for that identifier in the translation unit.
The entire program may have zero or one external definition of every identifier with [external linkage](storage_duration "c/language/storage duration").
If an identifier with external linkage is used in any expression other than a non-VLA, (since C99) [`sizeof`](sizeof "c/language/sizeof"), or [`_Alignof`](_alignof "c/language/ Alignof") (since C11), there must be one and only one external definition for that identifier somewhere in the entire program.
### Notes
| | |
| --- | --- |
| Inline definitions in different translation units are not constrained by one definition rule. See [`inline`](inline "c/language/inline") for the details on the inline function definitions. | (since C99) |
See [storage duration and linkage](storage_duration "c/language/storage duration") for the meaning of the keyword `extern` with declarations at file scope.
See [definitions](declarations#Definitions "c/language/declarations") for the distinction between declarations and definitions.
Tentative definitions were invented to standardize various pre-C89 approaches to forward declaring identifiers with internal linkage.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.9 External definitions (p: 113-116)
* C11 standard (ISO/IEC 9899:2011):
+ 6.9 External definitions (p: 155-159)
* C99 standard (ISO/IEC 9899:1999):
+ 6.9 External definitions (p: 140-144)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.7 EXTERNAL DEFINITIONS
| programming_docs |
c Enumerations Enumerations
============
An *enumerated type* is a distinct [type](type "c/language/type") whose value is a value of its *underlying type* (see below), which includes the values of explicitly named constants (*enumeration constants*).
### Syntax
Enumerated type is declared using the following *enumeration specifier* as the type-specifier in the [declaration grammar](declarations "c/language/declarations"):
| | | |
| --- | --- | --- |
| `enum` attr-spec-seq(optional) identifier(optional) `{` enumerator-list `}` | | |
where enumerator-list is a comma-separated list (with trailing comma permitted) (since C99) of enumerator, each of which has the form:
| | | |
| --- | --- | --- |
| enumeration-constant attr-spec-seq(optional) | (1) | |
| enumeration-constant attr-spec-seq(optional) `=` constant-expression | (2) | |
where.
| | | |
| --- | --- | --- |
| identifier, enumeration-constant | - | identifiers that are introduced by this declaration |
| constant-expression | - | [integer constant expression](constant_expression "c/language/constant expression") whose value is representable as a value of type `int` |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), * applied to the whole enumeration if appears after `enum`,
* applied to the enumerator if appears after enumeration-constant
|
As with [struct](struct "c/language/struct") or [union](union "c/language/union"), a declaration that introduced an enumerated type and one or more enumeration constants may also declare one or more objects of that type or type derived from it.
```
enum color { RED, GREEN, BLUE } c = RED, *cp = &c;
// introduces the type enum color
// the integer constants RED, GREEN, BLUE
// the object c of type enum color
// the object cp of type pointer to enum color
```
### Explanation
Each enumeration-constant that appears in the body of an enumeration specifier becomes an [integer constant](constant_expression "c/language/constant expression") with type `int` in the enclosing scope and can be used whenever integer constants are required (e.g. as a case label or as a non-VLA array size).
```
enum color { RED, GREEN, BLUE } r = RED;
switch(r) {
case RED:
puts("red");
break;
case GREEN:
puts("green");
break;
case BLUE:
puts("blue");
break;
}
```
If enumeration-constant is followed by = constant-expression, its value is the value of that constant expression. If enumeration-constant is not followed by = constant-expression, its value is the value one greater than the value of the previous enumerator in the same enumeration. The value of the first enumerator (if it does not use = constant-expression) is zero.
```
enum Foo { A, B, C=10, D, E=1, F, G=F+C };
// A=0, B=1, C=10, D=11, E=1, F=2, G=12
```
The identifier itself, if used, becomes the name of the enumerated type in the tags [name space](name_space "c/language/name space") and requires the use of the keyword enum (unless typedef'd into the ordinary name space).
```
enum color { RED, GREEN, BLUE };
enum color r = RED; // OK
// color x = GREEN: // Error: color is not in ordinary name space
typedef enum color color_t;
color_t x = GREEN; // OK
```
Each enumerated type is [compatible](type#Compatible_types "c/language/type") with one of: `char`, a signed integer type, or an unsigned integer type. It is implementation-defined which type is compatible with any given enumerated type, but whatever it is, it must be capable of representing all enumerator values of that enumeration.
Enumerated types are integer types, and as such can be used anywhere other integer types can, including in [implicit conversions](conversion "c/language/conversion") and [arithmetic operators](operator_arithmetic "c/language/operator arithmetic").
```
enum { ONE = 1, TWO } e;
long n = ONE; // promotion
double d = ONE; // conversion
e = 1.2; // conversion, e is now ONE
e = e + 1; // e is now TWO
```
### Notes
Unlike [struct](struct "c/language/struct") or [union](union "c/language/union"), there are no forward-declared enums in C:
```
enum Color; // Error: no forward-declarations for enums in C
enum Color { RED, GREEN, BLUE };
```
Enumerations permit the declaration of named constants in a more convenient and structured fashion than does `#define`; they are visible in the debugger, obey scope rules, and participate in the type system.
```
#define TEN 10
struct S { int x : TEN; }; // OK
```
or.
```
enum { TEN = 10 };
struct S { int x : TEN; }; // also OK
```
Moreover, as a [struct](struct "c/language/struct") or [union](union "c/language/union") does not establish its scope in C, an enumeration type and its enumeration constants may be introduced in the member specification of the former, and their scope is the same as of the former, afterwards.
```
struct Element {
int z;
enum State { SOLID, LIQUID, GAS, PLASMA } state;
} oxygen = { 8, GAS };
// type enum State and its enumeration constants stay visible here, e.g.
void foo(void) {
enum State e = LIQUID; // OK
printf("%d %d %d ", e, oxygen.state, PLASMA); // prints 1 2 3
}
```
### Example
```
#include <stdio.h>
int main(void)
{
enum TV { FOX = 11, CNN = 25, ESPN = 15, HBO = 22, MAX = 30, NBC = 32 };
printf("List of cable stations: \n");
printf(" FOX: \t%2d\n", FOX);
printf(" HBO: \t%2d\n", HBO);
printf(" MAX: \t%2d\n", MAX);
}
```
Output:
```
List of cable stations:
FOX: 11
HBO: 22
MAX: 30
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.2.5/16 Types (p: 32)
+ 6.7.2.2 Enumeration specifiers (p: 84-85)
* C11 standard (ISO/IEC 9899:2011):
+ 6.2.5/16 Types (p: 41)
+ 6.7.2.2 Enumeration specifiers (p: 117-118)
* C99 standard (ISO/IEC 9899:1999):
+ 6.2.5/16 Types (p: 35)
+ 6.7.2.2 Enumeration specifiers (p: 105-106)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.2.5 Types
+ 3.5.2.2 Enumeration specifiers
### Keywords
[`enum`](../keyword/enum "c/keyword/enum").
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/enum "cpp/language/enum") for enumeration declaration |
c Compound literals Compound literals
=================
Constructs an unnamed object of specified type (which may be struct, union, or even array type) in-place.
### Syntax
| | | |
| --- | --- | --- |
| `(` type `)` `{` initializer-list `}` | | (since C99) |
| `(` type `)` `{` initializer-list `,` `}` | | (since C99) |
| `(` type `)` `{` `}` | | (since C23) |
where.
| | | |
| --- | --- | --- |
| type | - | a [type name](type#Type_names "c/language/type") specifying any complete object type or an array of unknown size, but not a VLA |
| initializer-list | - | list of initializers suitable for [initialization](initialization "c/language/initialization") of an object of type |
### Explanation
The compound literal expression constructs an unnamed object of the type specified by type and initializes it as specified by initializer-list. [Designated initializers](initialization "c/language/initialization") are accepted.
The type of the compound literal is type (except when type is an array of unknown size; its size is deduced from the initializer-list as in [array initialization](array_initialization "c/language/array initialization")).
The value category of a compound literal is [lvalue](value_category "c/language/value category") (its address can be taken).
The unnamed object to which the compound literal evaluates has static [storage duration](storage_duration "c/language/storage duration") if the compound literal occurs at file scope and automatic [storage duration](storage_duration "c/language/storage duration") if the compound literal occurs at block scope (in which case the object's [lifetime](lifetime "c/language/lifetime") ends at the end of the enclosing block).
### Notes
Compound literals of const-qualified character or wide character array types may share storage with [string literals](string_literal "c/language/string literal").
```
(const char []){"abc"} == "abc" // might be 1 or 0, implementation-defined
```
Each compound literal creates only a single object in its scope:
```
int f (void)
{
struct s {int i;} *p = 0, *q;
int j = 0;
again:
q = p, p = &((struct s){ j++ });
if (j < 2) goto again; // note; if a loop were used, it would end scope here,
// which would terminate the lifetime of the compound literal
// leaving p as a dangling pointer
return p == q && q->i == 1; // always returns 1
}
```
Because compound literals are unnamed, a compound literal cannot reference itself (a named struct can include a pointer to itself).
Although the syntax of a compound literal is similar to a [cast](cast "c/language/cast"), the important distinction is that a cast is a non-lvalue expression while a compound literal is an lvalue.
### Example
```
#include <stdio.h>
int *p = (int[]){2, 4}; // creates an unnamed static array of type int[2]
// initializes the array to the values {2, 4}
// creates pointer p to point at the first element of
// the array
const float *pc = (const float []){1e0, 1e1, 1e2}; // read-only compound literal
struct point {double x,y;};
int main(void)
{
int n = 2, *p = &n;
p = (int [2]){*p}; // creates an unnamed automatic array of type int[2]
// initializes the first element to the value formerly
// held in *p
// initializes the second element to zero
// stores the address of the first element in p
void drawline1(struct point from, struct point to);
void drawline2(struct point *from, struct point *to);
drawline1(
(struct point){.x=1, .y=1}, // creates two structs with block scope and
(struct point){.x=3, .y=4}); // calls drawline1, passing them by value
drawline2(
&(struct point){.x=1, .y=1}, // creates two structs with block scope and
&(struct point){.x=3, .y=4}); // calls drawline2, passing their addresses
}
void drawline1(struct point from, struct point to)
{
printf("drawline1: `from` @ %p {%.2f, %.2f}, `to` @ %p {%.2f, %.2f}\n",
(void*)&from, from.x, from.y, (void*)&to, to.x, to.y);
}
void drawline2(struct point *from, struct point *to)
{
printf("drawline2: `from` @ %p {%.2f, %.2f}, `to` @ %p {%.2f, %.2f}\n",
(void*)from, from->x, from->y, (void*)to, to->x, to->y);
}
```
Possible output:
```
drawline1: `from` @ 0x7ffd24facea0 {1.00, 1.00}, `to` @ 0x7ffd24face90 {3.00, 4.00}
drawline2: `from` @ 0x7ffd24facec0 {1.00, 1.00}, `to` @ 0x7ffd24faced0 {3.00, 4.00}
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.5.2.5 Compound literals (p: 61-63)
* C11 standard (ISO/IEC 9899:2011):
+ 6.5.2.5 Compound literals (p: 85-87)
* C99 standard (ISO/IEC 9899:1999):
+ 6.5.2.5 Compound literals (p: 75-77)
c Function declarations Function declarations
=====================
A function declaration introduces an [identifier](identifier "c/language/identifier") that designates a function and, optionally, specifies the types of the function parameters (the *prototype*). Function declarations (unlike [definitions](function_definition "c/language/function definition")) may appear at block scope as well as file scope.
### Syntax
In the [declaration grammar](declarations "c/language/declarations") of a function declaration, the type-specifier sequence, possibly modified by the declarator, designates the *return type* (which may be any type other than array or function type), and the declarator has one of three forms:
| | | |
| --- | --- | --- |
| noptr-declarator `(` parameter-list `)` attr-spec-seq(optional) | (1) | |
| noptr-declarator `(` identifier-list `)` attr-spec-seq(optional) | (2) | (until C23) |
| noptr-declarator `(` `)` attr-spec-seq(optional) | (3) | |
where.
| | | |
| --- | --- | --- |
| noptr-declarator | - | any [declarator](declarations#Declarators "c/language/declarations") except unparenthesized pointer declarator. The identifier that is contained in this declarator is the identifier that becomes the function designator. |
| parameter-list | - | either the single keyword `void` or a comma-separated list of *parameters*, which may end with an [ellipsis parameter](variadic "c/language/variadic") |
| identifier-list | - | comma-separated list of identifiers, only possible if this declarator is used as part of old-style [function definition](function_definition "c/language/function definition") |
| attr-spec-seq | - | (C23)an optional list of [attributes](attributes "c/language/attributes"), applied to the function type |
1) New-style (C89) function declaration. This declaration both introduces the function designator itself and also serves as a function prototype for any future [function call expressions](operator_other#Function_call "c/language/operator other"), forcing conversions from argument expressions to the declared parameter types and compile-time checks for the number of arguments.
```
int max(int a, int b); // declaration
int n = max(12.01, 3.14); // OK, conversion from double to int
```
2) (until C23) Old-style (K&R) function definition. This declaration does not introduce a prototype and any future [function call expressions](operator_other#Function_call "c/language/operator other") will perform default argument promotions and will invoke undefined behavior if the number of arguments doesn't match the number of parameters.
```
int max(a, b)
int a, b; { return a>b?a:b; } // definition expects ints; the second call is undefined
int n = max(true, (char)'a'); // calls max with two int args (after promotions)
int n = max(12.01f, 3.14); // calls max with two double args (after promotions)
```
3) Non-prototype function declaration. This declaration does not introduce a prototype except as part of a function definition, where it is equivalent to the parameter-list `void` (since C23). ### Explanation
The return type of the function, determined by the type specifier in specifiers-and-qualifiers and possibly modified by the declarator as usual in [declarations](declarations "c/language/declarations"), must be a non-array object type or the type `void`. If the function declaration is not a definition, the return type can be [incomplete](type#Incomplete_types "c/language/type"). The return type cannot be cvr-qualified: any qualified return type is adjusted to its unqualified version for the purpose of constructing the function type.
```
void f(char *s); // return type is void
int sum(int a, int b); // return type of sum is int.
int (*foo(const void *p))[3]; // return type is pointer to array of 3 int
double const bar(void); // declares function of type double(void)
double (*barp)(void) = bar; // OK: barp is a pointer to double(void)
double const (*barpc)(void) = barp; // OK: barpc is also a pointer to double(void)
```
Function declarators can be combined with other declarators as long as they can share their type specifiers and qualifiers.
```
int f(void), *fip(), (*pfi)(), *ap[3]; // declares two functions and two objects
inline int g(int), n; // Error: inline qualifier is for functions only
typedef int array_t[3];
array_t a, h(); // Error: array type cannot be a return type for a function
```
If a function declaration appears outside of any function, the identifier it introduces has [file scope](scope "c/language/scope") and [external linkage](storage_duration "c/language/storage duration"), unless `static` is used or an earlier static declaration is visible. If the declaration occurs inside another function, the identifier has block scope (and also either internal or external linkage).
```
int main(void)
{
int f(int); // external linkage, file scope
f(1); // definition needs to be available somewhere in the program
}
```
The parameters in a declaration that is not part of a [function definition](function_definition "c/language/function definition") (until C23) do not need to be named:
```
int f(int, int); // declaration
// int f(int, int) { return 7; } // Error: parameters must be named in definitions
// This definition is allowed since C23
```
Each parameter in a parameter-list is a [declaration](declarations "c/language/declarations") that introduced a single variable, with the following additional properties:
* the identifier in the declarator is optional (except if this function declaration is part of a function definition) (until C23)
```
int f(int, double); // OK
int g(int a, double b); // also OK
// int f(int, double) { return 1; } // Error: definition must name parameters
// This definition is allowed since C23
```
* the only [storage class specifier](storage_duration "c/language/storage duration") allowed for parameters is `register`, and it is ignored in function declarations that are not definitions
```
int f(static int x); // Error
int f(int [static 10]); // OK (array index static is not a storage class specifier)
```
* any parameter of array type is adjusted to the corresponding pointer type, which may be qualified if there are qualifiers between the square brackets of the array declarator (since C99)
```
int f(int[]); // declares int f(int*)
int g(const int[10]); // declares int g(const int*)
int h(int[const volatile]); // declares int h(int * const volatile)
int x(int[*]); // declares int x(int*)
```
* any parameter of function type is adjusted to the corresponding pointer type
```
int f(char g(double)); // declares int f(char (*g)(double))
int h(int(void)); // declares int h(int (*)(void))
```
* the parameter list may terminate with `, ...`, see [variadic functions](variadic "c/language/variadic") for details.
```
int f(int, ...);
```
* parameters cannot have type `void` (but can have type pointer to void). The special parameter list that consists entirely of the keyword `void` is used to declare functions that take no parameters.
```
int f(void); // OK
int g(void x); // Error
```
* any identifier that appears in a parameter list that could be treated as a typedef name or as a parameter name is treated as a typedef name: `int f([size\_t](http://en.cppreference.com/w/c/types/size_t), [uintptr\_t](http://en.cppreference.com/w/c/types/integer))` is parsed as a new-style declarator for a function taking two unnamed parameters of type size\_t and uintptr\_t, not an old-style declarator that begins the definition of a function taking two parameters named "size\_t" and "uintptr\_t"
* parameters may have incomplete type and may use the VLA notation [\*] (since C99) (except that in a [function definition](function_definition "c/language/function definition"), the parameter types after array-to-pointer and function-to-pointer adjustment must be complete)
| | |
| --- | --- |
| [Attribute specifier sequences](attributes "c/language/attributes") can also applied to function parameters. | (since C23) |
See [function call operator](operator_other#Function_call "c/language/operator other") for other details on the mechanics of a function call and [return](return "c/language/return") for returning from functions.
### Notes
Unlike in C++ and [function definitions](function_definition "c/language/function definition") (since C23), the declarators `f()` and `f(void)` have different meaning: the declarator `f(void)` is a new-style (prototype) declarator that declares a function that takes no parameters. The declarator `f()` is a declarator that declares a function that takes *unspecified* number of parameters (unless used in a function definition).
```
int f(void); // declaration: takes no parameters
int g(); // declaration: takes unknown parameters
int main(void) {
f(1); // compile-time error
g(2); // undefined behavior
}
int f(void) { return 1; } // actual definition
int g(a,b,c,d) int a,b,c,d; { return 2; } // actual definition
```
Unlike in a [function definition](function_definition "c/language/function definition"), the parameter list may be inherited from a typedef.
```
typedef int p(int q, int r); // p is a function type int(int, int)
p f; // declares int f(int, int)
```
| | |
| --- | --- |
| In C89, specifiers-and-qualifiers was optional, and if omitted, the return type of the function defaulted to `int` (possibly amended by the declarator).
```
*f() { // function returning int*
return NULL;
}
```
| (until C99) |
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [DR 423](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_423) | C89 | the return type might be qualified | the return type is implicitly disqualified |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.6.3 Function declarators (including prototypes) (p: 96-98)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.6.3 Function declarators (including prototypes) (p: 133-136)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.5.3 Function declarators (including prototypes) (p: 118-121)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.5.4.3 Function declarators (including prototypes)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/function "cpp/language/function") for Function declaration |
| programming_docs |
c Array declaration Array declaration
=================
Array is a type consisting of a contiguously allocated nonempty sequence of objects with a particular *element type*. The number of those objects (the array size) never changes during the array lifetime.
### Syntax
In the [declaration grammar](declarations "c/language/declarations") of an array declaration, the *type-specifier* sequence designates the *element type* (which must be a complete object type), and the *declarator* has the form:
| | | |
| --- | --- | --- |
| `[` `static`(optional) qualifiers(optional) expression(optional) `]` attr-spec-seq(optional) | (1) | |
| `[` qualifiers(optional) `static`(optional) expression(optional) `]` attr-spec-seq(optional) | (2) | |
| `[` qualifiers(optional) `*` `]` attr-spec-seq(optional) | (3) | |
1,2) General array declarator syntax
3) Declarator for VLA of unspecified size (can appear in function prototype scope only) where
| | | |
| --- | --- | --- |
| expression | - | any expression other than [comma operator](operator_other#Comma_operator "c/language/operator other"), designates the number of elements in the array |
| qualifiers | - | any combination of [`const`](const "c/language/const"), [`restrict`](restrict "c/language/restrict"), or [`volatile`](volatile "c/language/volatile") qualifiers, only allowed in function parameter lists; this qualifies the pointer type to which this array parameter is transformed |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the declared array |
```
float fa[11], *afp[17]; // fa is an array of 11 floats
// afp is an array of 17 pointers to floats
```
### Explanation
There are several variations of array types: arrays of known constant size, variable-length arrays, and arrays of unknown size.
#### Arrays of constant known size
If expression in an array declarator is an [integer constant expression](constant_expression#Integer_constant_expression "c/language/constant expression") with a value greater than zero and the element type is a type with a known constant size (that is, elements are not VLA) (since C99), then the declarator declares an array of constant known size:
```
int n[10]; // integer constants are constant expressions
char o[sizeof(double)]; // sizeof is a constant expression
enum { MAX_SZ=100 };
int n[MAX_SZ]; // enum constants are constant expressions
```
Arrays of constant known size can use [array initializers](array_initialization "c/language/array initialization") to provide their initial values:
```
int a[5] = {1,2,3}; // declares int[5] initalized to 1,2,3,0,0
char str[] = "abc"; // declares char[4] initialized to 'a','b','c','\0'
```
| | |
| --- | --- |
| In function parameter lists, additional syntax elements are allowed within the array declarators: the keyword `static` and qualifiers, which may appear in any order before the size expression (they may also appear even when the size expression is omitted).
In each [function call](operator_other#Function_call "c/language/operator other") to a function where an array parameter uses the keyword `static` between `[` and `]`, the value of the actual parameter must be a valid pointer to the first element of an array with at least as many elements as specified by expression:
```
void fadd(double a[static 10], const double b[static 10])
{
for (int i = 0; i < 10; i++) {
if (a[i] < 0.0) return;
a[i] += b[i];
}
}
// a call to fadd may perform compile-time bounds checking
// and also permits optimizations such as prefetching 10 doubles
int main(void)
{
double a[10] = {0}, b[20] = {0};
fadd(a, b); // OK
double x[5] = {0};
fadd(x, b); // undefined behavior: array argument is too small
}
```
If qualifiers are present, they qualify the pointer type to which the array parameter type is transformed:
```
int f(const int a[20])
{
// in this function, a has type const int* (pointer to const int)
}
int g(const int a[const 20])
{
// in this function, a has type const int* const (const pointer to const int)
}
```
This is commonly used with the [`restrict`](restrict "c/language/restrict") type qualifier:
```
void fadd(double a[static restrict 10],
const double b[static restrict 10])
{
for (int i = 0; i < 10; i++) { // loop can be unrolled and reordered
if (a[i] < 0.0) break;
a[i] += b[i];
}
}
```
Variable-length arrays If expression is not an [integer constant expression](constant_expression#Integer_constant_expression "c/language/constant expression"), the declarator is for an array of variable size.
Each time the flow of control passes over the declaration, expression is evaluated (and it must always evaluate to a value greater than zero), and the array is allocated (correspondingly, [lifetime](lifetime "c/language/lifetime") of a VLA ends when the declaration goes out of scope). The size of each VLA instance does not change during its lifetime, but on another pass over the same code, it may be allocated with a different size.
```
#include <stdio.h>
int main(void)
{
int n = 1;
label:;
int a[n]; // re-allocated 10 times, each with a different size
printf("The array has %zu elements\n", sizeof a / sizeof *a);
if (n++ < 10) goto label; // leaving the scope of a VLA ends its lifetime
}
```
If the size is `*`, the declaration is for a VLA of unspecified size. Such declaration may only appear in a function prototype scope, and declares an array of a complete type. In fact, all VLA declarators in function prototype scope are treated as if expression were replaced by `*`.
```
void foo(size_t x, int a[*]);
void foo(size_t x, int a[x])
{
printf("%zu\n", sizeof a); // same as sizeof(int*)
}
```
Variable-length arrays and the types derived from them (pointers to them, etc) are commonly known as "variably-modified types" (VM). Objects of any variably-modified type may only be declared at block scope or function prototype scope.
```
extern int n;
int A[n]; // Error: file scope VLA
extern int (*p2)[n]; // Error: file scope VM
int B[100]; // OK: file-scope array of constant known size
void fvla(int m, int C[m][m]); // OK: prototype-scope VLA
```
VLA must have automatic or allocated storage duration. Pointers to VLA, but not VLA themselves may also have static storage duration. No VM type may have linkage.
```
void fvla(int m, int C[m][m]) // OK: block scope/auto duration pointer to VLA
{
typedef int VLA[m][m]; // OK: block scope VLA
int D[m]; // OK: block scope/auto duration VLA
// static int E[m]; // Error: static duration VLA
// extern int F[m]; // Error: VLA with linkage
int (*s)[m]; // OK: block scope/auto duration VM
s = malloc(m * sizeof(int)); // OK: s points to VLA in allocated storage
// extern int (*r)[m]; // Error: VM with linkage
static int (*q)[m] = &B; // OK: block scope/static duration VM}
}
```
Variably-modified types cannot be members of structs or unions.
```
struct tag {
int z[n]; // Error: VLA struct member
int (*y)[n]; // Error: VM struct member
};
```
| (since C99) |
| If the compiler defines the macro constant `__STDC_NO_VLA__` to integer constant `1`, then VLA and VM types are not supported. | (since C11)(until C23) |
| If the compiler defines the macro constant `__STDC_NO_VLA__` to integer constant `1`, then VLA objects with automatic storage duration are not supported.
The support for VM types and VLAs with allocated storage durations is mandated. | (since C23) |
#### Arrays of unknown size
If expression in an array declarator is omitted, it declares an array of unknown size. Except in function parameter lists (where such arrays are transformed to pointers) and when an [initializer](array_initialization "c/language/array initialization") is available, such type is an [incomplete type](type#Incomplete_types "c/language/type") (note that VLA of unspecified size, declared with `*` as the size, is a complete type) (since C99):
```
extern int x[]; // the type of x is "array of unknown bound of int"
int a[] = {1,2,3}; // the type of a is "array of 3 int"
```
| | |
| --- | --- |
| Within a [struct](struct "c/language/struct") definition, an array of unknown size may appear as the last member (as long as there is at least one other named member), in which case it is a special case known as *flexible array member*. See [struct](struct "c/language/struct") for details:
```
struct s { int n; double d[]; }; // s.d is a flexible array member
struct s *s1 = malloc(sizeof (struct s) + (sizeof (double) * 8)); // as if d was double d[8]
```
| (since C99) |
#### Qualifiers
| | |
| --- | --- |
| If an array type is declared with a [`const`](const "c/language/const"), [`volatile`](volatile "c/language/volatile"), or [`restrict`](restrict "c/language/restrict") (since C99) qualifier (which is possible through the use of [typedef](typedef "c/language/typedef")), the array type is not qualified, but its element type is: | (until C23) |
| An array type and its element type are always considered to be identically qualified, except that an array type is never considered to be [`_Atomic`](atomic "c/language/atomic")-qualified. | (since C23) |
```
typedef int A[2][3];
const A a = {{4, 5, 6}, {7, 8, 9}}; // array of array of const int
int* pi = a[0]; // Error: a[0] has type const int*
void *unqual_ptr = a; // OK until C23; error since C23
// Notes: clang applies the rule in C++/C23 even in C89-C17 modes
```
| | |
| --- | --- |
| [`_Atomic`](atomic "c/language/atomic") is not allowed to be applied to an array type, although an array of atomic type is allowed.
```
typedef int A[2];
// _Atomic A a0 = {0}; // Error
// _Atomic(A) a1 = {0}; // Error
_Atomic int a2[2] = {0}; // OK
_Atomic(int) a3[2] = {0}; // OK
```
| (since C11) |
#### Assignment
Objects of array type are not [modifiable lvalues](value_category "c/language/value category"), and although their address may be taken, they cannot appear on the left hand side of an assignment operator. However, structs with array members are modifiable lvalues and can be assigned:
```
int a[3] = {1,2,3}, b[3] = {4,5,6};
int (*p)[3] = &a; // okay, address of a can be taken
// a = b; // error, a is an array
struct { int c[3]; } s1, s2 = {3,4,5};
s1 = s2; // okay: can assign structs holding array members
```
#### Array to pointer conversion
Any [lvalue expression](value_category "c/language/value category") of array type, when used in any context other than.
* as the operand of the [address-of operator](operator_member_access "c/language/operator member access")
* as the operand of [`sizeof`](sizeof "c/language/sizeof")
* as the string literal used for [array initialization](array_initialization "c/language/array initialization")
| | |
| --- | --- |
| * as the operand of [`_Alignof`](_alignof "c/language/ Alignof")
| (since C11) |
undergoes an [implicit conversion](conversion "c/language/conversion") to the pointer to its first element. The result is not an lvalue.
If the array was declared [`register`](storage_duration "c/language/storage duration"), the behavior of the program that attempts such conversion is undefined.
```
int a[3] = {1,2,3};
int* p = a;
printf("%zu\n", sizeof a); // prints size of array
printf("%zu\n", sizeof p); // prints size of a pointer
```
When an array type is used in a function parameter list, it is transformed to the corresponding pointer type: `int f(int a[2])` and `int f(int* a)` declare the same function. Since the function's actual parameter type is pointer type, a function call with an array argument performs array-to-pointer conversion; the size of the argument array is not available to the called function and must be passed explicitly:
```
#include <stdio.h>
void f(int a[], int sz) // actually declares void f(int* a, int sz)
{
for(int i = 0; i < sz; ++i)
printf("%d\n", a[i]);
}
int main(void)
{
int a[10];
f(a, 10); // converts a to int*, passes the pointer
}
```
#### Multidimensional arrays
When the element type of an array is another array, it is said that the array is multidimensional:
```
// array of 2 arrays of 3 ints each
int a[2][3] = {{1,2,3}, // can be viewed as a 2x3 matrix
{4,5,6}}; // with row-major layout
```
Note that when array-to-pointer conversion is applied, a multidimensional array is converted to a pointer to its first element, e.g., pointer to the first row:
```
int a[2][3]; // 2x3 matrix
int (*p1)[3] = a; // pointer to the first 3-element row
int b[3][3][3]; // 3x3x3 cube
int (*p2)[3][3] = b; // pointer to the first 3x3 plane
```
| | |
| --- | --- |
| Multidimensional arrays may be variably modified in every dimension if VLAs are supported (since C11):
```
int n = 10;
int a[n][2*n];
```
| (since C99) |
### Notes
Zero-length array declarations are not allowed, even though some compilers offer them as extensions (typically as a pre-C99 implementation of [flexible array members](struct "c/language/struct")).
If the size expression of a VLA has side effects, they are guaranteed to be produced except when it is a part of a sizeof expression whose result doesn't depend on it:
```
int n = 5;
size_t sz = sizeof(int (*)[n++]); // may or may not increment n
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.6.2 Array declarators (p: 94-96)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.6.2 Array declarators (p: 130-132)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.5.2 Array declarators (p: 116-118)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.5.4.2 Array declarators
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/array "cpp/language/array") for Array declaration |
c Bit fields Bit fields
==========
Declares a member with explicit width, in bits. Adjacent bit field members may be packed to share and straddle the individual bytes.
A bit field declaration is a [struct](struct "c/language/struct") or [union](union "c/language/union") member declaration which uses the following [declarator](declarations "c/language/declarations"):
| | | |
| --- | --- | --- |
| identifier(optional) `:` width | | |
| | | |
| --- | --- | --- |
| identifier | - | the name of the bit field that is being declared. The name is optional: nameless bit fields introduce the specified number of bits of padding |
| width | - | an integer [constant expression](constant_expression "c/language/constant expression") with a value greater or equal to zero and less or equal the number of bits in the underlying type. When greater than zero, this is the number of bits that this bit field will occupy. The value zero is only allowed for nameless bit fields and has special meaning: it specifies that the next bit field in the class definition will begin at an allocation unit's boundary. |
### Explanation
Bit fields can have only one of four types (possibly [const](const "c/language/const") or [volatile](volatile "c/language/volatile") qualified):
* `unsigned int`, for unsigned bit fields (`unsigned int b:3;` has the range `0..7`)
* `signed int`, for signed bit fields (`signed int b:3;` has the range `-4..3`)
* `int`, for bit fields with implementation-defined signedness (Note that this differs from the meaning of the keyword `int` everywhere else, where it means "signed int"). For example, `int b:3;` may have the range of values `0..7` or `-4..3`.
| | |
| --- | --- |
| * `_Bool`, for single-bit bit fields (`bool x:1;` has the range `0..1` and [implicit conversions](conversion "c/language/conversion") to and from it follow the boolean conversion rules.
| (since C99) |
Additional implementation-defined types may be acceptable. It is also implementation-defined whether a bit field may have [atomic](atomic "c/language/atomic") type. (since C11) The number of bits in a bit field (width) sets the limit to the range of values it can hold:
```
#include <stdio.h>
struct S {
// three-bit unsigned field,
// allowed values are 0...7
unsigned int b : 3;
};
int main(void)
{
struct S s = {7};
++s.b; // unsigned overflow
printf("%d\n", s.b); // output: 0
}
```
Multiple adjacent bit fields are permitted to be (and usually are) packed together:
```
#include <stdio.h>
struct S {
// will usually occupy 4 bytes:
// 5 bits: value of b1
// 11 bits: unused
// 6 bits: value of b2
// 2 bits: value of b3
// 8 bits: unused
unsigned b1 : 5, : 11, b2 : 6, b3 : 2;
};
int main(void)
{
printf("%zu\n",sizeof(struct S)); // usually prints 4
}
```
The special *unnamed bit field* of width zero breaks up padding: it specifies that the next bit field begins at the beginning of the next allocation unit:
```
#include <stdio.h>
struct S {
// will usually occupy 8 bytes:
// 5 bits: value of b1
// 27 bits: unused
// 6 bits: value of b2
// 15 bits: value of b3
// 11 bits: unused
unsigned b1 : 5;
unsigned :0; // start a new unsigned int
unsigned b2 : 6;
unsigned b3 : 15;
};
int main(void)
{
printf("%zu\n", sizeof(struct S)); // usually prints 8
}
```
Because bit fields do not necessarily begin at the beginning of a byte, address of a bit field cannot be taken. Pointers to bit fields are not possible. Bit fields cannot be used with [`sizeof`](sizeof "c/language/sizeof") and [`_Alignas`](_alignas "c/language/ Alignas") (since C11).
### Notes
The following properties of bit fields are *undefined*:
* The effect of calling `[offsetof](../types/offsetof "c/types/offsetof")` on a bit field
The following properties of bit fields are *unspecified*:
* Alignment of the allocation unit that holds a bit field
The following properties of bit fields are *implementation-defined*:
* Whether bit fields of type `int` are treated as signed or unsigned
* Whether types other than `int`, `signed int`, `unsigned int`, and `_Bool` (since C99) are permitted
| | |
| --- | --- |
| * Whether atomic types are permitted
| (since C11) |
* Whether a bit field can straddle an allocation unit boundary
* The order of bit fields within an allocation unit (on some platforms, bit fields are packed left-to-right, on others right-to-left)
| | |
| --- | --- |
| Even though the number of bits in the object representation of `_Bool` is at least `[CHAR\_BIT](../types/limits "c/types/limits")`, the width of the bit field of type `_Bool` cannot be greater than 1. | (since C99) |
In the C++ programming language, the width of a bit field can exceed the width of the underlying type, and bit fields of type `int` are always signed.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.2.1 Structure and union specifiers
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.2.1 Structure and union specifiers
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.2.1 Structure and union specifiers
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.5.2.1 Structure and union specifiers
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/bit_field "cpp/language/bit field") for Bit field |
c Floating constant Floating constant
=================
Allows values of floating type to be used directly in expressions.
### Syntax
A floating constant is a [non-lvalue](value_category "c/language/value category") expression having the form:
| | | |
| --- | --- | --- |
| significand exponent(optional) suffix(optional) | | |
Where the significand has the form.
| | | |
| --- | --- | --- |
| whole-number(optional) `.`(optional) fraction(optional) | | |
The exponent has the form.
| | | |
| --- | --- | --- |
| `e` | `E` exponent-sign(optional) digit-sequence | (1) | |
| `p` | `P` exponent-sign(optional) digit-sequence | (2) | (since C99) |
1) The exponent syntax for a decimal floating-point constant
2) The exponent syntax for hexadecimal floating-point constant
| | |
| --- | --- |
| Optional single quotes (`'`) can be inserted between the digits as a separator, they are ignored when compiling. | (since C23) |
### Explanation
| | |
| --- | --- |
| If the significand begins with the character sequence `0x` or `0X`, the floating constant is a *hexadecimal floating constant*. Otherwise, it is a *decimal floating constant*.
For a *hexadecimal floating constant*, the significand is interpreted as a hexadecimal rational number, and the digit-sequence of the exponent is interpreted as the integer power of 2 to which the significand has to be scaled.
```
double d = 0x1.2p3; // hex fraction 1.2 (decimal 1.125) scaled by 2^3, that is 9.0
```
| (since C99) |
For a *decimal floating constant*, the significand is interpreted as a decimal rational number, and the digit-sequence of the exponent is interpreted as the integer power of 10 to which the significand has to be scaled.
```
double d = 1.2e3; // decimal fraction 1.2 scaled by 10^3, that is 1200.0
```
#### Suffixes
An unsuffixed floating constant has type `double`. If suffix is the letter `f` or `F`, the floating constant has type `float`. If suffix is the letter `l` or `L`, the floating constant has type `long double`.
| | |
| --- | --- |
| If the implementation predefines macro `__STDC_IEC_60559_BFP__`, the following suffixes and corresponding floating constants are additionally supported:* if suffix is `df` or `DF`, the floating constant has type `_Decimal32`;
* if suffix is `dd` or `DD`, the floating constant has type `_Decimal64`;
* if suffix is `dl` or `DL`, the floating constant has type `_Decimal128`.
Suffixes for decimal floating-point types are not allowed in hexadecimal floating constants. | (since C23) |
#### Optional parts
If the exponent is present and fractional part is not used, the decimal separator may be omitted:
```
double x = 1e0; // floating-point 1.0 (period not used)
```
For decimal floating constants, the exponent part is optional. If it is omitted, the period is not optional, and either the whole-number or the fraction must be present.
```
double x = 1.; // floating-point 1.0 (fractional part optional)
double y = .1; // floating-point 0.1 (whole-number part optional)
```
| | |
| --- | --- |
| For hexadecimal floating constants, the exponent is not optional to avoid ambiguity resulting from an `f` suffix being mistaken as a hexadecimal digit. | (since C99) |
#### Representable values
The result of evaluating a floating constant is either the nearest representable value or the larger or smaller representable value immediately adjacent to the nearest representable value, chosen in an implementation-defined manner (in other words, [default rounding direction](../numeric/fenv/fe_round "c/numeric/fenv/FE round") during translation is implementation-defined).
All floating constants of the same source form convert to the same internal format with the same value. Floating constants of different source forms, e.g. `1.23` and `1.230`, need not to convert to the same internal format and value.
| | |
| --- | --- |
| Floating-point constants may convert to more range and precision than is indicated by their type, if indicated by `[FLT\_EVAL\_METHOD](../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")`. For example, the constant `0.1f` may act as if it were `0.1L` in an expression.
The result of evaluating a hexadecimal floating constant, if `[FLT\_RADIX](../types/limits "c/types/limits")` is 2, is the exact value represented by the floating constant, correctly rounded to the target type. | (since C99) |
| | |
| --- | --- |
| Floating constants of decimal floating-point type that have the same numerical value \(\small x\)x but different quantum exponents, e.g. `1230.dd`, `1230.0dd`, and `1.23e3dd`, have distinguishable internal representations.
The quantum exponent \(\small q\)q of a floating constant of a decimal floating-point type is determined in the manner that \(\small 10^q\)10q represents 1 at the place of last digit of the significand when possible. If the quantum exponent \(\small q\)q and the coefficient \(\small c = x\cdot 10^{-q}\)c=x·10-q determined above cannot represented exactly in the type of the floating constant, \(\small q\)q is increased as needed within the limit of the type, and \(\small c\)c is reduced correspondingly, with needed rounding. The rounding may result in zero or infinity. If (the possibly rounded) \(\small c\)c is still out of the permitted range after \(\small q\)q reaches the maximum value, the resulted floating constant has value positive infinity. | (since C23) |
### Notes
Default [rounding direction](../numeric/fenv/fe_round "c/numeric/fenv/FE round") and [precision](../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD") are in effect when the floating constants are converted into internal representations, and [floating-point exceptions](../numeric/fenv/fe_exceptions "c/numeric/fenv/FE exceptions") are not raised even if [`#pragma STDC FENV_ACCESS`](../preprocessor/impl "c/preprocessor/impl") is in effect (for execution-time conversion of character strings, `[strtod](../string/byte/strtof "c/string/byte/strtof")` can be used). Note that this differs from [arithmetic constant expressions](constant_expression "c/language/constant expression") of floating type.
Letters in the floating constants are case-insensitive, except that uppercase and lowercase cannot be both used in suffixes for decimal floating-point types (since C23): `0x1.ep+3` and `0X1.EP+3` represent the same floating-point value 15.0.
The decimal point specified by `[setlocale](../locale/setlocale "c/locale/setlocale")` has no effect on the syntax of floating constants: the decimal point character is always the period.
Unlike integers, not every floating value can be represented directly by decimal or even hexadecimal (since C99) constant syntax: macros [`NAN`](../numeric/math/nan "c/numeric/math/NAN") and [`INFINITY`](../numeric/math/infinity "c/numeric/math/INFINITY") as well as functions such as `[nan](../numeric/math/nan "c/numeric/math/nan")` offer ways to generate those special values (since C99). Note that `0x1.FFFFFEp128f`, which might appear to be an IEEE float NaN, in fact overflows to an infinity in that format.
There are no negative floating constants; an expression such as `-1.2` is the [arithmetic operator](operator_arithmetic "c/language/operator arithmetic") unary minus applied to the floating constant `1.2`. Note that the special value negative zero may be constructed with `-0.0`.
### Example
```
#include <stdio.h>
int main(void)
{
printf("15.0 = %a\n", 15.0);
printf("0x1.ep+3 = %f\n", 0x1.ep+3);
// Constants outside the range of type double.
printf("+2.0e+308 --> %g\n", 2.0e+308);
printf("+1.0e-324 --> %g\n", 1.0e-324);
printf("-1.0e-324 --> %g\n", -1.0e-324);
printf("-2.0e+308 --> %g\n", -2.0e+308);
}
```
Output:
```
15.0 = 0x1.ep+3
0x1.ep+3 = 15.000000
+2.0e+308 --> inf
+1.0e-324 --> 0
-1.0e-324 --> -0
-2.0e+308 --> -inf
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.4.4.2 Floating constants (p: 47-48)
* C11 standard (ISO/IEC 9899:2011):
+ 6.4.4.2 Floating constants (p: 65-66)
* C99 standard (ISO/IEC 9899:1999):
+ 6.4.4.2 Floating constants (p: 57-58)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.3.1 Floating constants
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/floating_literal "cpp/language/floating literal") for Floating-point literal |
| programming_docs |
c Static assertion Static assertion
================
### Syntax
| | | |
| --- | --- | --- |
| `_Static_assert` `(` expression `,` message `)` | | (since C11) |
| `_Static_assert` `(` expression `)` | | (since C23) |
| | | |
| --- | --- | --- |
| expression | - | any [integer constant expression](constant_expression "c/language/constant expression") |
| message | - | any [string literal](string_literal "c/language/string literal") |
This keyword is also available as convenience macro [`static_assert`](../error/static_assert "c/error/static assert"), available in the header `<assert.h>`.
### Explanation
The constant expression is evaluated at compile time and compared to zero. If it compares equal to zero, a compile-time error occurs and the compiler must display message (if provided) as part of the error message (except that characters not in [basic source character set](translation_phases "c/language/translation phases") aren't required to be displayed).
Otherwise, if expression does not equal zero, nothing happens; no code is emitted.
### Keywords
[`_Static_assert`](../keyword/_static_assert "c/keyword/ Static assert").
### Example
```
#include <assert.h>
int main(void)
{
// Test if math works.
static_assert(2 + 2 == 4, "Whoa dude!"); // or _Static_assert(...
// This will produce an error at compile time.
static_assert(sizeof(int) < sizeof(char),
"this program requires that int is less than char");
}
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.10 Static assertions (p: 105)
+ 7.2 Diagnostics <assert.h> (p: 135)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.10 Static assertions (p: 145)
+ 7.2 Diagnostics <assert.h> (p: 186-187)
### See also
| | |
| --- | --- |
| [assert](../error/assert "c/error/assert") | aborts the program if the user-specified condition is not `true`. May be disabled for release builds (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/static_assert "cpp/language/static assert") for `static_assert` declaration |
c Static assertion Static assertion
================
### Syntax
| | | |
| --- | --- | --- |
| `_Static_assert` `(` expression `,` message `)` | | (since C11) |
| `_Static_assert` `(` expression `)` | | (since C23) |
| | | |
| --- | --- | --- |
| expression | - | any [integer constant expression](constant_expression "c/language/constant expression") |
| message | - | any [string literal](string_literal "c/language/string literal") |
This keyword is also available as convenience macro [`static_assert`](../error/static_assert "c/error/static assert"), available in the header `<assert.h>`.
### Explanation
The constant expression is evaluated at compile time and compared to zero. If it compares equal to zero, a compile-time error occurs and the compiler must display message (if provided) as part of the error message (except that characters not in [basic source character set](translation_phases "c/language/translation phases") aren't required to be displayed).
Otherwise, if expression does not equal zero, nothing happens; no code is emitted.
### Keywords
[`_Static_assert`](../keyword/_static_assert "c/keyword/ Static assert").
### Example
```
#include <assert.h>
int main(void)
{
// Test if math works.
static_assert(2 + 2 == 4, "Whoa dude!"); // or _Static_assert(...
// This will produce an error at compile time.
static_assert(sizeof(int) < sizeof(char),
"this program requires that int is less than char");
}
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.10 Static assertions (p: 105)
+ 7.2 Diagnostics <assert.h> (p: 135)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.10 Static assertions (p: 145)
+ 7.2 Diagnostics <assert.h> (p: 186-187)
### See also
| | |
| --- | --- |
| [assert](../error/assert "c/error/assert") | aborts the program if the user-specified condition is not `true`. May be disabled for release builds (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/static_assert "cpp/language/static assert") for `static_assert` declaration |
c Scope Scope
=====
Each [identifier](identifier "c/language/identifier") that appears in a C program is *visible* (that is, may be used) only in some possibly discontiguous portion of the source code called its *scope*.
Within a scope, an identifier may designate more than one entity only if the entities are in different [name spaces](name_space "c/language/name space").
C has four kinds of scopes:
* block scope
* file scope
* function scope
* function prototype scope
### Nested scopes
If two different entities named by the same identifier are in scope at the same time, and they belong to the same [name space](name_space "c/language/name space"), the scopes are nested (no other form of scope overlap is allowed), and the declaration that appears in the inner scope hides the declaration that appears in the outer scope:
```
// The name space here is ordinary identifiers.
int a; // file scope of name a begins here
void f(void)
{
int a = 1; // the block scope of the name a begins here; hides file-scope a
{
int a = 2; // the scope of the inner a begins here, outer a is hidden
printf("%d\n", a); // inner a is in scope, prints 2
} // the block scope of the inner a ends here
printf("%d\n", a); // the outer a is in scope, prints 1
} // the scope of the outer a ends here
void g(int a); // name a has function prototype scope; hides file-scope a
```
### Block scope
The scope of any identifier declared inside a [compound statement](statements#Compound_statements "c/language/statements"), including function bodies, or in any expression, declaration, or statement appearing in [if](if "c/language/if"), [switch](switch "c/language/switch"), [for](for "c/language/for"), [while](while "c/language/while"), or [do-while](do "c/language/do") statement (since C99), or within the parameter list of a [function definition](function_definition "c/language/function definition") begins at the point of declaration and ends at the end of the block or statement in which it was declared.
```
void f(int n) // scope of the function parameter 'n' begins
{ // the body of the function begins
++n; // 'n' is in scope and refers to the function parameter
// int n = 2; // error: cannot redeclare identifier in the same scope
for(int n = 0; n<10; ++n) { // scope of loop-local 'n' begins
printf("%d\n", n); // prints 0 1 2 3 4 5 6 7 8 9
} // scope of the loop-local 'n' ends
// the function parameter 'n' is back in scope
printf("%d\n", n); // prints the value of the parameter
} // scope of function parameter 'n' ends
int a = n; // Error: name 'n' is not in scope
```
| | |
| --- | --- |
| Until C99, selection and iteration statements did not establish their own block scopes (although if a compound statement was used in the statement, it had its usual block scope):
```
enum {a, b};
int different(void)
{
if (sizeof(enum {b, a}) != sizeof(int))
return a; // a == 1
return b; // b == 0 in C89, b == 1 in C99
}
```
| (since C99) |
Block-scope variables have [no linkage](storage_duration "c/language/storage duration") and [automatic storage duration](storage_duration "c/language/storage duration") by default. Note that storage duration for non-VLA local variables begins when the block is entered, but until the declaration is seen, the variable is not in scope and cannot be accessed.
### File scope
The scope of any identifier declared outside of any block or parameter list begins at the point of declaration and ends at the end of the translation unit.
```
int i; // scope of i begins
static int g(int a) { return a; } // scope of g begins (note, "a" has block scope)
int main(void)
{
i = g(2); // i and g are in scope
}
```
File-scope identifiers have [external linkage](storage_duration "c/language/storage duration") and [static storage duration](storage_duration "c/language/storage duration") by default.
### Function scope
A [label (and only a label)](statements#Labels "c/language/statements") declared inside a function is in scope everywhere in that function, in all nested blocks, before and after its own declaration. Note: a label is declared implicitly, by using an otherwise unused identifier before the colon character before any statement.
```
void f()
{
{
goto label; // label in scope even though declared later
label:;
}
goto label; // label ignores block scope
}
void g()
{
goto label; // error: label not in scope in g()
}
```
### Function prototype scope
The scope of a name introduced in the parameter list of a [function declaration](function_declaration "c/language/function declaration") that is not a definition ends at the end of the function [declarator](declarations "c/language/declarations").
```
int f(int n,
int a[n]); // n is in scope and refers to the first parameter
```
Note that if there are multiple or nested declarators in the declaration, the scope ends at the end of the nearest enclosing function declarator:
```
void f ( // function name 'f' is at file scope
long double f, // the identifier 'f' is now in scope, file-scope 'f' is hidden
char (**a)[10 * sizeof f] // 'f' refers to the first parameter, which is in scope
);
enum{ n = 3 };
int (*(*g)(int n))[n]; // the scope of the function parameter 'n'
// ends at the end of its function declarator
// in the array declarator, global n is in scope
// (this declares a pointer to function returning a pointer to an array of 3 int)
```
### Point of declaration
The scope of structure, union, and enumeration tags begins immediately after the appearance of the tag in a type specifier that declares the tag.
```
struct Node {
struct Node* next; // Node is in scope and refers to this struct
};
```
The scope of enumeration constant begins immediately after the appearance of its defining enumerator in an enumerator list.
```
enum { x = 12 };
{
enum { x = x + 1, // new x is not in scope until the comma, x is initialized to 13
y = x + 1 // the new enumerator x is now in scope, y is initialized to 14
};
}
```
The scope of any other identifier begins just after the end of its declarator and before the initializer, if any:
```
int x = 2; // scope of the first 'x' begins
{
int x[x]; // scope of the newly declared x begins after the declarator (x[x]).
// Within the declarator, the outer 'x' is still in scope.
// This declares a VLA array of 2 int.
}
```
```
unsigned char x = 32; // scope of the outer 'x' begins
{
unsigned char x = x;
// scope of the inner 'x' begins before the initializer (= x)
// this does not initialize the inner 'x' with the value 32,
// this initializes the inner 'x' with its own, indeterminate, value
}
unsigned long factorial(unsigned long n)
// declarator ends, 'factorial' is in scope from this point
{
return n<2 ? 1 : n*factorial(n-1); // recursive call
}
```
As a special case, the scope of a [type name](type "c/language/type") that is not a declaration of an identifier is considered to begin just after the place within the type name where the identifier would appear were it not omitted.
### Notes
Prior to C89, identifiers with external linkage had file scope even when introduced within a block, and because of that, a C89 compiler is not required to diagnose the use of an extern identifier that has gone out of scope (such use is undefined behavior).
Local variables within a loop body can hide variables declared in the init clause of a [for](for "c/language/for") loop in C (their scope is nested), but cannot do that in C++.
Unlike C++, C has no struct scope: names declared within a struct/union/enum declaration are in the same scope as the struct declaration (except that data members are in their own [member name space](name_space "c/language/name space")):
```
struct foo {
struct baz {};
enum color {RED, BLUE};
};
struct baz b; // baz is in scope
enum color x = RED; // color and RED are in scope
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.2.1 Scopes of identifiers (p: 28-29)
* C11 standard (ISO/IEC 9899:2011):
+ 6.2.1 Scopes of identifiers (p: 35-36)
* C99 standard (ISO/IEC 9899:1999):
+ 6.2.1 Scopes of identifiers (p: 29-30)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.2.1 Scopes of identifiers
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/scope "cpp/language/scope") for Scope |
c Analyzability Analyzability
=============
This optional extension to the C language limits the potential results of executing some forms of undefined behavior, which improves the effectiveness of static analysis of such programs. Analyzability is only guaranteed to be enabled if the [predefined macro constant](../preprocessor/replace "c/preprocessor/replace") `__STDC_ANALYZABLE__`(C11) is defined by the compiler.
If the compiler supports analyzability, any language or library construct whose behavior is undefined is further classified between *critical* and *bounded* undefined behavior, and the behavior of all bounded UB cases is limited as specified below.
### Critical undefined behavior
Critical UB is undefined behavior that might perform a memory write or a volatile memory read out of bounds of any object. A program that has critical undefined behavior may be susceptible to security exploits.
Only the following undefined behaviors are critical:
* access to an object outside of its [lifetime](lifetime "c/language/lifetime") (e.g. through a dangling pointer)
* write to an object whose declarations are not [compatible](type#Compatible_types "c/language/type")
* function call through a function pointer whose type is not [compatible](type#Compatible_types "c/language/type") with the type of the function it points to
* [lvalue expression](value_category "c/language/value category") is evaluated, but does not designate an object
* attempted modification of a [string literal](string_literal "c/language/string literal")
* [dereferencing](operator_member_access "c/language/operator member access") an invalid (null, indeterminate, etc) or [past-the-end](operator_arithmetic "c/language/operator arithmetic") pointer
* modification of a [const object](const "c/language/const") through a non-const pointer
* call to a standard library function or macro with an invalid argument
* call to a variadic standard library function with unexpected argument type (e.g. call to `[printf](../io/fprintf "c/io/fprintf")` with an argument of the type that doesn't match its conversion specifier)
* `[longjmp](../program/longjmp "c/program/longjmp")` where there is no `[setjmp](../program/setjmp "c/program/setjmp")` up the calling scope, across threads, or from within the scope of a VM type.
* any use of the pointer that was deallocated by `[free](../memory/free "c/memory/free")` or `[realloc](../memory/realloc "c/memory/realloc")`
* any [string](../string/byte "c/string/byte") or [wide string](../string/wide "c/string/wide") library function accesses an array out of bounds
### Bounded undefined behavior
Bounded UB is undefined behavior that cannot perform an illegal memory write, although it may trap and may produce or store indeterminate values.
* All undefined behavior not listed as critical is bounded, including
+ multithreaded data races
+ use of a [indeterminate values](initialization "c/language/initialization") with automatic storage duration
+ [strict aliasing](object#Strict_aliasing "c/language/object") violations
+ [misaligned](object#alignment "c/language/object") object access
+ signed integer overflow
+ [unsequenced side-effects](eval_order "c/language/eval order") modify the same scalar or modify and read the same scalar
+ floating-to-integer or pointer-to-integer [conversion](conversion "c/language/conversion") overflow
+ [bitwise shift](operator_arithmetic "c/language/operator arithmetic") by a negative or too large bit count
+ [integer division](operator_arithmetic "c/language/operator arithmetic") by zero
+ use of a void expression
+ direct [assignment](operator_assignment "c/language/operator assignment") or `[memcpy](../string/byte/memcpy "c/string/byte/memcpy")` of inexactly-overlapped objects
+ [restrict](restrict "c/language/restrict") violations
+ etc.. ALL undefined behavior that's not in the critical list.
### Notes
Bounded undefined behavior disables certain optimizations: compilation with analyzability enabled preserves source-code causality, which [may be violated](as_if "c/language/as if") by undefined behavior otherwise.
Analyzability extension permits, as a form of implementation-defined behavior, for the [runtime constraint handler](../error/set_constraint_handler_s "c/error/set constraint handler s") to be invoked when a trap occurs.
### References
* C11 standard (ISO/IEC 9899:2011):
+ 6.10.8.3/1 Conditional feature macros (p: 177)
+ Annex L Analyzability (p: 652-653)
c Type Type
====
(See also [arithmetic types](arithmetic_types "c/language/arithmetic types") for the details on most built-in types and [the list of type-related utilities](../types "c/types") that are provided by the C library).
[Objects](object "c/language/object"), [functions](functions "c/language/functions"), and [expressions](expressions "c/language/expressions") have a property called *type*, which determines the interpretation of the binary value stored in an object or evaluated by the expression.
### Type classification
The C type system consists of the following types:
* the type `void`
* basic types
* the type `char`
* signed integer types
+ standard: `signed char`, `short`, `int`, `long`, `long long` (since C99)
| | |
| --- | --- |
| * extended: implementation defined, e.g. `__int128`
| (since C99) |
* unsigned integer types
+ standard: `_Bool`, (since C99) `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, `unsigned long long` (since C99)
| | |
| --- | --- |
| * extended: implementation-defined, e.g. `__uint128`
| (since C99) |
* floating-point types
+ real floating-point types: `float`, `double`, `long double`
| | |
| --- | --- |
| * decimal real floating-point types: `_Decimal32`, `_Decimal64`, `_Decimal128`
| (since C23) |
| * complex types: `float _Complex`, `double _Complex`, `long double _Complex`
* imaginary types: `float _Imaginary`, `double _Imaginary`, `long double _Imaginary`
| (since C99) |
* [enumerated types](enum "c/language/enum")
* derived types
+ [array types](array "c/language/array")
+ [structure types](struct "c/language/struct")
+ [union types](union "c/language/union")
+ [function types](functions "c/language/functions")
+ [pointer types](pointer "c/language/pointer")
| | |
| --- | --- |
| * [atomic types](atomic "c/language/atomic")
| (since C11) |
For every type listed above several qualified versions of its type may exist, corresponding to the combinations of one, two, or all three of the [`const`](const "c/language/const"), [`volatile`](volatile "c/language/volatile"), and [`restrict`](restrict "c/language/restrict") qualifiers (where allowed by the qualifier's semantics).
#### Type groups
* *object types*: all types that aren't function types
* *character types*: `char`, `signed char`, `unsigned char`
* *integer types*: `char`, signed integer types, unsigned integer types, enumerated types
* *real types*: integer types and real floating types
* [arithmetic types](arithmetic_types "c/language/arithmetic types"): integer types and floating types
* *scalar types*: arithmetic types, pointer types, and `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` (since C23)
* *aggregate types*: array types and structure types
* *derived declarator types*: array types, function types, and pointer types
### Compatible types
In a C program, the declarations referring to the same object or function in *different translation units* do not have to use the same type. They only have to use sufficiently similar types, formally known as *compatible types*. Same applies to function calls and lvalue accesses; argument types must be *compatible* with parameter types and lvalue expression type must be *compatible* with the object type that is accessed.
The types `T` and `U` are compatible, if.
* they are the same type (same name or aliases introduced by a [typedef](typedef "c/language/typedef"))
* they are identically cvr-qualified versions of compatible unqualified types
* they are pointer types and are pointing to compatible types
* they are array types, and
+ their element types are compatible, and
+ if both have constant size, that size is the same. Note: arrays of unknown bound are compatible with any array of compatible element type. VLA is compatible with any array of compatible element type. (since C99)
* they are both structure/union/enumeration types, and
* (C99)if one is declared with a tag, the other must also be declared with the same tag.
* if both are completed types, their members must correspond exactly in number, be declared with compatible types, and have matching names.
* additionally, if they are enumerations, corresponding members must also have the same values.
* additionally, if they are structures or unions,
+ Corresponding members must be declared in the same order (structures only)
+ Corresponding bit fields must have the same widths.
* one is an enumerated type and the other is that enumeration's underlying type
* they are function types, and
+ their return types are compatible
+ they both use parameter lists, the number of parameters (including the use of the ellipsis) is the same, and the corresponding parameter, after applying array-to-pointer and function-to-pointer type adjustments and after stripping top-level qualifiers, have compatible types
+ one is an old-style (parameter-less) definition, the other has a parameter list, the parameter list does not use an ellipsis and each parameter is compatible (after function parameter type adjustment) with the corresponding old-style parameter after default argument promotions
+ one is an old-style (parameter-less) declaration, the other has a parameter list, the parameter list does not use an ellipsis, and all parameters (after function parameter type adjustment) are unaffected by default argument promotions
The type `char` is not compatible with `signed char` and not compatible with `unsigned char`.
If two declarations refer to the same object or function and do not use compatible types, the behavior of the program is undefined.
```
// Translation Unit 1
struct S {int a;};
extern struct S *x; // compatible with TU2's x, but not with TU3's x
// Translation Unit 2
struct S;
extern struct S *x; // compatible with both x's
// Translation Unit 3
struct S {float a;};
extern struct S *x; // compatible with TU2's x, but not with TU1's x
// the behavior is undefined
```
```
// Translation Unit 1
#include <stdio.h>
struct s {int i;}; // compatible with TU3's s, but not TU2's
extern struct s x = {0}; // compatible with TU3's x
extern void f(void); // compatible with TU2's f
int main()
{
f();
return x.i;
}
// Translation Unit 2
struct s {float f;}; // compatible with TU4's s, but not TU1's s
extern struct s y = {3.14}; // compatible with TU4's y
void f() // compatible with TU1's f
{
return;
}
// Translation Unit 3
struct s {int i;}; // compatible with TU1's s, but not TU2's s
extern struct s x; // compatible with TU1's x
// Translation Unit 4
struct s {float f;}; // compatible with TU2's s, but not TU1's s
extern struct s y; // compatible with TU2's y
// the behavior is well-defined: only multiple declarations
// of objects and functions must have compatible types, not the types themselves
```
Note: C++ has no concept of compatible types. A C program that declares two types that are compatible but not identical in different translation units is not a valid C++ program.
### Composite types
A composite type can be constructed from two types that are compatible; it is a type that is compatible with both of the two types and satisfies the following conditions:
* If both types are array types, the following rules are applied:
+ If one type is an array of known constant size, the composite type is an array of that size.
| | |
| --- | --- |
| * Otherwise, if one type is a VLA whose size is specified by an expression that is not evaluated, the behavior is undefined.
* Otherwise, if one type is a VLA whose size is specified, the composite type is a VLA of that size.
* Otherwise, if one type is a VLA of unspecified size, the composite type is a VLA of unspecified size.
| (since C99) |
* Otherwise, both types are arrays of unknown size and the composite type is an array of unknown size.
* If only one type is a function type with a parameter type list (a function prototype), the composite type is a function prototype with the parameter type list.
* If both types are function types with parameter type lists, the type of each parameter in the composite parameter type list is the composite type of the corresponding parameters.
The element type of the composite type is the composite type of the two element types. These rules apply recursively to the types from which the two types are derived.
```
// Given the following two file scope declarations:
int f(int (*)(), double (*)[3]);
int f(int (*)(char *), double (*)[]);
// The resulting composite type for the function is:
int f(int (*)(char *), double (*)[3]);
```
For an identifier with internal or external [linkage](storage_duration "c/language/storage duration") declared in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the type of the identifier at the later declaration becomes the composite type.
### Incomplete types
An incomplete type is an object type that lacks sufficient information to determine the size of the objects of that type. An incomplete type may be completed at some point in the translation unit.
The following types are incomplete:
* the type `void`. This type cannot be completed.
* array type of unknown size. It can be completed by a later declaration that specifies the size.
```
extern char a[]; // the type of a is incomplete (this typically appears in a header)
char a[10]; // the type of a is now complete (this typically appears in a source file)
```
* structure or union type of unknown content. It can be completed by a declaration of the same structure or union that defines its content later in the same scope.
```
struct node {
struct node *next; // struct node is incomplete at this point
}; // struct node is complete at this point
```
### Type names
A type may have to be named in context other than the [declaration](declarations "c/language/declarations"). In these situations, *type name* is used, which is, grammatically, exactly the same as a list of *type-specifiers* and *type-qualifiers*, followed by the *declarator* (see [declarations](declarations "c/language/declarations")) as would be used to declare a single object or function of this type, except that the identifier is omitted:
```
int n; // declaration of an int
sizeof(int); // use of type name
int *a[3]; // declaration of an array of 3 pointers to int
sizeof(int *[3]); // use of type name
int (*p)[3]; // declaration of a pointer to array of 3 int
sizeof(int (*)[3]); // use of type name
int (*a)[*] // declaration of pointer to VLA (in a function parameter)
sizeof(int (*)[*]) // use of type name (in a function parameter)
int *f(void); // declaration of function
sizeof(int *(void)); // use of type name
int (*p)(void); // declaration of pointer to function
sizeof(int (*)(void)); // use of type name
int (*const a[])(unsigned int, ...) = {0}; // array of pointers to functions
sizeof(int (*const [])(unsigned int, ...)); // use of type name
```
Except the redundant parentheses around the identifier are meaningful in a type-name and represent "function with no parameter specification":
```
int (n); // declares n of type int
sizeof(int ()); // uses type "function returning int"
```
Type names are used in the following situations:
* [cast](cast "c/language/cast")
* [sizeof](sizeof "c/language/sizeof")
| | |
| --- | --- |
| * [compound literal](compound_literal "c/language/compound literal")
| (since C99) |
| * [generic selection](generic "c/language/generic")
* [\_Alignof](_alignof "c/language/ Alignof")
* [\_Alignas](_alignas "c/language/ Alignas")
* [\_Atomic](atomic "c/language/atomic") (when used as a type specifier)
| (since C11) |
A type name may introduce a new type:
```
void* p = (void*)(struct X {int i;} *)0;
// type name "struct X {int i;}*" used in the cast expression
// introduces the new type "struct X"
struct X x = {1}; // struct X is now in scope
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.2.5 Types (p: 31-33)
+ 6.2.6 Representations of types (p: 31-35)
+ 6.2.7 Compatible type and composite type (p: 35-36)
* C11 standard (ISO/IEC 9899:2011):
+ 6.2.5 Types (p: 39-43)
+ 6.2.6 Representations of types (p: 44-46)
+ 6.2.7 Compatible type and composite type (p: 47-48)
* C99 standard (ISO/IEC 9899:1999):
+ 6.2.5 Types (p: 33-37)
+ 6.2.6 Representations of types (p: 37-40)
+ 6.2.7 Compatible type and composite type (p: 40-41)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.2.5 Types
+ 3.1.2.6 Compatible type and composite type
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/type "cpp/language/type") for Type |
| programming_docs |
c File scope File scope
==========
If the declarator or type specifier that declares the identifier appears outside of any block or list of parameters, the identifier has file scope, which terminates at the end of the translation unit.
So, placement of an identifier's declaration (in a declarator or type specifier) outside any block or list of parameters means that the identifier has file scope. File scope of an identifier extends from the declaration to the end of the translation unit in which the declaration appears.
### Example
Identifiers a, b, f, and g have file scope.
```
#include <stdio.h>
int a = 1;
static int b = 2;
void f (void) {printf("from function f()\n");}
static void g (void) {printf("from function g()\n");}
int main(void)
{
f();
g();
return 0;
}
/* end of this translation unit, end of file scope */
```
Possible output:
```
from function f()
from function g()
```
c Atomic types Atomic types
============
### Syntax
| | | |
| --- | --- | --- |
| `_Atomic` `(` type-name `)` | (1) | (since C11) |
| `_Atomic` type-name | (2) | (since C11) |
1) Use as a type specifier; this designates a new atomic type
2) Use as a type qualifier; this designates the atomic version of type-name. In this role, it may be mixed with [const](const "c/language/const"), [volatile](volatile "c/language/volatile"), and [restrict](restrict "c/language/restrict")), although unlike other qualifiers, the atomic version of type-name may have a different size, alignment, and object representation.
| | | |
| --- | --- | --- |
| type-name | - | any type other than array or function. For (1), type-name also cannot be atomic or cvr-qualified |
The header `<stdatomic.h>` defines [37 convenience type aliases](../thread#Atomic_operations "c/thread"), from [`atomic_bool`](../thread#Atomic_operations "c/thread") to [`atomic_uintmax_t`](../thread#Atomic_operations "c/thread"), which simplify the use of this keyword with built-in and library types.
```
_Atomic const int * p1; // p is a pointer to an atomic const int
const atomic_int * p2; // same
const _Atomic(int) * p3; // same
```
If the macro constant `__STDC_NO_ATOMICS__` is defined by the compiler, the keyword `_Atomic` is not provided.
### Explanation
Objects of atomic types are the only objects that are free from [data races](memory_model "c/language/memory model"); that is, they may be modified by two threads concurrently or modified by one and read by another.
Each atomic object has its own associated *modification order*, which is a total order of modifications made to that object. If, from some thread's point of view, modification `A` of some atomic M [happens-before](../atomic/memory_order "c/atomic/memory order") modification `B` of the same atomic M, then in the modification order of M, A occurs before B.
Note that although each atomic object has its own modification order, there is no single total order; different threads may observe modifications to different atomic objects in different orders.
There are four coherences that are guaranteed for all atomic operations:
* **write-write coherence**: If an operation A that modifies an atomic object M *happens-before* an operation B that modifies M, then A appears earlier than B in the modification order of M.
* **read-read coherence**: If a value computation A of an atomic object M happens before a value computation B of M, and A takes its value from a side effect X on M, then the value computed by B is either the value stored by X or is the value stored by a side effect Y on M, where Y appears later than X in the modification order of M.
* **read-write coherence**: If a value computation A of an atomic object M *happens-before* an operation B on M, then A takes its value from a side effect X on M, where X appears before B in the modification order of M.
* **write-read coherence**: If a side effect X on an atomic object M *happens-before* a value computation B of M, then the evaluation B takes its value from X or from a side effect Y that appears after X in the modification order of M.
Some atomic operations are also synchronization operations; they may have additional release semantics, acquire semantics, or sequentially-consistent semantics. See `[memory\_order](../atomic/memory_order "c/atomic/memory order")`.
Built-in [increment and decrement operators](operator_incdec "c/language/operator incdec") and [compound assignment](operator_assignment "c/language/operator assignment") are read-modify-write atomic operations with total sequentially consistent ordering (as if using `[memory\_order\_seq\_cst](../atomic/memory_order "c/atomic/memory order")`). If less strict synchronization semantics are desired, the [standard library functions](../thread#Atomic_operations "c/thread") may be used instead.
Atomic properties are only meaningful for [lvalue expressions](value_category "c/language/value category"). Lvalue-to-rvalue conversion (which models a memory read from an atomic location to a CPU register) strips atomicity along with other qualifiers.
### Notes
Accessing a member of an atomic struct/union is undefined behavior.
The library type `[sig\_atomic\_t](http://en.cppreference.com/w/c/program/sig_atomic_t)` does not provide inter-thread synchronization or memory ordering, only atomicity.
The [volatile](volatile "c/language/volatile") types do not provide inter-thread synchronization, memory ordering, or atomicity.
Implementations are recommended to ensure that the representation of `_Atomic(T)` in C is same as that of `std::atomic<T>` in C++ for every possible type `T`. The mechanisms used to ensure atomicity and memory ordering should be compatible.
### Keywords
[`_Atomic`](../keyword/_atomic "c/keyword/ Atomic").
### Example
```
#include <stdio.h>
#include <threads.h>
#include <stdatomic.h>
atomic_int acnt;
int cnt;
int f(void* thr_data)
{
for(int n = 0; n < 1000; ++n) {
++cnt;
++acnt;
// for this example, relaxed memory order is sufficient, e.g.
// atomic_fetch_add_explicit(&acnt, 1, memory_order_relaxed);
}
return 0;
}
int main(void)
{
thrd_t thr[10];
for(int n = 0; n < 10; ++n)
thrd_create(&thr[n], f, NULL);
for(int n = 0; n < 10; ++n)
thrd_join(thr[n], NULL);
printf("The atomic counter is %u\n", acnt);
printf("The non-atomic counter is %u\n", cnt);
}
```
Possible output:
```
The atomic counter is 10000
The non-atomic counter is 8644
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.2.4 Atomic type specifiers (p: 87)
+ 7.17 Atomics <stdatomic.h> (p: 200-209)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.2.4 Atomic type specifiers (p: 121)
+ 7.17 Atomics <stdatomic.h> (p: 273-286)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic "cpp/atomic/atomic") for `atomic` |
c Increment/decrement operators Increment/decrement operators
=============================
Increment/decrement operators are unary operators that increment/decrement the value of a variable by 1.
They can have postfix form:
| | | |
| --- | --- | --- |
| expr `++` | | |
| expr `--` | | |
As well as the prefix form:
| | | |
| --- | --- | --- |
| `++` expr | | |
| `--` expr | | |
The operand expr of both prefix and postfix increment or decrement must be a [modifiable lvalue](value_category "c/language/value category") of [integer type](type "c/language/type") (including `_Bool` and enums), real floating type, or a pointer type. It may be cvr-qualified, unqualified, or [atomic](atomic "c/language/atomic").
The result of the postfix increment and decrement operators is the value of expr.
The result of the prefix increment operator is the result of adding the value `1` to the value of expr: the expression `++e` is equivalent to `e+=1`. The result of the prefix decrement operator is the result of subtracting the value `1` from the value of expr: the expression `--e` is equivalent to `e-=1`.
Increment operators initiate the side-effect of adding the value `1` of appropriate type to the operand. Decrement operators initiate the side-effect of subtracting the value `1` of appropriate type from the operand. As with any other side-effects, these operations complete at or before the next [sequence point](eval_order "c/language/eval order"). `int a = 1; int b = a++; // stores 1+a (which is 2) to a // returns the value of a (which is 1) // After this line, b == 1 and a == 2 a = 1; int c = ++a; // stores 1+a (which is 2) to a // returns 1+a (which is 2) // after this line, c == 2 and a == 2`.
| | |
| --- | --- |
| Post-increment or post-decrement on any [atomic variable](atomic "c/language/atomic") is an atomic read-modify-write operation with memory order `[memory\_order\_seq\_cst](../atomic/memory_order "c/atomic/memory order")`. | (since C11) |
See [arithmetic operators](operator_arithmetic "c/language/operator arithmetic") for limitations on pointer arithmetic, as well as for implicit conversions applied to the operands.
### Notes
Because of the side-effects involved, increment and decrement operators must be used with care to avoid undefined behavior due to violations of [sequencing rules](eval_order "c/language/eval order").
Increment/decrement operators are not defined for complex or imaginary types: the usual definition of adding/subtracting the real number 1 would have no effect on imaginary types, and making it add/subtract `i` for imaginaries but `1` for complex numbers would have made it handle `0+yi` different from `yi`.
Unlike C++ (and some implementations of C), the increment/decrement expressions are never themselves lvalues: `&++a` is invalid.
### Example
```
#include <stdlib.h>
#include <stdio.h>
int main(void) {
int a = 1;
int b = 1;
printf("\n");
printf("original values: a == %d, b == %d\n", a, b);
printf("result of postfix operators: a++ == %d, b-- == %d\n", a++, b--);
printf("after postfix operators applied: a == %d, b == %d\n", a, b);
// Reset a and b.
a = 1;
b = 1;
printf("\n");
printf("original values: a == %d, b == %d\n", a, b);
printf("result of prefix operators: ++a == %d, --b == %d\n", ++a, --b);
printf("after prefix operators applied: a == %d, b == %d\n", a, b);
}
```
Output:
```
original values: a == 1, b == 1
result of postfix operators: a++ == 1, b-- == 1
after postfix operators applied: a == 2, b == 0
original values: a == 1, b == 1
result of prefix operators: ++a == 2, --b == 0
after prefix operators applied: a == 2, b == 0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 6.5.2.4 Postfix increment and decrement operators (p: 85)
+ 6.5.3.1 Prefix increment and decrement operators (p: 88)
* C99 standard (ISO/IEC 9899:1999):
+ 6.5.2.4 Postfix increment and decrement operators (p: 75)
+ 6.5.3.1 Prefix increment and decrement operators (p: 78)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.3.2.4 Postfix increment and decrement operators
+ 3.3.3.1 Prefix increment and decrement operators
### See Also
[Operator precedence](operator_precedence "c/language/operator precedence").
| Common operators |
| --- |
| [assignment](operator_assignment "c/language/operator assignment") | **incrementdecrement** | [arithmetic](operator_arithmetic "c/language/operator arithmetic") | [logical](operator_logical "c/language/operator logical") | [comparison](operator_comparison "c/language/operator comparison") | [memberaccess](operator_member_access "c/language/operator member access") | [other](operator_other "c/language/operator other") |
| `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b`. | `a[b] *a &a a->b a.b`. | `a(...) a, b (type) a ? : sizeof _Alignof` (since C11). |
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_incdec "cpp/language/operator incdec") for Increment/decrement operators |
c inline function specifier inline function specifier
=========================
Declares an [inline function](https://en.wikipedia.org/wiki/inline_function "enwiki:inline function").
### Syntax
| | | |
| --- | --- | --- |
| `inline` function\_declaration | | (since C99) |
### Explanation
The intent of the `inline` specifier is to serve as a hint for the compiler to perform optimizations, such as [function inlining](https://en.wikipedia.org/wiki/inline_expansion "enwiki:inline expansion"), which usually require the definition of a function to be visible at the call site. The compilers can (and usually do) ignore presence or absence of the `inline` specifier for the purpose of optimization.
If the compiler performs function inlining, it replaces a call of that function with its body, avoiding the overhead of a function call (placing data on stack and retrieving the result), which may result in a larger executable as the code for the function has to be repeated multiple times. The result is similar to [function-like macros](../preprocessor/replace "c/preprocessor/replace"), except that identifiers and macros used in the function refer to the definitions visible at the point of definition, not at the point of call.
Regardless of whether inlining takes place, the following semantics of inline functions are guaranteed:
Any function with internal linkage may be declared `static inline` with no other restrictions.
A non-static inline function cannot define a non-const function-local static and cannot refer to a file-scope static.
```
static int x;
inline void f(void)
{
static int n = 1; // error: non-const static in a non-static inline function
int k = x; // error: non-static inline function accesses a static variable
}
```
If a non-static function is declared `inline`, then it must be defined in the same translation unit. The inline definition that does not use `extern` is not externally visible and does not prevent other translation units from defining the same function. This makes the `inline` keyword an alternative to `static` for defining functions inside header files, which may be included in multiple translation units of the same program.
If a function is declared `inline` in some translation units, it does not need to be declared `inline` everywhere: at most one translation unit may also provide a regular, non-inline non-static function, or a function declared `extern inline`. This one translation unit is said to provide the *external definition*. In order to avoid undefined behavior, one external definition must exist in the program if the name of the function with external linkage is used in an expression, see [one definition rule](extern#One_definition_rule "c/language/extern").
The address of an inline function with external linkage is always the address of the external definition, but when this address is used to make a function call, it's unspecified whether the *inline definition* (if present in the translation unit) or the *external definition* is called. The static objects defined within an inline definition are distinct from the static objects defined within the external definition:
```
inline const char *saddr(void) // the inline definition for use in this file
{
static const char name[] = "saddr";
return name;
}
int compare_name(void)
{
return saddr() == saddr(); // unspecified behavior, one call could be external
}
extern const char *saddr(void); // an external definition is generated, too
```
A C program should not depend on whether the inline version or the external version of a function is called, otherwise the behavior is unspecified.
### Keywords
[`inline`](../keyword/inline "c/keyword/inline").
### Notes
The `inline` keyword was adopted from C++, but in C++, if a function is declared `inline`, it must be declared `inline` in every translation unit, and also every definition of an inline function must be exactly the same (in C, the definitions may be different, and depending on the differences only results in unspecified behavior). On the other hand, C++ allows non-const function-local statics and all function-local statics from different definitions of an inline function are the same in C++ but distinct in C.
### Example
```
// file test.h
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
inline int sum (int a, int b)
{
return a+b;
}
#endif
// file sum.c
#include "test.h"
extern inline int sum (int a, int b); // provides external definition
// file test1.c
#include <stdio.h>
#include "test.h"
extern int f(void);
int main(void)
{
printf("%d\n", sum(1, 2) + f());
}
// file test2.c
#include "test.h"
int f(void)
{
return sum(2, 3);
}
```
Output:
```
8
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.4 Function specifiers (p: 125-127)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.4 Function specifiers (p: 112-113)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/inline "cpp/language/inline") for `inline` specifier |
c sizeof operator sizeof operator
===============
Queries size of the object or type.
Used when actual size of the object must be known.
### Syntax
| | | |
| --- | --- | --- |
| `sizeof(` type `)` | (1) | |
| `sizeof` expression | (2) | |
Both versions return a value of type `[size\_t](../types/size_t "c/types/size t")`.
### Explanation
1) Returns the size, in bytes, of the [object representation](object#Object_representation "c/language/object") of type
2) Returns the size, in bytes, of the object representation of the type of expression. No implicit conversions are applied to expression. ### Notes
Depending on the computer architecture, a [byte](https://en.wikipedia.org/wiki/Byte "enwiki:Byte") may consist of 8 or more bits, the exact number provided as `[CHAR\_BIT](../types/limits "c/types/limits")`.
`sizeof(char)`, `sizeof(signed char)`, and `sizeof(unsigned char)` always return `1`.
sizeof cannot be used with function types, incomplete types (including `void`), or [bit field](bit_field "c/language/bit field") lvalues.
When applied to an operand that has [structure](struct "c/language/struct") or [union](union "c/language/union") type, the result is the total number of bytes in such an object, including internal and trailing padding. The trailing padding is such that if the object were an element of an array, the alignment requirement of the next element of this array would be satisfied, in other words, `sizeof(T)` returns the size of an element of a `T[]` array.
| | |
| --- | --- |
| If type is a [VLA](array "c/language/array") type and changing the value of its size expression would not affect the result of `sizeof`, it is unspecified whether or not the size expression is evaluated. | (since C99) |
Except if the type of expression is a [VLA](array "c/language/array"), (since C99)expression is not evaluated and the `sizeof` operator may be used in an integer [constant expression](constant_expression "c/language/constant expression").
| | |
| --- | --- |
| If the type of expression is a [variable-length array](array "c/language/array") type, expression is evaluated and the size of the array it evaluates to is calculated at run time. | (since C99) |
Number of elements in any [array](array "c/language/array") `a` including VLA (since C99) may be determined with the expression `sizeof a / sizeof a[0]`. Note that if `a` has pointer type (such as after array-to-pointer conversion of function parameter type adjustment), this expression would simply divide the number of bytes in a pointer type by the number of bytes in the pointed type.
### Keywords
[`sizeof`](../keyword/sizeof "c/keyword/sizeof").
### Example
sample output corresponds to a platform with 64-bit pointers and 32-bit int.
```
#include <stdio.h>
int main(void)
{
short x;
// type argument:
printf("sizeof(float) = %zu\n", sizeof(float));
printf("sizeof(void(*)(void)) = %zu\n", sizeof(void(*)(void)));
printf("sizeof(char[10]) = %zu\n", sizeof(char[10]));
// printf("sizeof(void(void)) = %zu\n", sizeof(void(void))); // Error: function type
// printf("sizeof(char[]) = %zu\n", sizeof(char[])); // Error: incomplete type
// expression argument:
printf("sizeof 'a' = %zu\n", sizeof 'a'); // type of 'a' is int
// printf("sizeof main = %zu\n", sizeof main); // Error: Function type
printf("sizeof &main = %zu\n", sizeof &main);
printf("sizeof \"hello\" = %zu\n", sizeof "hello"); // type is char[6]
printf("sizeof x = %zu\n", sizeof x); // type of x is short
printf("sizeof (x+1) = %zu\n", sizeof(x+1)); // type of x+1 is int
}
```
Possible output:
```
sizeof(float) = 4
sizeof(void(*)(void)) = 8
sizeof(char[10]) = 10
sizeof 'a' = 4
sizeof &main = 8
sizeof "hello" = 6
sizeof x = 2
sizeof (x+1) = 4
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 6.5.3.4 The sizeof and \_Alignof operators (p: 90-91)
* C99 standard (ISO/IEC 9899:1999):
+ 6.5.3.4 The sizeof operator (p: 80-81)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.3.3.4 The sizeof operator
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/sizeof "cpp/language/sizeof") for `sizeof` operator |
| programming_docs |
c goto statement goto statement
==============
Transfers control unconditionally to the desired location.
Used when it is otherwise impossible to transfer control to the desired location using conventional constructs.
### Syntax
| | | |
| --- | --- | --- |
| attr-spec-seq(optional) `goto` label `;` | | |
| | | |
| --- | --- | --- |
| label | - | target [label](statements#Labels "c/language/statements") for the `goto` statement |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the `goto` statement |
### Explanation
The `goto` statement causes an unconditional jump (transfer of control) to the statement prefixed by the named label (which must appear in the same function as the goto statement), except when this jump would enter the scope of a [variable-length array](array "c/language/array") or another [variably-modified type](declarations "c/language/declarations"). (since C99).
A label is an identifier followed by a colon (`:`) and a statement (until C23). Labels are the only identifiers that have *function scope*: they can be used (in a goto statement) anywhere in the same function in which they appear. There may be multiple labels before any statement.
| | |
| --- | --- |
| Entering the scope of a non-variably modified variable is permitted:
```
goto lab1; // OK: going into the scope of a regular variable
int n = 5;
lab1:; // Note, n is uninitialized, as if declared by int n;
// goto lab2; // Error: going into the scope of two VM types
double a[n]; // a VLA
int (*p)[n]; // a VM pointer
lab2:
```
If `goto` leaves the scope of a VLA, it is deallocated (and may be reallocated if its initialization is executed again):
```
{
int n = 1;
label:;
int a[n]; // re-allocated 10 times, each with a different size
if (n++ < 10) goto label; // leaving the scope of a VM
}
```
| (since C99) |
### Keywords
[`goto`](../keyword/goto "c/keyword/goto").
### Notes
| | |
| --- | --- |
| Because declarations are not statements, a label before a declaration must use a null statement (a semicolon immediately after the colon). Same applies to a label before the end of a block. | (until C23) |
C++ imposes additional limitations on the `goto` statement, but allows labels before declarations (which are statements in C++).
### Example
```
#include <stdio.h>
int main(void)
{
// goto can be used to leave a multi-level loop easily
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
printf("(%d;%d)\n",x,y);
if (x + y >= 3) goto endloop;
}
}
endloop:;
}
```
Output:
```
(0;0)
(0;1)
(0;2)
(1;0)
(1;1)
(1;2)
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.8.6.1 The goto statement (p: 110-111)
* C11 standard (ISO/IEC 9899:2011):
+ 6.8.6.1 The goto statement (p: 152-153)
* C99 standard (ISO/IEC 9899:1999):
+ 6.8.6.1 The goto statement (p: 137-138)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.6.6.1 The goto statement
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/goto "cpp/language/goto") for `goto` statement |
c Static storage duration Static storage duration
=======================
An object whose identifier is declared without the storage-class specifier `_Thread_local`, and either with external or internal [linkage](storage_duration#Linkage "c/language/storage duration") or with the storage-class specifier `static`, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
### Notes
Since its stored value is initialized only once, an object with static storage duration can profile the invocations of a function.
The other use of the keyword `static` is [file scope](file_scope "c/language/file scope").
### Example
```
#include <stdio.h>
void f (void)
{
static int count = 0; // static variable
int i = 0; // automatic variable
printf("%d %d\n", i++, count++);
}
int main(void)
{
for (int ndx=0; ndx<10; ++ndx)
f();
}
```
Output:
```
0 0
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9
```
c Generic selection Generic selection
=================
Provides a way to choose one of several expressions at compile time, based on a type of a controlling expression.
### Syntax
| | | |
| --- | --- | --- |
| `_Generic` `(` controlling-expression `,` association-list `)` | | (since C11) |
where association-list is a comma-separated list of associations, each of which has the syntax.
| | | |
| --- | --- | --- |
| type-name `:` expression | | |
| `default` `:` expression | | |
where.
| | | |
| --- | --- | --- |
| type-name | - | any complete [object type](type "c/language/type") that isn't variably-modified (that is, not VLA or pointer to VLA). |
| controlling-expression | - | any expression (except for the [comma operator](operator_other#Comma_operator "c/language/operator other")) whose type must be compatible with one of the type-names if the `default` association is not used |
| expression | - | any expression (except for the [comma operator](operator_other#Comma_operator "c/language/operator other")) of any type and value category |
No two type-names in the association-list may specify [compatible types](type#Compatible_types "c/language/type"). There may be only one association that uses the keyword `default`. If `default` is not used and none of the type-names are compatible with the type of the controlling expression, the program will not compile.
### Explanation
First, the type of controlling-expression undergoes [lvalue conversions](conversion#Lvalue_conversions "c/language/conversion"). The conversion is performed in type domain only: it discards the top-level cvr-qualifiers and atomicity and applies array-to-pointer/function-to-pointer transformations to the type of the controlling expression, without initiating any side-effects or calculating any values.
The type after conversion is compared with type-names from the list of associations.
If the type is [compatible](type#Compatible_types "c/language/type") with the type-name of one of the associations, then the type, value, and [value category](value_category "c/language/value category") of the generic selection are the type, value, and value category of the expression that appears after the colon for that type-name.
If none of the type-names are compatible with the type of the controlling-expression, and the `default` association is provided, then the type, value, and value category of the generic selection are the type, value, and value category of the expression after the `default :` label.
### Notes
The controlling-expression and the expressions of the selections that are not chosen are never evaluated.
Because of the lvalue conversions, `"abc"` matches `char*` and not `char[4]` and `(int const){0}` matches `int`, and not `const int`.
All [value categories](value_category "c/language/value category"), including function designators and void expressions, are allowed as expressions in a generic selection, and if selected, the generic selection itself has the same value category.
The [type-generic math macros](../numeric/tgmath "c/numeric/tgmath") from `<tgmath.h>`, introduced in C99, were implemented in compiler-specific manner. Generic selections, introduced in C11, gave the programmers the ability to write similar type-dependent code.
Generic selection is similar to overloading in C++ (where one of several functions is chosen at compile time based on the types of the arguments), except that it makes the selection between arbitrary expressions.
### Keywords
[`_Generic`](../keyword/_generic "c/keyword/ Generic"), [`default`](../keyword/default "c/keyword/default").
### Example
```
#include <stdio.h>
#include <math.h>
// Possible implementation of the tgmath.h macro cbrt
#define cbrt(X) _Generic((X), \
long double: cbrtl, \
default: cbrt, \
float: cbrtf \
)(X)
int main(void)
{
double x = 8.0;
const float y = 3.375;
printf("cbrt(8.0) = %f\n", cbrt(x)); // selects the default cbrt
printf("cbrtf(3.375) = %f\n", cbrt(y)); // converts const float to float,
// then selects cbrtf
}
```
Output:
```
cbrt(8.0) = 2.000000
cbrtf(3.375) = 1.500000
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [DR 481](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_481) | C11 | it was underspecified if the controlling expression undergoes lvalue conversions | it undergoes |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.5.1.1 Generic selection (p: 56-57)
* C11 standard (ISO/IEC 9899:2011):
+ 6.5.1.1 Generic selection (p: 78-79)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/templates "cpp/language/templates") for Templates |
c return statement return statement
================
Terminates current function and returns specified value to the caller function.
### Syntax
| | | |
| --- | --- | --- |
| attr-spec-seq(optional) `return` expression `;` | (1) | |
| attr-spec-seq(optional) `return` `;` | (2) | |
| | | |
| --- | --- | --- |
| expression | - | expression used for initializing the return value of the function |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the `return` statement |
### Explanation
1) Evaluates the expression, terminates the current function and returns the result of the expression to the caller (the value returned becomes the value of the function call expression). Only valid if the function return type is not `void`.
2) Terminates the current function. Only valid if the function return type is `void`. If the type of the expression is different from the return type of the function, its value is [converted](conversion "c/language/conversion") as if by assignment to an object whose type is the return type of the function, except that overlap between object representations is permitted:
```
struct s { double i; } f(void); // function returning struct s
union { struct { int f1; struct s f2; } u1;
struct { struct s f3; int f4; } u2; } g;
struct s f(void)
{
return g.u1.f2;
}
int main(void)
{
// g.u2.f3 = g.u1.f2; // undefined behavior (overlap in assignment)
g.u2.f3 = f(); // well-defined
}
```
If the return type is a real floating type, the result may be represented in [greater range and precision](../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD") than implied by the new type.
Reaching the end of a function returning `void` is equivalent to `return;`. Reaching the end of any other value-returning function is undefined behavior if the result of the function is used in an expression (it is allowed to discard such return value). For `main`, see [`main` function](main_function "c/language/main function").
| | |
| --- | --- |
| Executing the `return` statement in a [no-return function](_noreturn "c/language/ Noreturn") is undefined behavior. | (since C11) |
### Keywords
[`return`](../keyword/return "c/keyword/return").
### Example
```
#include <stdio.h>
void fa(int i)
{
if (i == 2)
return;
printf("fa(): %d\n", i);
} // implied return;
int fb(int i)
{
if (i > 4)
return 4;
printf("fb(): %d\n", i);
return 2;
}
int main(void)
{
fa(2);
fa(1);
int i = fb(5); // the return value 4 used to initializes i
i = fb(i); // the return value 2 used as rhs of assignment
printf("main(): %d\n", i);
}
```
Output:
```
fa(): 1
fb(): 4
main(): 2
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.8.6.4 The return statement (p: 111-112)
* C11 standard (ISO/IEC 9899:2011):
+ 6.8.6.4 The return statement (p: 154)
* C99 standard (ISO/IEC 9899:1999):
+ 6.8.6.4 The return statement (p: 139)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.6.6.4 The return statement
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/return "cpp/language/return") for `return` statement |
c Undefined behavior Undefined behavior
==================
The C language standard precisely specifies the [observable behavior](as_if "c/language/as if") of C language programs, except for the ones in the following categories:
* *undefined behavior* - there are no restrictions on the behavior of the program. Examples of undefined behavior are memory accesses outside of array bounds, signed integer overflow, null pointer dereference, modification of the same scalar [more than once](eval_order "c/language/eval order") in an expression without sequence points, access to an object through a pointer of a different type, etc. Compilers are not required to diagnose undefined behavior (although many simple situations are diagnosed), and the compiled program is not required to do anything meaningful.
* *unspecified behavior* - two or more behaviors are permitted and the implementation is not required to document the effects of each behavior. For example, [order of evaluation](eval_order "c/language/eval order"), whether identical [string literals](string_literal "c/language/string literal") are distinct, etc. Each unspecified behavior results in one of a set of valid results and may produce a different result when repeated in the same program.
* *implementation-defined behavior* - unspecified behavior where each implementation documents how the choice is made. For example, number of bits in a byte, or whether signed integer right shift is arithmetic or logical.
* *locale-specific behavior* - implementation-defined behavior that depends on the [currently chosen locale](../locale/setlocale "c/locale/setlocale"). For example, whether `[islower](../string/byte/islower "c/string/byte/islower")` returns true for any character other than the 26 lowercase Latin letters.
(Note: [Strictly conforming](conformance "c/language/conformance") programs do not depend on any unspecified, undefined, or implementation-defined behavior).
The compilers are required to issue diagnostic messages (either errors or warnings) for any programs that violates any C syntax rule or semantic constraint, even if its behavior is specified as undefined or implementation-defined or if the compiler provides a language extension that allows it to accept such program. Diagnostics for undefined behavior are not otherwise required.
### UB and optimization
Because correct C programs are free of undefined behavior, compilers may produce unexpected results when a program that actually has UB is compiled with optimization enabled:
For example,
#### Signed overflow
```
int foo(int x) {
return x+1 > x; // either true or UB due to signed overflow
}
```
may be compiled as ([demo](https://godbolt.org/z/D249FL)).
```
foo:
movl $1, %eax
ret
```
#### Access out of bounds
```
int table[4] = {0};
int exists_in_table(int v)
{
// return true in one of the first 4 iterations or UB due to out-of-bounds access
for (int i = 0; i <= 4; i++) {
if (table[i] == v) return 1;
}
return 0;
}
```
May be compiled as ([demo](https://godbolt.org/z/qoD2uP)).
```
exists_in_table:
movl $1, %eax
ret
```
#### Uninitialized scalar
```
_Bool p; // uninitialized local variable
if(p) // UB access to uninitialized scalar
puts("p is true");
if(!p) // UB access to uninitialized scalar
puts("p is false");
```
May produce the following output (observed with an older version of gcc):
```
p is true
p is false
```
```
size_t f(int x)
{
size_t a;
if(x) // either x nonzero or UB
a = 42;
return a;
}
```
May be compiled as ([demo](https://godbolt.org/z/u9lBlY)).
```
f:
mov eax, 42
ret
```
#### Invalid scalar
```
int f(void) {
_Bool b = 0;
unsigned char* p =(unsigned char*)&b;
*p = 10;
// reading from b is now UB
return b == 0;
}
```
May be compiled as ([demo](https://gcc.godbolt.org/z/JGG6uI)).
```
f():
movl $11, %eax
ret
```
#### Null pointer dereference
```
int foo(int* p) {
int x = *p;
if(!p) return x; // Either UB above or this branch is never taken
else return 0;
}
int bar() {
int* p = NULL;
return *p; // Unconditional UB
}
```
may be compiled as ([foo with gcc, bar with clang](https://godbolt.org/z/W6nz9j)).
```
foo:
xorl %eax, %eax
ret
bar:
retq
```
#### Access to pointer passed to realloc
Choose clang to observe the output shown.
```
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = (int*)malloc(sizeof(int));
int *q = (int*)realloc(p, sizeof(int));
*p = 1; // UB access to a pointer that was passed to realloc
*q = 2;
if (p == q) // UB access to a pointer that was passed to realloc
printf("%d%d\n", *p, *q);
}
```
Possible output:
```
12
```
#### Infinite loop without side-effects
Choose clang to observe the output shown.
```
#include <stdio.h>
int fermat() {
const int MAX = 1000;
int a=1,b=1,c=1;
// Endless loop with no side effects is UB
while (1) {
if (((a*a*a) == ((b*b*b)+(c*c*c)))) return 1;
a++;
if (a>MAX) { a=1; b++; }
if (b>MAX) { b=1; c++; }
if (c>MAX) { c=1;}
}
return 0;
}
int main(void) {
if (fermat())
puts("Fermat's Last Theorem has been disproved.");
else
puts("Fermat's Last Theorem has not been disproved.");
}
```
Possible output:
```
Fermat's Last Theorem has been disproved.
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 3.4 Behavior (p: 3-4)
+ 4 Conformance (p: 8)
* C11 standard (ISO/IEC 9899:2011):
+ 3.4 Behavior (p: 3-4)
+ 4/2 Undefined behavior (p: 8)
* C99 standard (ISO/IEC 9899:1999):
+ 3.4 Behavior (p: 3-4)
+ 4/2 Undefined behavior (p: 7)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 1.6 DEFINITIONS OF TERMS
### External links
* [What Every C Programmer Should Know About Undefined Behavior #1/3](http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html)
* [What Every C Programmer Should Know About Undefined Behavior #2/3](http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html)
* [What Every C Programmer Should Know About Undefined Behavior #3/3](http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html)
* [Undefined behavior can result in time travel (among other things, but time travel is the funkiest)](http://blogs.msdn.com/b/oldnewthing/archive/2014/06/27/10537746.aspx)
* [Understanding Integer Overflow in C/C++](http://www.cs.utah.edu/~regehr/papers/overflow12.pdf)
* [Undefined Behavior and Fermat’s Last Theorem](https://web.archive.org/web/20201108094235/https://kukuruku.co/post/undefined-behavior-and-fermats-last-theorem/)
* [Fun with NULL pointers, part 1](http://lwn.net/Articles/342330/) (local exploit in Linux 2.6.30 caused by UB due to null pointer dereference)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/ub "cpp/language/ub") for Undefined behavior |
c Function definitions Function definitions
====================
A function definition associates the function body (a sequence of declarations and statements) with the function name and parameter list. Unlike [function declaration](function_declaration "c/language/function declaration"), function definitions are allowed at file scope only (there are no nested functions).
C supports two different forms of function definitions:
| | | |
| --- | --- | --- |
| attr-spec-seq(optional) specifiers-and-qualifiers parameter-list-declarator function-body | (1) | |
| specifiers-and-qualifiers identifier-list-declarator declaration-list function-body | (2) | (until C23) |
where.
| | | |
| --- | --- | --- |
| attr-spec-seq | - | (C23)an optional list of [attributes](attributes "c/language/attributes"), applied to the function |
| specifiers-and-qualifiers | - | a combination of * [type specifiers](declarations "c/language/declarations") that, possibly modified by the declarator, form the *return type*
* [storage class specifiers](storage_duration "c/language/storage duration"), which determine the linkage of the identifier (`static`, `extern`, or none)
* function specifiers [`inline`](inline "c/language/inline"), [`_Noreturn`](_noreturn "c/language/ Noreturn"), or none
|
| parameter-list-declarator | - | a declarator for a function type which uses a [parameter list](function_declaration "c/language/function declaration") to designate function parameters |
| identifier-list-declarator | - | a declarator for a function type which uses a [identifier list](function_declaration "c/language/function declaration") to designate function parameters |
| declaration-list | - | sequence of declarations that declare every identifier in identifier-list-declarator. These declarations cannot use initializers and the only [storage-class specifier](storage_duration "c/language/storage duration") allowed is `register`. |
| function-body | - | a [compound statement](statements#Compound_statements "c/language/statements"), that is a brace-enclosed sequence of declarations and statements, that is executed whenever this function is called |
1) New-style (C89) function definition. This definition both introduces the function itself and serves as a function prototype for any future [function call expressions](operator_other#Function_call "c/language/operator other"), forcing conversions from argument expressions to the declared parameter types.
```
int max(int a, int b)
{
return a>b?a:b;
}
double g(void)
{
return 0.1;
}
```
2) (until C23) Old-style (K&R) function definition. This definition does not behave as a prototype and any future [function call expressions](operator_other#Function_call "c/language/operator other") will perform default argument promotions.
```
int max(a, b)
int a, b;
{
return a>b?a:b;
}
double g()
{
return 0.1;
}
```
### Explanation
As with [function declarations](function_declaration "c/language/function declaration"), the return type of the function, determined by the type specifier in specifiers-and-qualifiers and possibly modified by the declarator as usual in [declarations](declarations "c/language/declarations"), must be a complete non-array object type or the type `void`. If the return type would be cvr-qualified, it is adjusted to its unqualified version for the purpose of constructing the function type.
```
void f(char *s) { puts(s); } // return type is void
int sum(int a, int b) { return a+b: } // return type is int
int (*foo(const void *p))[3] { // return type is pointer to array of 3 int
return malloc(sizeof(int[3]));
}
```
As with [function declarations](function_declaration "c/language/function declaration"), the types of the parameters are adjusted from functions to pointers and from arrays to pointers for the purpose of constructing the function type and the top-level cvr-qualifiers of all parameter types are ignored for the purpose of determining [compatible function type](type#Compatible_types "c/language/type").
| | |
| --- | --- |
| Unlike [function declarations](function_declaration "c/language/function declaration"), unnamed formal parameters are not allowed (otherwise, there would be conflicts in old-style (K&R) function definitions), they must be named even if they are not used within the function. The only exception is the special parameter list `(void)`. | (until C23) |
| Formal parameters may be unnamed in function definitions, because old-style (K&R) function definitions has been removed. Unnamed parameters are inaccessible by name within the function body. | (since C23) |
```
int f(int, int); // declaration
// int f(int, int) { return 7; } // Error until C23, OK since C23
int f(int a, int b) { return 7; } // definition
int g(void) { return 8; } // OK: void doesn't declare a parameter
```
Within the function body, every named parameter is an [lvalue](value_category "c/language/value category") expression, they have automatic [storage duration](storage_duration "c/language/storage duration") and [block scope](scope "c/language/scope"). The layout of the parameters in memory (or if they are stored in memory at all) is unspecified: it is a part of the [calling convention](https://en.wikipedia.org/wiki/Calling_convention "enwiki:Calling convention").
```
int main(int ac, char **av)
{
ac = 2; // parameters are lvalues
av = (char *[]){"abc", "def", NULL};
f(ac, av);
}
```
See [function call operator](operator_other#Function_call "c/language/operator other") for other details on the mechanics of a function call and [return](return "c/language/return") for returning from functions.
| | |
| --- | --- |
| \_\_func\_\_ Within every function-body, the special predefined variable `__func__` with block scope and static storage duration is available, as if defined immediately after the opening brace by.
```
static const char __func__[] = "function name";
```
This special identifier is sometimes used in combination with the [predefined macro constants](../preprocessor/replace "c/preprocessor/replace") `__FILE__` and `__LINE__`, for example, by `[assert](../error/assert "c/error/assert")`. | (since C99) |
### Notes
The argument list must be explicitly present in the declarator, it cannot be inherited from a typedef.
```
typedef int p(int q, int r); // p is a function type int(int, int)
p f { return q + r; } // Error
```
| | |
| --- | --- |
| In C89, specifiers-and-qualifiers was optional, and if omitted, the return type of the function defaulted to `int` (possibly amended by the declarator).
In addition, old-style definition didn't require a declaration for every parameter in declaration-list. Any parameter whose declaration was missing had type `int`.
```
max(a, b) // a and b have type int, return type is int
{
return a>b?a:b;
}
```
| (until C99) |
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [DR 423](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_423) | C89 | the return type might be qualified | the return type is implicitly disqualified |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.9.1 Function definitions (p: 113-115)
* C11 standard (ISO/IEC 9899:2011):
+ 6.9.1 Function definitions (p: 156-158)
* C99 standard (ISO/IEC 9899:1999):
+ 6.9.1 Function definitions (p: 141-143)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.7.1 Function definitions
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/function#Function_definition "cpp/language/function") for Function definition |
| programming_docs |
c Expressions Expressions
===========
An expression is a sequence of *operators* and their *operands*, that specifies a computation.
Expression evaluation may produce a result (e.g., evaluation of `2+2` produces the result `4`), may generate side-effects (e.g. evaluation of `[printf](http://en.cppreference.com/w/c/io/fprintf)("%d",4)` sends the character `'4'` to the standard output stream), and may designate objects or functions.
#### General
* [value categories](value_category "c/language/value category") (lvalue, non-lvalue object, function designator) classify expressions by their values
* [order of evaluation](eval_order "c/language/eval order") of arguments and subexpressions specifies the order in which intermediate results are obtained
### Operators
| Common operators |
| --- |
| [assignment](operator_assignment "c/language/operator assignment") | [incrementdecrement](operator_incdec "c/language/operator incdec") | [arithmetic](operator_arithmetic "c/language/operator arithmetic") | [logical](operator_logical "c/language/operator logical") | [comparison](operator_comparison "c/language/operator comparison") | [memberaccess](operator_member_access "c/language/operator member access") | [other](operator_other "c/language/operator other") |
| `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b`. | `a[b] *a &a a->b a.b`. | `a(...) a, b (type) a ? : sizeof _Alignof` (since C11). |
* [operator precedence](operator_precedence "c/language/operator precedence") defines the order in which operators are bound to their arguments
* [alternative representations](operator_alternative "c/language/operator alternative") are alternative spellings for some operators
#### Conversions
* [Implicit conversions](conversion "c/language/conversion") take place when types of operands do not match the expectations of operators
* [Casts](cast "c/language/cast") may be used to explicitly convert values from one type to another.
#### Other
* [constant expressions](constant_expression "c/language/constant expression") can be evaluated at compile time and used in compile-time context (non-VLA (since C99)array sizes, static initializers, etc)
| | |
| --- | --- |
| * [generic selections](generic "c/language/generic") can execute different expressions depending on the types of the arguments
| (since C11) |
| | |
| --- | --- |
| * Floating-point expressions may raise exceptions and report errors as specified in [`math_errhandling`](../numeric/math/math_errhandling "c/numeric/math/math errhandling")
* The standard [#pragmas](../preprocessor/impl "c/preprocessor/impl") `FENV_ACCESS`, `FP_CONTRACT`, and `CX_LIMITED_RANGE` as well as the [floating-point evaluation precision](../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD") and [rounding direction](../numeric/fenv/fe_round "c/numeric/fenv/FE round") control the way floating-point expressions are executed.
| (since C99) |
### Primary expressions
The operands of any operator may be other expressions or they may be *primary expressions* (e.g. in `1+2*3`, the operands of operator+ are the subexpression `2*3` and the primary expression `1`).
Primary expressions are any of the following:
1) Constants and literals (e.g. `2` or `"Hello, world"`)
2) Suitably declared [identifiers](identifier "c/language/identifier") (e.g. `n` or `[printf](http://en.cppreference.com/w/c/io/fprintf)`)
| | |
| --- | --- |
| 3) [Generic selections](generic "c/language/generic") | (since C11) |
Any expression in parentheses is also classified as a primary expression: this guarantees that the parentheses have higher precedence than any operator.
#### Constants and literals
Constant values of certain types may be embedded in the source code of a C program using specialized expressions known as literals (for lvalue expressions) and constants (for non-lvalue expressions).
* [integer constants](integer_constant "c/language/integer constant") are decimal, octal, or hexadecimal numbers of integer type.
* [character constants](character_constant "c/language/character constant") are individual characters of type `int` suitable for conversion to a character type or of type `char16_t`, `char32_t`, or (since C11)`wchar_t`
* [floating constants](floating_constant "c/language/floating constant") are values of type `float`, `double`, or `long double`
| | |
| --- | --- |
| * predefined constants [`true`/`false`](bool_constant "c/language/bool constant") are values of type `bool`
* predefined constant [`nullptr`](nullptr "c/language/nullptr") is a value of type `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")`
| (since C23) |
* [string literals](string_literal "c/language/string literal") are sequences of characters of type `char[]`, `char16_t[]`, `char32_t[]`, (since C11) or `wchar_t[]` that represent null-terminated strings
| | |
| --- | --- |
| * [compound literals](compound_literal "c/language/compound literal") are values of struct, union, or array type directly embedded in program code
| (since C99) |
### Unevaluated expressions
The operands of the [`sizeof` operator](sizeof "c/language/sizeof") are expressions that are not evaluated (unless they are VLAs) (since C99). Thus, `[size\_t](http://en.cppreference.com/w/c/types/size_t) n = sizeof([printf](http://en.cppreference.com/w/c/io/fprintf)("%d", 4));` does not perform console output.
| | |
| --- | --- |
| The operands of the [`_Alignof` operator](_alignof "c/language/ Alignof"), the controlling expression of a [generic selection](generic "c/language/generic"), and size expressions of VLAs that are operands of `_Alignof` are also expressions that are not evaluated. | (since C11) |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.5 Expressions (p: 55-75)
+ 6.6 Constant expressions (p: 76-77)
* C11 standard (ISO/IEC 9899:2011):
+ 6.5 Expressions (p: 76-105)
+ 6.6 Constant expressions (p: 106-107)
* C99 standard (ISO/IEC 9899:1999):
+ 6.5 Expressions (p: 67-94)
+ 6.6 Constant expressions (p: 95-96)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.3 EXPRESSIONS
+ 3.4 CONSTANT EXPRESSIONS
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/expressions "cpp/language/expressions") for Expressions |
c Constant expressions Constant expressions
====================
Several varieties of expressions are known as *constant expressions*.
### Preprocessor constant expression
The expression following [#if or #elif](../preprocessor/conditional "c/preprocessor/conditional") must expand to.
* [operators](expressions#Operators "c/language/expressions") other than [assignment](operator_assignment "c/language/operator assignment"), [increment, decrement](operator_incdec "c/language/operator incdec"), [function-call](operator_other#Function_call "c/language/operator other"), or [comma](operator_other#Comma_operator "c/language/operator other") whose arguments are preprocessor constant expressions
* [integer constants](integer_constant "c/language/integer constant")
* [character constants](character_constant "c/language/character constant")
* the special preprocessor operator `defined`
Character constants, when evaluated in `#if`-expressions, may be interpreted in the source character set, the execution character set, or some other implementation-defined character set.
| | |
| --- | --- |
| Integer arithmetic in `#if`-expressions is performed using the semantics of `[intmax\_t](../types/integer "c/types/integer")` for signed types and `[uintmax\_t](../types/integer "c/types/integer")` for unsigned types. | (since C99) |
### Integer constant expression
An integer constant expression is an expression that consists only of.
* [operators](expressions#Operators "c/language/expressions") other than [assignment](operator_assignment "c/language/operator assignment"), [increment, decrement](operator_incdec "c/language/operator incdec"), [function-call](operator_other#Function_call "c/language/operator other"), or [comma](operator_other#Comma_operator "c/language/operator other"), except that [cast](cast "c/language/cast") operators can only cast arithmetic types to integer types
* [integer constants](integer_constant "c/language/integer constant")
* [enumeration constants](enum "c/language/enum")
* [character constants](character_constant "c/language/character constant")
* [floating constants](floating_constant "c/language/floating constant"), but only if they are immediately used as operands of casts to integer type
* [`sizeof`](sizeof "c/language/sizeof") operators whose operands are not VLA (since C99)
| | |
| --- | --- |
| * [`_Alignof`](_alignof "c/language/ Alignof") operators
| (since C11) |
Integer constant expressions are evaluated at compile time. The following contexts require expressions that are known as *integer constant expressions*:
* The size of a [bit field](bit_field "c/language/bit field").
* The value of an [enumeration constant](enum "c/language/enum")
* The `case` label of a [switch statement](switch "c/language/switch")
* The size of a non-VLA (since C99) array
* Integer to pointer implicit [conversion](conversion "c/language/conversion").
| | |
| --- | --- |
| * The index in an [array designator](array_initialization "c/language/array initialization")
| (since C99) |
| * The first argument of [`_Static_assert`](_static_assert "c/language/ Static assert")
* The integer argument of [`_Alignas`](_alignas "c/language/ Alignas")
| (since C11) |
### Static initializer
Expressions that are used in the [initializers](initialization "c/language/initialization") of objects with static and thread\_local [storage duration](storage_duration "c/language/storage duration") must be expressions that may be one of the following.
1) *arithmetic constant expression*, which is an expression of any arithmetic type that consists of * [operators](expressions#Operators "c/language/expressions") other than [assignment](operator_assignment "c/language/operator assignment"), [increment, decrement](operator_incdec "c/language/operator incdec"), [function-call](operator_other#Function_call "c/language/operator other"), or [comma](operator_other#Comma_operator "c/language/operator other"), except that [cast](cast "c/language/cast") operators must be converting arithmetic types to other arithmetic types
* [integer constants](integer_constant "c/language/integer constant")
* [floating constants](floating_constant "c/language/floating constant")
* [enumeration constants](enum "c/language/enum")
* [character constants](character_constant "c/language/character constant")
* [`sizeof`](sizeof "c/language/sizeof") operators whose operands are not VLA (since C99)
| | |
| --- | --- |
| * [`_Alignof`](_alignof "c/language/ Alignof") operators
| (since C11) |
2) the null pointer constant `[NULL](../types/null "c/types/NULL")`
3) *address constant expression*, which is * a null pointer
* [lvalue](value_category "c/language/value category") designating an object of static [storage duration](storage_duration "c/language/storage duration") or a function designator, converted to a pointer either
+ by using the unary address-of operator
+ by casting an integer constant to a pointer
+ by array-to-pointer or function-to-pointer implicit [conversion](conversion "c/language/conversion")
4) *address constant expression* of some complete object type, plus or minus an *integer constant expression*
5) constant expression of one of the other forms accepted by the implementation. Unlike with integer constant expressions, static initializer expressions are not required to be evaluated at compile time; the compiler is at liberty to turn such initializers into executable code which is invoked prior to program startup.
```
static int i = 2 || 1 / 0; // initializes i to value 1
```
The value of a floating-point static initializer is never less accurate than the value of the same expression executed at run time, but it may be better.
### Floating-point constant expressions
Arithmetic constant expressions of floating-point types that are not used in static initializers are always evaluated as-if during run-time and are affected by the [current rounding](../numeric/fenv/fe_round "c/numeric/fenv/FE round") (if [FENV\_ACCESS](../preprocessor/impl "c/preprocessor/impl") is on) and report errors as specified in [`math_errhandling`](../numeric/math/math_errhandling "c/numeric/math/math errhandling").
```
void f(void)
{
#pragma STDC FENV_ACCESS ON
static float x = 0.0/0.0; // static initializer: does not raise an exception
float w[] = { 0.0/0.0 }; // raises an exception
float y = 0.0/0.0; // raises an exception
double z = 0.0/0.0; // raises an exception
}
```
### Notes
If an expression evaluates to a value that is not representable by its type, it cannot be used as a constant expression.
Implementations may accept other forms of constant expressions. However, these constant expressions are not considered as integer constant expressions, arithmetic constant expressions, or address constant expressions, and thus cannot be used in the contexts requiring these kinds of constant expressions. For example, `int arr[(int)+1.0];` declares a VLA.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.6 Constant expressions (p: 76-77)
* C11 standard (ISO/IEC 9899:2011):
+ 6.6 Constant expressions (p: 106-107)
* C99 standard (ISO/IEC 9899:1999):
+ 6.6 Constant expressions (p: 95-96)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.4 CONSTANT EXPRESSIONS
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/constant_expression "cpp/language/constant expression") for Constant expressions |
c break statement break statement
===============
Causes the enclosing [for](for "c/language/for"), [while](while "c/language/while") or [do-while](do "c/language/do") loop or [switch statement](switch "c/language/switch") to terminate.
Used when it is otherwise awkward to terminate the loop using the condition expression and conditional statements.
### Syntax
| | | |
| --- | --- | --- |
| attr-spec-seq(optional) `break` `;` | | |
| | | |
| --- | --- | --- |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the `break` statement |
Appears only within the statement of a loop body ([`while`](while "c/language/while"), [`do-while`](do "c/language/do"), [`for`](for "c/language/for")) or within the statement of a [`switch`](switch "c/language/switch").
### Explanation
After this statement the control is transferred to the statement or declaration immediately following the enclosing loop or switch, as if by [`goto`](goto "c/language/goto").
### Keywords
[`break`](../keyword/break "c/keyword/break").
### Notes
A break statement cannot be used to break out of multiple nested loops. The [`goto` statement](goto "c/language/goto") may be used for this purpose.
### Example
```
#include <stdio.h>
int main(void)
{
int i = 2;
switch (i) {
case 1: printf("1");
case 2: printf("2"); // i==2, so execution starts at this case label
case 3: printf("3");
case 4:
case 5: printf("45");
break; // execution of subsequent cases is terminated
case 6: printf("6");
}
printf("\n");
// Compare outputs from these two nested for loops.
for (int j = 0; j < 2; j++)
for (int k = 0; k < 5; k++)
printf("%d%d ", j,k);
printf("\n");
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 5; k++) { // only this loop is exited by break
if (k == 2) break;
printf("%d%d ", j,k);
}
}
}
```
Possible output:
```
2345
00 01 02 03 04 10 11 12 13 14
00 01 10 11
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.8.6.3 The break statement (p: 111)
* C11 standard (ISO/IEC 9899:2011):
+ 6.8.6.3 The break statement (p: 153)
* C99 standard (ISO/IEC 9899:1999):
+ 6.8.6.3 The break statement (p: 138)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.6.6.3 The break statement
### See also
| | |
| --- | --- |
| `[[[fallthrough](attributes/fallthrough "c/language/attributes/fallthrough")]]`(C23) | indicates that the fall through from the previous case label is intentional and should not be diagnosed by a compiler that warns on fall-through |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/break "cpp/language/break") for `break` statement |
c Escape sequences Escape sequences
================
Escape sequences are used to represent certain special characters within [string literals](string_literal "c/language/string literal") and [character constants](character_constant "c/language/character constant").
The following escape sequences are available. ISO C requires a diagnostic if the backslash is followed by any character not listed here:
| Escape sequence | Description | Representation |
| --- | --- | --- |
| Simple escape sequences |
| `\'` | single quote | byte `0x27` in ASCII encoding |
| `\"` | double quote | byte `0x22` in ASCII encoding |
| `\?` | question mark | byte `0x3f` in ASCII encoding |
| `\\` | backslash | byte `0x5c` in ASCII encoding |
| `\a` | audible bell | byte `0x07` in ASCII encoding |
| `\b` | backspace | byte `0x08` in ASCII encoding |
| `\f` | form feed - new page | byte `0x0c` in ASCII encoding |
| `\n` | line feed - new line | byte `0x0a` in ASCII encoding |
| `\r` | carriage return | byte `0x0d` in ASCII encoding |
| `\t` | horizontal tab | byte `0x09` in ASCII encoding |
| `\v` | vertical tab | byte `0x0b` in ASCII encoding |
| Numeric escape sequences |
| `\*nnn*` | arbitrary octal value | byte `*nnn*` |
| `\x*nn*` | arbitrary hexadecimal value | byte `*nn*` |
| Universal character names |
| `\u*nnnn*` (since C99) | [Unicode](https://en.wikipedia.org/wiki/Unicode "enwiki:Unicode") value in allowed range;may result in several code units | code point `U+*nnnn*` |
| `\U*nnnnnnnn*` (since C99) | [Unicode](https://en.wikipedia.org/wiki/Unicode "enwiki:Unicode") value in allowed range;may result in several code units | code point `U+*nnnnnnnn*` |
| | |
| --- | --- |
| Range of universal character names If a universal character name corresponds to a code point that is not 0x24 (`$`), 0x40 (`@`), nor 0x60 (```) and less than 0xA0, or a surrogate code point (the range 0xD800-0xDFFF, inclusive), or greater than 0x10FFFF, i.e. not a Unicode code point (since C23), the program is ill-formed. In other words, members of [basic source character set](translation_phases "c/language/translation phases") and control characters (in ranges 0x0-0x1F and 0x7F-0x9F) cannot be expressed in universal character names. | (since C99) |
### Notes
`\0` is the most commonly used octal escape sequence, because it represents the terminating null character in null-terminated strings.
The new-line character `\n` has special meaning when used in [text mode I/O](../io "c/io"): it is converted to the OS-specific newline byte or byte sequence.
Octal escape sequences have a length limit of three octal digits but terminate at the first character that is not a valid octal digit if encountered sooner.
Hexadecimal escape sequences have no length limit and terminate at the first character that is not a valid hexadecimal digit. If the value represented by a single hexadecimal escape sequence does not fit the range of values represented by the character type used in this string literal or character constant (`char`, `char16_t`, `char32_t` (since C11), or `wchar_t`), the result is unspecified.
| | |
| --- | --- |
| A universal character name in a narrow string literal or a 16-bit string literal (since C11) may map to more than one code unit, e.g. `\U0001f34c` is 4 `char` code units in UTF-8 (`\xF0\x9F\x8D\x8C`) and 2 `char16_t` code units in UTF-16 (`\xD83C\xDF4C`) (since C11). | (since C99) |
| | |
| --- | --- |
| A universal character name corresponding to a code pointer greater than 0x10FFFF (which is undefined in ISO/ISC 10646) can be used in [character constants](character_constant "c/language/character constant") and [string literals](string_literal "c/language/string literal"). Such usage is not allowed in C++20. | (since C99)(until C23) |
The question mark escape sequence `\?` is used to prevent [trigraphs](operator_alternative "c/language/operator alternative") from being interpreted inside string literals: a string such as `"??/"` is compiled as `"\"`, but if the second question mark is escaped, as in `"?\?/"`, it becomes `"??/"`
### Example
```
#include <stdio.h>
int main(void)
{
printf("This\nis\na\ntest\n\nShe said, \"How are you?\"\n");
}
```
Output:
```
This
is
a
test
She said, "How are you?"
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 5.2.2 Character display semantics (p: 18-19)
+ 6.4.3 Universal Character names (p: 44)
+ 6.4.4.4 Character constants (p: 48-50)
* C11 standard (ISO/IEC 9899:2011):
+ 5.2.2 Character display semantics (p: 24-25)
+ 6.4.3 Universal Character names (p: 61)
+ 6.4.4.4 Character constants (p: 67-70)
* C99 standard (ISO/IEC 9899:1999):
+ 5.2.2 Character display semantics (p: 19-20)
+ 6.4.3 Universal Character names (p: 53)
+ 6.4.4.4 Character constants (p: 59-61)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 2.2.2 Character display semantics
+ 3.1.3.4 Character constants
### See also
* [ASCII chart](ascii "c/language/ascii")
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/escape "cpp/language/escape") for Escape sequences |
| programming_docs |
c Punctuation Punctuation
===========
These are the punctuation symbols in C. The meaning of each symbol is detailed in the linked pages.
### `{` `}`
* In a [struct](struct "c/language/struct") or [union](union "c/language/union") definition, delimit the struct-declaration-list.
* In a [enum](enum "c/language/enum") definition, delimit the enumerator list.
* Delimit a [compound statement](statements#Compound_statements "c/language/statements"). The compound statement may be part of a [function definition](function_definition "c/language/function definition").
* In [initialization](initialization "c/language/initialization"), delimit the initializers.
### `[` `]`
* [Subscript operator](operator_member_access#Subscript "c/language/operator member access").
* Part of [array declarator](declarations#Declarators "c/language/declarations") in a [declaration](declarations "c/language/declarations") or a [type-id](type#Type_names "c/language/type").
* In [initialization](initialization "c/language/initialization"), introduce a designator for an array element. (since C99)
* In a [attribute specifier](attributes "c/language/attributes"), delimit the attributes. (since C23)
### `#`
* Introduce a [preprocessing directive](../preprocessor "c/preprocessor").
* The [preprocessing operator for stringification](../preprocessor/replace#.23_and_.23.23_operators "c/preprocessor/replace").
### `##`
* The [preprocessing operator for token pasting](../preprocessor/replace#.23_and_.23.23_operators "c/preprocessor/replace").
### `(` `)`
* In a expression, [indicate grouping](expressions#Primary_expressions "c/language/expressions").
* [Function call operator](operator_other#Function_call "c/language/operator other").
* In a [`sizeof`](sizeof "c/language/sizeof") or [`_Alignof`](_alignof "c/language/ Alignof") (since C11) expression, delimit the operand.
* In a [explicit cast](cast "c/language/cast"), delimit the type-id.
* In a [compound literal](compound_literal "c/language/compound literal"), delimit the type-id. (since C99)
* In a [declaration](declarations "c/language/declarations") or a [type-id](type#Type_names "c/language/type"), indicate grouping.
* In a [function declarator](function_declaration "c/language/function declaration") (in a [declaration](declarations "c/language/declarations") or a [type-id](type#Type_names "c/language/type")), delimit the parameter list.
* In a [`if`](if "c/language/if"), [`switch`](switch "c/language/switch"), [`while`](while "c/language/while"), [`do-while`](do "c/language/do"), or [`for`](for "c/language/for") statement, delimit the controlling clause.
* In a [function-like macro definition](../preprocessor/replace#Function-like_macros "c/preprocessor/replace"), delimit the macro parameters.
* Part of a `defined`, `__has_include`, or `__has_c_attribute` (since C23) preprocessing operator.
* Part of a [generic selection expression](generic "c/language/generic"). (since C11)
* In an [`_Atomic`](atomic "c/language/atomic") type specifier, delimit the type-id. (since C11)
* In a [static assertion declaration](_static_assert "c/language/ Static assert"), delimit the operands. (since C11)
* In an [`_Alignas`](_alignas "c/language/ Alignas") specifier, delimit the operand. (since C11)
* In an [attribute](attributes "c/language/attributes"), delimit the attribute arguments. (since C23)
### `;`
* Indicate the end of
+ a [statement](statements "c/language/statements") (including the init-statement of a for statement)
+ a [declaration](declarations "c/language/declarations") or struct-declaration-list
* Separate the second and third clauses of a [for statement](for "c/language/for").
### `:`
* Part of [conditional operator](operator_other#Conditional_operator "c/language/operator other").
* Part of [label declaration](statements#Labels "c/language/statements").
* In a [bit-field member declaration](bit_field "c/language/bit field"), introduce the width.
### `...`
* In the [parameter list](function_declaration#Parameter_list "c/language/function declaration") of a function declarator, signify a [variadic function](variadic "c/language/variadic").
* In a [macro definition](../preprocessor/replace "c/preprocessor/replace"), signify a variadic macro. (since C99)
### `?`
* Part of [conditional operator](operator_other#Conditional_operator "c/language/operator other").
* In a [generic association](generic "c/language/generic"), delimit the type-id or `default` and the selected expression. (since C11)
### `::`
* In a [attribute](attributes "c/language/attributes"), indicate attribute scope. (since C23)
### `.`
* [Member access operator](operator_member_access#Member_access "c/language/operator member access").
* In [initialization](initialization "c/language/initialization"), introduce a designator for a struct/union member. (since C99)
### `->`
* [Member access operator](operator_member_access#Member_access_through_pointer "c/language/operator member access").
### `~`
* [Unary complement operator (a.k.a. bitwise not operator)](operator_arithmetic#Bitwise_logic "c/language/operator arithmetic").
### `!`
* [Logical not operator](operator_logical#Logical_NOT "c/language/operator logical").
### `+`
* [Unary plus operator](operator_arithmetic#Unary_arithmetic "c/language/operator arithmetic").
* [Binary plus operator](operator_arithmetic#Additive_operators "c/language/operator arithmetic").
### `-`
* [Unary minus operator](operator_arithmetic#Unary_arithmetic "c/language/operator arithmetic").
* [Binary minus operator](operator_arithmetic#Additive_operators "c/language/operator arithmetic").
### `*`
* [Indirection operator](operator_member_access#Dereference "c/language/operator member access").
* [Multiplication operator](operator_arithmetic#Multiplicative_operators "c/language/operator arithmetic").
* Pointer operator operator in a [declarator](declarations#Declarators "c/language/declarations") or in a [type-id](type#Type_names "c/language/type").
* Placeholder for the length of a variable-length array declarator in a [function declaration](function_declaration "c/language/function declaration"). (since C99)
### `/`
* [Division operator](operator_arithmetic#Multiplicative_operators "c/language/operator arithmetic").
### `%`
* [Modulo operator](operator_arithmetic#Multiplicative_operators "c/language/operator arithmetic").
### `^`
* [Bitwise xor operator](operator_arithmetic#Bitwise_logic "c/language/operator arithmetic").
### `&`
* [Address-of operator](operator_member_access#Address_of "c/language/operator member access").
* [Bitwise and operator](operator_arithmetic#Bitwise_logic "c/language/operator arithmetic").
### `|`
* [Bitwise or operator](operator_arithmetic#Bitwise_logic "c/language/operator arithmetic").
### `=`
* [Simple assignment operator](operator_assignment#Simple_assignment "c/language/operator assignment").
* In [initialization](initialization "c/language/initialization"), delimit the object and the initializer list.
* In a [enum definition](enum "c/language/enum"), introduce the value of enumeration constant.
### `+=`
* [Compound assignment operator](operator_assignment#Compound_assignment "c/language/operator assignment").
### `-=`
* [Compound assignment operator](operator_assignment#Compound_assignment "c/language/operator assignment").
### `*=`
* [Compound assignment operator](operator_assignment#Compound_assignment "c/language/operator assignment").
### `/=`
* [Compound assignment operator](operator_assignment#Compound_assignment "c/language/operator assignment").
### `%=`
* [Compound assignment operator](operator_assignment#Compound_assignment "c/language/operator assignment").
### `^=`
* [Compound assignment operator](operator_assignment#Compound_assignment "c/language/operator assignment").
### `&=`
* [Compound assignment operator](operator_assignment#Compound_assignment "c/language/operator assignment").
### `|=`
* [Compound assignment operator](operator_assignment#Compound_assignment "c/language/operator assignment").
### `==`
* [Equality operator](operator_comparison#Equality_operators "c/language/operator comparison").
### `!=`
* [Inequality operator](operator_comparison#Equality_operators "c/language/operator comparison").
### `<`
* [Less-than operator](operator_comparison#Relational_operators "c/language/operator comparison").
* Introduce a header name in a [`#include` directive](../preprocessor/include "c/preprocessor/include").
### `>`
* [Greater-than operator](operator_comparison#Relational_operators "c/language/operator comparison").
* Indicate the end of a header name in a [`#include` directive](../preprocessor/include "c/preprocessor/include")
### `<=`
* [Less-than-or-equal-to operator](operator_comparison#Relational_operators "c/language/operator comparison").
### `>=`
* [Greater-than-or-equal-to operator](operator_comparison#Relational_operators "c/language/operator comparison").
### `&&`
* [Logical and operator](operator_logical#Logical_AND "c/language/operator logical").
### `||`
* [Logical or operator](operator_logical#Logical_OR "c/language/operator logical").
### `<<`
* [Bitwise shift operator](operator_arithmetic#Shift_operators "c/language/operator arithmetic").
### `>>`
* [Bitwise shift operator](operator_arithmetic#Shift_operators "c/language/operator arithmetic").
### `<<=`
* [Compound assignment operator](operator_assignment#Compound_assignment "c/language/operator assignment").
### `>>=`
* [Compound assignment operator](operator_assignment#Compound_assignment "c/language/operator assignment").
### `++`
* [Increment operator](operator_incdec "c/language/operator incdec").
### `--`
* [Decrement operator](operator_incdec "c/language/operator incdec").
### `,`
* [Comma operator](operator_other#Comma_operator "c/language/operator other").
* List separator in
+ the declarator list in a [declaration](declarations "c/language/declarations")
+ initializer list in [initialization](initialization "c/language/initialization"), including [compound literals](compound_literal "c/language/compound literal") (since C99)
+ the argument list in a [function call expression](operator_other#Function_call "c/language/operator other")
+ the enumerator list in a [enum](enum "c/language/enum") declaration
+ the macro parameter list in a [function-like macro definition](../preprocessor/replace#Function-like_macros "c/preprocessor/replace")
+ the generic association list in a [generic selection expression](generic "c/language/generic") (since C11)
+ an [attribute](attributes "c/language/attributes") list (since C23)
* In a [static assertion declaration](_static_assert "c/language/ Static assert"), separate the arguments. (since C11)
* In a [generic selection expression](generic "c/language/generic"), seperate the controlling expression and the generic association list. (since C11)
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.4.6 Punctuators (p: 52-53)
* C11 standard (ISO/IEC 9899:2011):
+ 6.4.6 Punctuators (p: 72-73)
* C99 standard (ISO/IEC 9899:1999):
+ 6.4.6 Punctuators (p: 63-64)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.6 Punctuators
### See also
| | |
| --- | --- |
| [Alternative representations](operator_alternative "c/language/operator alternative") (C95) | alternative spellings for certain operators |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/punctuators "cpp/language/punctuators") for Punctuation |
c if statement if statement
============
Conditionally executes code.
Used where code needs to be executed only if some condition is true.
### Syntax
| | | |
| --- | --- | --- |
| attr-spec-seq(optional) `if (` expression `)` statement-true | (1) | |
| attr-spec-seq(optional) `if (` expression `)` statement-true `else` statement-false | (2) | |
| | | |
| --- | --- | --- |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the `if` statement |
| expression | - | an [expression](expressions "c/language/expressions") of any scalar type |
| statement-true | - | any [statement](statements "c/language/statements") (often a compound statement), which is executed if expression compares not equal to `0` |
| statement-false | - | any [statement](statements "c/language/statements") (often a compound statement), which is executed if expression compares equal to `0` |
### Explanation
expression must be an expression of any [scalar type](type#Type_groups "c/language/type").
If expression compares not equal to the integer zero, statement-true is executed.
In the form (2), if expression compares equal to the integer zero, statement\_false is executed.
| | |
| --- | --- |
| As with all other selection and iteration statements, the entire if-statement has its own block scope:
```
enum {a, b};
int different(void)
{
if (sizeof(enum {b, a}) != sizeof(int))
return a; // a == 1
return b; // b == 0 in C89, b == 1 in C99
}
```
| (since C99) |
### Notes
The `else` is always associated with the closest preceding `if` (in other words, if statement-true is also an if statement, then that inner if statement must contain an `else` part as well):
```
int j = 1;
if (i > 1)
if(j > 2)
printf("%d > 1 and %d > 2\n", i, j);
else // this else is part of if(j>2), not part of if(i>1)
printf("%d > 1 and %d <= 2\n", i, j);
```
If statement-true is entered through a [goto](goto "c/language/goto"), statement-false is not executed.
### Keywords
[`if`](../keyword/if "c/keyword/if"), [`else`](../keyword/else "c/keyword/else").
### Example
```
#include <stdio.h>
int main(void)
{
int i = 2;
if (i > 2) {
printf("first is true\n");
} else {
printf("first is false\n");
}
i = 3;
if (i == 3) printf("i == 3\n");
if (i != 3) printf("i != 3 is true\n");
else printf("i != 3 is false\n");
}
```
Output:
```
first is false
i == 3
i != 3 is false
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.8.4.1 The if statement (p: 108-109)
* C11 standard (ISO/IEC 9899:2011):
+ 6.8.4.1 The if statement (p: 148-149)
* C99 standard (ISO/IEC 9899:1999):
+ 6.8.4.1 The if statement (p: 133-134)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.6.4.1 The if statement
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/if "cpp/language/if") for `if` statement |
c const type qualifier const type qualifier
====================
Each individual type in the C [type system](type "c/language/type") has several *qualified* versions of that type, corresponding to one, two, or all three of the *const*, [volatile](volatile "c/language/volatile"), and, for pointers to object types, [restrict](restrict "c/language/restrict") qualifiers. This page describes the effects of the *const* qualifier.
Objects [declared](declarations "c/language/declarations") with const-qualified types may be placed in read-only memory by the compiler, and if the address of a const object is never taken in a program, it may not be stored at all.
`const` semantics apply to [lvalue](value_category "c/language/value category") expressions only; whenever a const lvalue expression is used in context that does not require an lvalue, its `const` qualifier is lost (note that volatile qualifier, if present, isn't lost).
The lvalue expressions that designate objects of const-qualified type and the lvalue expressions that designate objects of struct or union type with at least one member of const-qualified type (including members of recursively contained aggregates or unions), are not *modifiable lvalues*. In particular, they are not assignable:
```
const int n = 1; // object of const type
n = 2; // error: the type of n is const-qualified
int x = 2; // object of unqualified type
const int* p = &x;
*p = 3; // error: the type of the lvalue *p is const-qualified
struct {int a; const int b; } s1 = {.b=1}, s2 = {.b=2};
s1 = s2; // error: the type of s1 is unqualified, but it has a const member
```
A member of a const-qualified structure or union type acquires the qualification of the type it belongs to (both when accessed using the `.` operator or the `->` operator).
```
struct s { int i; const int ci; } s;
// the type of s.i is int, the type of s.ci is const int
const struct s cs;
// the types of cs.i and cs.ci are both const int
```
| | |
| --- | --- |
| If an array type is declared with the const type qualifier (through the use of [typedef](typedef "c/language/typedef")), the array type is not const-qualified, but its element type is. | (until C23) |
| An array type and its element type are always considered to be identically const-qualified. | (since C23) |
If a function type is declared with the const type qualifier (through the use of [typedef](typedef "c/language/typedef")), the behavior is undefined.
```
typedef int A[2][3];
const A a = {{4, 5, 6}, {7, 8, 9}}; // array of array of const int
int* pi = a[0]; // Error: a[0] has type const int*
void *unqual_ptr = a; // OK until C23; error since C23
// Notes: clang applies the rule in C++/C23 even in C89-C17 modes
```
| | |
| --- | --- |
| const-qualified compound literals do not necessarily designate distinct objects; they may share storage with other compound literals and with string literals that happen to have the same or overlapping representation.
```
const int* p1 = (const int[]){1, 2, 3};
const int* p2 = (const int[]){2, 3, 4}; // the value of p2 may equal p1+1
_Bool b = "foobar" + 3 == (const char[]){"bar"}; // the value of b may be 1
```
| (since C99) |
A pointer to an non-const type can be implicitly converted to a pointer to const-qualified version of the same or [compatible type](compatible_type "c/language/compatible type"). The reverse conversion can be performed with a cast expression.
```
int* p = 0;
const int* cp = p; // OK: adds qualifiers (int to const int)
p = cp; // Error: discards qualifiers (const int to int)
p = (int*)cp; // OK: cast
```
Note that pointer to pointer to `T` is not convertible to pointer to pointer to `const T`; for two types to be compatible, their qualifications must be identical.
```
char *p = 0;
const char **cpp = &p; // Error: char* and const char* are not compatible types
char * const *pcp = &p; // OK, adds qualifiers (char* to char*const)
```
Any attempt to modify an object whose type is const-qualified results in undefined behavior.
```
const int n = 1; // object of const-qualified type
int* p = (int*)&n;
*p = 2; // undefined behavior
```
| | |
| --- | --- |
| In a function declaration, the keyword `const` may appear inside the square brackets that are used to declare an array type of a function parameter. It qualifies the pointer type to which the array type is transformed.
The following two declarations declare the same function:
```
void f(double x[const], const double y[const]);
void f(double * const x, const double * const y);
```
| (since C99) |
### Keywords
[`const`](https://en.cppreference.com/w/cpp/keyword/const "cpp/keyword/const").
### Notes
C adopted the *const* qualifier from C++, but unlike in C++, expressions of const-qualified type in C are not [constant expressions](constant_expression "c/language/constant expression"); they may not be used as [case](switch "c/language/switch") labels or to initialize [static](static_storage_duration "c/language/static storage duration") and [thread](thread_storage_duration "c/language/thread storage duration") storage duration objects, [enumerators](enum "c/language/enum"), or [bit field](bit_field "c/language/bit field") sizes. When they are used as [array](array "c/language/array") sizes, the resulting arrays are VLAs.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.3 Type qualifiers (p: 87-90)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.3 Type qualifiers (p: 121-123)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.3 Type qualifiers (p: 108-110)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 6.5.3 Type qualifiers
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/cv "cpp/language/cv") for cv (`const` and `volatile`) type qualifiers |
| programming_docs |
c Variadic arguments Variadic arguments
==================
Variadic functions are functions that may be called with different number of arguments.
Only prototyped [function declarations](function_declaration "c/language/function declaration") may be variadic. This is indicated by the parameter of the form `...` which must appear last in the parameter list and must follow at least one named parameter (until C23). The ellipsis parameter and the proceeding parameter must be delimited by `,`.
```
// Prototyped declaration
int printx(const char* fmt, ...); // function declared this way
printx("hello world"); // may be called with one
printx("a=%d b=%d", a, b); // or more arguments
int printz(...); // OK since C23 and in C++
// Error until C23: ... must follow at least one named parameter
// int printy(..., const char* fmt); // Error: ... must be the last
// int printa(const char* fmt...); // Error in C: ',' is required; OK in C++
```
At the [function call](operator_other#Function_call "c/language/operator other"), each argument that is a part of the variable argument list undergoes special implicit conversions known as [default argument promotions](conversion#Default_argument_promotions "c/language/conversion").
Within the body of a function that uses variadic arguments, the values of these arguments may be accessed using the [`<stdarg.h>` library facilities](../variadic "c/variadic"):
| Defined in header `<stdarg.h>` |
| --- |
| [va\_start](../variadic/va_start "c/variadic/va start") | enables access to variadic function arguments (function macro) |
| [va\_arg](../variadic/va_arg "c/variadic/va arg") | accesses the next variadic function argument (function macro) |
| [va\_copy](../variadic/va_copy "c/variadic/va copy")
(C99) | makes a copy of the variadic function arguments (function macro) |
| [va\_end](../variadic/va_end "c/variadic/va end") | ends traversal of the variadic function arguments (function macro) |
| [va\_list](../variadic/va_list "c/variadic/va list") | holds the information needed by va\_start, va\_arg, va\_end, and va\_copy (typedef) |
### Notes
Although old-style (prototype-less) [function declarations](function_declaration "c/language/function declaration") allow the subsequent function calls to use any number of arguments, they are not allowed to be variadic (as of C89). The definition of such function must specify a fixed number of parameters and cannot use the `stdarg.h` macros.
```
// old-style declaration, removed in C23
int printx(); // function declared this way
printx("hello world"); // may be called with one
printx("a=%d b=%d", a, b); // or more arguments
// the behavior of at least one of these calls is undefined, depending on
// the number of parameters the function is defined to take
```
### Example
```
#include <stdio.h>
#include <time.h>
#include <stdarg.h>
void tlog(const char* fmt,...)
{
char msg[50];
strftime(msg, sizeof msg, "%T", localtime(&(time_t){time(NULL)}));
printf("[%s] ", msg);
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
}
int main(void)
{
tlog("logging %d %d %d...\n", 1, 2, 3);
}
```
Output:
```
[10:21:38] logging 1 2 3...
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.6.3/9 Function declarators (including prototypes) (p: 96)
+ 7.16 Variable arguments <stdarg.h> (p: 197-199)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.6.3/9 Function declarators (including prototypes) (p: 133)
+ 7.16 Variable arguments <stdarg.h> (p: 269-272)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.5.3/9 Function declarators (including prototypes) (p: 119)
+ 7.15 Variable arguments <stdarg.h> (p: 249-252)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.5.4.3/5 Function declarators (including prototypes)
+ 4.8 VARIABLE ARGUMENTS <stdarg.h>
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/variadic_arguments "cpp/language/variadic arguments") for Variadic arguments |
c Struct declaration Struct declaration
==================
A struct is a type consisting of a sequence of members whose storage is allocated in an ordered sequence (as opposed to union, which is a type consisting of a sequence of members whose storage overlaps).
The [type specifier](declarations "c/language/declarations") for a struct is identical to the [`union`](union "c/language/union") type specifier except for the keyword used:
### Syntax
| | | |
| --- | --- | --- |
| `struct` attr-spec-seq(optional) name(optional) `{` struct-declaration-list `}` | (1) | |
| `struct` attr-spec-seq(optional) name | (2) | |
1) Struct definition: introduces the new type struct name and defines its meaning
2) If used on a line of its own, as in `struct` name `;`, *declares* but doesn't define the struct `name` (see forward declaration below). In other contexts, names the previously-declared struct, and attr-spec-seq is not allowed.
| | | |
| --- | --- | --- |
| name | - | the name of the struct that's being defined |
| struct-declaration-list | - | any number of variable declarations, [bit field](bit_field "c/language/bit field") declarations, and [static assert](static_assert "c/language/static assert") declarations. Members of incomplete type and members of function type are not allowed (except for the flexible array member described below) |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the struct type |
### Explanation
Within a struct object, addresses of its elements (and the addresses of the bit field allocation units) increase in order in which the members were defined. A pointer to a struct can be cast to a pointer to its first member (or, if the member is a bit field, to its allocation unit). Likewise, a pointer to the first member of a struct can be cast to a pointer to the enclosing struct. There may be unnamed padding between any two members of a struct or after the last member, but not before the first member. The size of a struct is at least as large as the sum of the sizes of its members.
| | |
| --- | --- |
| If a struct defines at least one named member, it is allowed to additionally declare its last member with incomplete array type. When an element of the flexible array member is accessed (in an expression that uses operator `.` or `->` with the flexible array member's name as the right-hand-side operand), then the struct behaves as if the array member had the longest size fitting in the memory allocated for this object. If no additional storage was allocated, it behaves as if an array with 1 element, except that the behavior is undefined if that element is accessed or a pointer one past that element is produced. Initialization and the assignment operator ignore the flexible array member. `sizeof` omits it, but may have more trailing padding than the omission would imply. Structures with flexible array members (or unions who have a recursive-possibly structure member with flexible array member) cannot appear as array elements or as members of other structures.
```
struct s { int n; double d[]; }; // s.d is a flexible array member
struct s t1 = { 0 }; // OK, d is as if double d[1], but UB to access
struct s t2 = { 1, { 4.2 } }; // error: initialization ignores flexible array
// if sizeof (double) == 8
struct s *s1 = malloc(sizeof (struct s) + 64); // as if d was double d[8]
struct s *s2 = malloc(sizeof (struct s) + 40); // as if d was double d[5]
s1 = malloc(sizeof (struct s) + 10); // now as if d was double d[1]. Two bytes excess.
double *dp = &(s1->d[0]); // OK
*dp = 42; // OK
s1->d[1]++; // Undefined behavior. 2 excess bytes can't be accessed
// as double.
s2 = malloc(sizeof (struct s) + 6); // same, but UB to access because 2 bytes are
// missing to complete 1 double
dp = &(s2->d[0]); // OK, can take address just fine
*dp = 42; // undefined behavior
*s1 = *s2; // only copies s.n, not any element of s.d
// except those caught in sizeof (struct s)
```
| (since C99) |
| | |
| --- | --- |
| Similar to union, an unnamed member of a struct whose type is a struct without name is known as *anonymous struct*. Every member of an anonymous struct is considered to be a member of the enclosing struct or union. This applies recursively if the enclosing struct or union is also anonymous.
```
struct v {
union { // anonymous union
struct { int i, j; }; // anonymous structure
struct { long k, l; } w;
};
int m;
} v1;
v1.i = 2; // valid
v1.k = 3; // invalid: inner structure is not anonymous
v1.w.k = 5; // valid
```
Similar to union, the behavior of the program is undefined if struct is defined without any named members (including those obtained via anonymous nested structs or unions). | (since C11) |
### Forward declaration
A declaration of the following form.
| | | |
| --- | --- | --- |
| `struct` attr-spec-seq(optional) name `;` | | |
hides any previously declared meaning for the name name in the tag name space and declares name as a new struct name in current scope, which will be defined later. Until the definition appears, this struct name has [incomplete type](type#Incomplete_types "c/language/type").
This allows structs that refer to each other:
```
struct y;
struct x { struct y *p; /* ... */ };
struct y { struct x *q; /* ... */ };
```
Note that a new struct name may also be introduced just by using a struct tag within another declaration, but if a previously declared struct with the same name exists in the tag [name space](name_space "c/language/name space"), the tag would refer to that name.
```
struct s* p = NULL; // tag naming an unknown struct declares it
struct s { int a; }; // definition for the struct pointed to by p
void g(void)
{
struct s; // forward declaration of a new, local struct s
// this hides global struct s until the end of this block
struct s *p; // pointer to local struct s
// without the forward declaration above,
// this would point at the file-scope s
struct s { char* p; }; // definitions of the local struct s
}
```
### Keywords
[`struct`](../keyword/struct "c/keyword/struct").
### Notes
See [struct initialization](struct_initialization "c/language/struct initialization") for the rules regarding the initializers for structs.
Because members of incomplete type are not allowed, and a struct type is not complete until the end of the definition, a struct cannot have a member of its own type. A pointer to its own type is allowed, and is commonly used to implement nodes in linked lists or trees.
Because a struct declaration does not establish [scope](scope "c/language/scope"), nested types, enumerations and enumerators introduced by declarations within struct-declaration-list are visible in the surrounding scope where the struct is defined.
### Example
```
#include <stddef.h>
#include <stdio.h>
int main(void)
{
struct car { char *make; char *model; int year; }; // declares the struct type
// declares and initializes an object of a previously-declared struct type
struct car c = {.year=1923, .make="Nash", .model="48 Sports Touring Car"};
printf("car: %d %s %s\n", c.year, c.make, c.model);
// declares a struct type, an object of that type, and a pointer to it
struct spaceship { char *make; char *model; char *year; }
ship = {"Incom Corporation", "T-65 X-wing starfighter", "128 ABY"},
*pship = &ship;
printf("spaceship: %s %s %s\n", ship.year, ship.make, ship.model);
// addresses increase in order of definition
// padding may be inserted
struct A { char a; double b; char c;};
printf("offset of char a = %zu\noffset of double b = %zu\noffset of char c = %zu\n"
"sizeof(struct A) = %zu\n", offsetof(struct A, a), offsetof(struct A, b),
offsetof(struct A, c), sizeof(struct A));
struct B { char a; char b; double c;};
printf("offset of char a = %zu\noffset of char b = %zu\noffset of double c = %zu\n"
"sizeof(struct B) = %zu\n", offsetof(struct B, a), offsetof(struct B, b),
offsetof(struct B, c), sizeof(struct B));
// A pointer to a struct can be cast to a pointer to its first member and vice versa
char* pmake = (char*)pship;
pship = (struct spaceship *)pmake;
}
```
Possible output:
```
car: 1923 Nash 48 Sports Touring Car
spaceship: 128 ABY Incom Corporation T-65 X-wing starfighter
offset of char a = 0
offset of double b = 8
offset of char c = 16
sizeof(struct A) = 24
offset of char a = 0
offset of char b = 1
offset of double c = 8
sizeof(struct B) = 16
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.2.1 Structure and union specifiers (p: 81-84)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.2.1 Structure and union specifiers (p: 112-117)
* C99 standard (ISO/IEC 9899:1999):
+ 6.7.2.1 Structure and union specifiers (p: 101-104)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.5.2.1 Structure and union specifiers
### See also
* [struct and union member access](operator_member_access "c/language/operator member access")
* [bit field](bit_field "c/language/bit field")
* [struct initialization](struct_initialization "c/language/struct initialization")
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/class "cpp/language/class") for Class declaration |
c switch statement switch statement
================
Executes code according to the value of an integral argument.
Used where one or several out of many branches of code need to be executed according to an integral value.
### Syntax
| | | |
| --- | --- | --- |
| attr-spec-seq(optional) `switch (` expression `)` statement | | |
| | | |
| --- | --- | --- |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the `switch` statement |
| expression | - | any [expression](expressions "c/language/expressions") of [integer type](type#Type_groups "c/language/type") (char, signed or unsigned integer, or enumeration) |
| statement | - | any [statement](statements "c/language/statements") (typically a compound statement). `case:` and `default:` labels are permitted in statement, and `break;` statement has special meaning. |
| | | |
| --- | --- | --- |
| `case` constant-expression `:` statement | (1) | (until C23) |
| attr-spec-seq(optional) `case` constant-expression `:` statement(optional) | (1) | (since C23) |
| `default` `:` statement | (2) | (until C23) |
| attr-spec-seq(optional) `default` `:` statement(optional) | (2) | (since C23) |
| | | |
| --- | --- | --- |
| constant-expression | - | any integer [constant expression](constant_expression "c/language/constant expression") |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the label |
### Explanation
The body of a switch statement may have an arbitrary number of `case:` labels, as long as the values of all constant-expressions are unique (after [conversion](conversion "c/language/conversion") to the [promoted type](conversion#Integer_promotions "c/language/conversion") of expression). At most one `default:` label may be present (although nested switch statements may use their own `default:` labels or have `case:` labels whose constants are identical to the ones used in the enclosing switch).
If expression evaluates to the value that is equal to the value of one of constant-expressions after conversion to the promoted type of expression, then control is transferred to the statement that is labeled with that constant-expression.
If expression evaluates to a value that doesn't match any of the `case:` labels, and the `default:` label is present, control is transferred to the statement labeled with the `default:` label.
If expression evaluates to a value that doesn't match any of the `case:` labels, and the `default:` label is not present, none of the switch body is executed.
The [break](break "c/language/break") statement, when encountered anywhere in statement, exits the switch statement:
```
switch(1) {
case 1 : puts("1"); // prints "1",
case 2 : puts("2"); // then prints "2" ("fall-through")
}
```
```
switch(1) {
case 1 : puts("1"); // prints "1"
break; // and exits the switch
case 2 : puts("2");
break;
}
```
| | |
| --- | --- |
| As with all other selection and iteration statements, the switch statement establishes [block scope](scope "c/language/scope"): any identifier introduced in the expression goes out of scope after the statement.
If a VLA or another identifier with variably-modified type has a `case:` or a `default:` label within its scope, the entire switch statement must be in its scope (in other words, a VLA must be declared either before the entire switch or after the last label):
```
switch (expr)
{
int i = 4; // not a VLA; OK to declare here
f(i); // never called
// int a[i]; // error: VLA cannot be declared here
case 0:
i = 17;
default:
int a[i]; // OK to declare VLA here
printf("%d\n", i); // prints 17 if expr == 0, prints indeterminate value otherwise
}
```
| (since C99) |
### Keywords
[`switch`](../keyword/switch "c/keyword/switch"), [`case`](../keyword/case "c/keyword/case"), [`default`](../keyword/default "c/keyword/default").
### Example
```
#include <stdio.h>
void func(int x)
{
printf("func(%d): ", x);
switch(x)
{
case 1: printf("case 1, ");
case 2: printf("case 2, ");
case 3: printf("case 3.\n"); break;
case 4: printf("case 4, ");
case 5:
case 6: printf("case 5 or case 6, ");
default: printf("default.\n");
}
}
int main(void)
{
for(int i = 1; i < 9; ++i) func(i);
}
```
Output:
```
func(1): case 1, case 2, case 3.
func(2): case 2, case 3.
func(3): case 3.
func(4): case 4, case 5 or case 6, default.
func(5): case 5 or case 6, default.
func(6): case 5 or case 6, default.
func(7): default.
func(8): default.
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.8.4.2 The switch statement (p: 108-109)
* C11 standard (ISO/IEC 9899:2011):
+ 6.8.4.2 The switch statement (p: 149-150)
* C99 standard (ISO/IEC 9899:1999):
+ 6.8.4.2 The switch statement (p: 134-135)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.6.4.2 The switch statement
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/switch "cpp/language/switch") for `switch` statement |
c do-while loop do-while loop
=============
Executes a statement repeatedly until the value of the condition expression becomes false. The test takes place after each iteration.
### Syntax
| | | |
| --- | --- | --- |
| attr-spec-seq(optional) `do` statement `while (` expression `)` `;` | | |
| | | |
| --- | --- | --- |
| expression | - | any [expression](expressions "c/language/expressions") of [scalar type](type#Type_groups "c/language/type"). This expression is evaluated after each iteration, and if it compares equal to zero, the loop is exited. |
| statement | - | any [statement](statements "c/language/statements"), typically a compound statement, which is the body of the loop |
| attr-spec-seq | - | (C23)optional list of [attributes](attributes "c/language/attributes"), applied to the loop statement |
### Explanation
A `do-while` statement causes the statement (also called *the loop body*) to be executed repeatedly until the expression (also called *controlling expression*) compares equal to 0. The repetition occurs regardless of whether the loop body is entered normally or by a [goto](goto "c/language/goto") into the middle of statement.
The evaluation of expression takes place after each execution of statement (whether entered normally or by a goto). If the controlling expression needs to be evaluated before the loop body, the [while loop](while "c/language/while") or the [for loop](for "c/language/for") may be used.
If the execution of the loop needs to be terminated at some point, [break statement](break "c/language/break") can be used as terminating statement.
If the execution of the loop needs to be continued at the end of the loop body, [continue statement](continue "c/language/continue") can be used as a shortcut.
A program with an endless loop has undefined behavior if the loop has no observable behavior (I/O, volatile accesses, atomic or synchronization operation) in any part of its statement or expression. This allows the compilers to optimize out all unobservable loops without proving that they terminate. The only exceptions are the loops where expression is a constant expression; `do {...} while(true);` is always an endless loop.
| | |
| --- | --- |
| As with all other selection and iteration statements, the do-while statement establishes [block scope](scope "c/language/scope"): any identifier introduced in the expression goes out of scope after the statement. | (since C99) |
### Notes
Boolean and pointer expressions are often used as loop controlling expressions. The boolean value `false` and the null pointer value of any pointer type compare equal to zero.
### Keywords
[`do`](../keyword/do "c/keyword/do"), [`while`](../keyword/while "c/keyword/while").
### Example
```
#include <stdio.h>
#include <stdlib.h>
enum { SIZE = 8 };
int main(void)
{
// trivial example
int array[SIZE], n = 0;
do array[n++] = rand() % 2; // the loop body is a single expression statement
while(n < SIZE);
puts("Array filled!");
n = 0;
do { // the loop body is a compound statement
printf("%d ", array[n]);
++n;
} while (n < SIZE);
printf("\n");
// the loop from K&R itoa(). The do-while loop is used
// because there is always at least one digit to generate
int num = 1234, i=0;
char s[10];
do s[i++] = num % 10 + '0'; // get next digit in reverse order
while ((num /= 10) > 0);
s[i] = '\0';
puts(s);
}
```
Possible output:
```
Array filled!
1 0 1 1 1 1 0 0
4321
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.8.5.2 The do statement (p: 109)
* C11 standard (ISO/IEC 9899:2011):
+ 6.8.5.2 The do statement (p: 151)
* C99 standard (ISO/IEC 9899:1999):
+ 6.8.5.2 The do statement (p: 136)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.6.5.2 The do statement
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/do "cpp/language/do") for `do`-`while` loop |
| programming_docs |
c for loop for loop
========
Executes a loop.
Used as a shorter equivalent of [while loop](while "c/language/while").
### Syntax
| | | |
| --- | --- | --- |
| attr-spec-seq(since C23)(optional) `for` `(` init-clause `;` cond-expression `;` iteration-expression `)` loop-statement | | |
### Explanation
Behaves as follows:
* init-clause may be an expression or a declaration (since C99).
+ An init-clause, which is an expression, is evaluated once, before the first evaluation of cond-expression and its result is discarded.
| | |
| --- | --- |
| * An init-clause, which is a declaration, is in scope in the entire loop body, including the remainder of init-clause, the entire cond-expression, the entire iteration-expression and the entire loop-statement. Only `auto` and `register` [storage class specifiers](storage_duration "c/language/storage duration") are allowed for the variables declared in this declaration.
| (since C99) |
* cond-expression is evaluated before the loop body. If the result of the expression is zero, the loop statement is exited immediately.
* iteration-expression is evaluated after the loop body and its result is discarded. After evaluating iteration-expression, control is transferred to cond-expression.
init-clause, cond-expression, and iteration-expression are all optional. If cond-expression is omitted, it is replaced with a non-zero integer constant, which makes the loop endless:
```
for(;;) {
printf("endless loop!");
}
```
loop-statement is not optional, but it may be a null statement:
```
for(int n = 0; n < 10; ++n, printf("%d\n", n))
; // null statement
```
If the execution of the loop needs to be terminated at some point, a [break statement](break "c/language/break") can be used anywhere within the loop-statement.
The [continue statement](continue "c/language/continue") used anywhere within the loop-statement transfers control to iteration-expression.
A program with an endless loop has undefined behavior if the loop has no observable behavior (I/O, volatile accesses, atomic or synchronization operation) in any part of its cond-expression, iteration-expression or loop-statement. This allows the compilers to optimize out all unobservable loops without proving that they terminate. The only exceptions are the loops where cond-expression is omitted or is a constant expression; `for(;;)` is always an endless loop.
| | |
| --- | --- |
| As with all other selection and iteration statements, the for statement establishes [block scope](scope "c/language/scope"): any identifier introduced in the init-clause, cond-expression, or iteration-expression goes out of scope after the loop-statement. | (since C99) |
| | |
| --- | --- |
| attr-spec-seq is an optional list of [attributes](attributes "c/language/attributes"), applied to the `for` statement. | (since C23) |
### Keywords
[`for`](../keyword/for "c/keyword/for").
### Notes
The expression statement used as loop-statement establishes its own block scope, distinct from the scope of init-clause, unlike in C++:
```
for (int i = 0; ; ) {
long i = 1; // valid C, invalid C++
// ...
}
```
It is possible to enter the body of a loop using [goto](goto "c/language/goto"). When entering a loop in this manner, init-clause and cond-expression are not executed. (If control then reaches the end of the loop body, repetition may occur including execution of cond-expression.).
### Example
```
#include <stdio.h>
#include <stdlib.h>
enum { SIZE = 8 };
int main(void)
{
int array[SIZE];
for(size_t i = 0 ; i < SIZE; ++i)
array [i] = rand() % 2;
printf("Array filled!\n");
for (size_t i = 0; i < SIZE; ++i)
printf("%d ", array[i]);
putchar('\n');
}
```
Possible output:
```
Array filled!
1 0 1 1 1 1 0 0
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.8.5.3 The for statement (p: 110)
* C11 standard (ISO/IEC 9899:2011):
+ 6.8.5.3 The for statement (p: 151)
* C99 standard (ISO/IEC 9899:1999):
+ 6.8.5.3 The for statement (p: 136)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.6.5.3 The for statement
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/for "cpp/language/for") for `for` loop |
c Thread storage duration Thread storage duration
=======================
An object whose identifier is declared with the storage-class specifier `_Thread_local` (since C11) has thread storage duration. Its lifetime is the entire execution of the thread for which it is created, and its stored value is initialized when the thread is started. There is a distinct object per thread, and use of the declared name in an expression refers to the object associated with the thread evaluating the expression. The result of attempting to indirectly access an object with thread storage duration from a thread other than the one with which the object is associated is implementation-defined.
### Example
```
const double PI = 3.14159; /* const variable is global to all threads */
_Thread_local unsigned int seed; /* seed is a thread-specific variable */
int main(void)
{
return 0;
}
```
Possible output:
```
(none)
```
c _Alignas \_Alignas
=========
Appears in the [declaration](declarations "c/language/declarations") syntax as one of the type specifiers to modify the [alignment requirement](object#Alignment "c/language/object") of the object being declared.
### Syntax
| | | |
| --- | --- | --- |
| `_Alignas` `(` expression `)` | (1) | (since C11) |
| `_Alignas` `(` type `)` | (2) | (since C11) |
| | | |
| --- | --- | --- |
| expression | - | any [integer constant expression](constant_expression "c/language/constant expression") whose value is a valid [alignment](object#Alignment "c/language/object") or zero |
| type | - | any [type name](type#Type_names "c/language/type") |
This keyword is also available as convenience macro [`alignas`](../types "c/types"), available in the header `<stdalign.h>`.
### Explanation
The `_Alignas` specifier can only be used when declaring objects that aren't [bit fields](bit_field "c/language/bit field"), and don't have the [register](storage_duration "c/language/storage duration") storage class. It cannot be used in function parameter declarations, and cannot be used in a typedef.
When used in a declaration, the declared object will have its [alignment requirement](object#Alignment "c/language/object") set to.
1) the result of the expression, unless it is zero
2) to the alignment requirement of type, that is, to `_Alignof(type)`
except when this would weaken the alignment the type would have had naturally.
If expression evaluates to zero, this specifier has no effect.
When multiple `_Alignas` specifiers appear in the same declaration, the strictest one is used.
`_Alignas` specifier only needs to appear on the [definition](declarations#Definitions "c/language/declarations") of an object, but if any declaration uses `_Alignas`, it must specify the same alignment as the `_Alignas` on the definition. The behavior is undefined if different translation units specify different alignments for the same object.
### Notes
In C++, the `alignas` specifier may also be applied to the declarations of class/struct/union types and enumerations. This is not supported in C, but the alignment of a struct type can be controlled by using `_Alignas` in a member declaration.
### Keywords
[`_Alignas`](../keyword/_alignas "c/keyword/ Alignas").
### Example
```
#include <stdalign.h>
#include <stdio.h>
// every object of type struct sse_t will be aligned to 16-byte boundary
// (note: needs support for DR 444)
struct sse_t
{
alignas(16) float sse_data[4];
};
// every object of type struct data will be aligned to 128-byte boundary
struct data {
char x;
alignas(128) char cacheline[128]; // over-aligned array of char,
// not array of over-aligned chars
};
int main(void)
{
printf("sizeof(data) = %zu (1 byte + 127 bytes padding + 128-byte array)\n",
sizeof(struct data));
printf("alignment of sse_t is %zu\n", alignof(struct sse_t));
alignas(2048) struct data d; // this instance of data is aligned even stricter
}
```
Output:
```
sizeof(data) = 256 (1 byte + 127 bytes padding + 128-byte array)
alignment of sse_t is 16
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [DR 444](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_444) | C11 | `_Alignas` was not allowed in struct and union members | allowed |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.7.5 Alignment specifier (p: 92)
+ 6.2.8 Alignment of objects (p: 36-37)
+ 7.15 Alignment <stdalign.h> (p: 196)
* C11 standard (ISO/IEC 9899:2011):
+ 6.7.5 Alignment specifier (p: 127-128)
+ 6.2.8 Alignment of objects (p: 48-49)
+ 7.15 Alignment <stdalign.h> (p: 268)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/alignas "cpp/language/alignas") for `alignas` specifier |
c C attribute: fallthrough (since C23)
C attribute: fallthrough (since C23)
====================================
Indicates that the fall through from the previous case label is intentional and should not be diagnosed by a compiler that warns on fallthrough.
### Syntax
| | | |
| --- | --- | --- |
| `[[` `fallthrough` `]]``[[` `__fallthrough__` `]]` | | |
### Explanation
May only be used in an [attribute declaration](../declarations "c/language/declarations") to create a *fallthrough declaration* (`[[fallthrough]];`).
A fallthrough declaration may only be used in a [`switch`](../switch "c/language/switch") statement, where the next block item (statement, declaration, or label) to be encounted is a statement with a `case` or `default` label for that switch statement.
Indicates that the fall through from the previous case label is intentional and should not be diagnosed by a compiler that warns on fallthrough.
### Example
```
#include <stdbool.h>
void g(void) {}
void h(void) {}
void i(void) {}
void f(int n) {
switch (n) {
case 1:
case 2:
g();
[[fallthrough]];
case 3: // no warning on fallthrough
h();
case 4: // compiler may warn on fallthrough
if(n < 3) {
i();
[[fallthrough]]; // OK
}
else {
return;
}
case 5:
while (false) {
[[fallthrough]]; // ill-formed: no subsequent case or default label
}
case 6:
[[fallthrough]]; // ill-formed: no subsequent case or default label
}
}
int main(void) {}
```
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/attributes/fallthrough "cpp/language/attributes/fallthrough") for `fallthrough` |
c C attribute: nodiscard (since C23)
C attribute: nodiscard (since C23)
==================================
If a function declared `nodiscard` or a function returning a struct/union/enum declared `nodiscard` by value is called from a [discarded-value expression](../expressions "c/language/expressions") other than a cast to `void`, the compiler is encouraged to issue a warning.
### Syntax
| | | |
| --- | --- | --- |
| `[[` `nodiscard` `]]``[[` `__nodiscard__` `]]` | (1) | |
| `[[` `nodiscard` `(` string-literal `)` `]]``[[` `__nodiscard__` `(` string-literal `)` `]]` | (2) | |
| | | |
| --- | --- | --- |
| string-literal | - | text that could be used to explain the rationale for why the result should not be discarded |
### Explanation
Appears in a function declaration, enumeration declaration, or struct/union declaration.
If, from a [discarded-value expression](../expressions "c/language/expressions") other than a cast to `void`,
* a function declared `nodiscard` is called, or
* a function returning a struct/union/enum declared `nodiscard` is called,
the compiler is encouraged to issue a warning.
The string-literal, if specified, is usually included in the warnings.
### Example
```
struct [[nodiscard]] error_info { int status; /*...*/ };
struct error_info enable_missile_safety_mode() { /*...*/ return (struct error_info){0}; }
void launch_missiles() { /*...*/ }
void test_missiles() {
enable_missile_safety_mode(); // compiler may warn on discarding a nodiscard value
launch_missiles();
}
struct error_info* foo() { static struct error_info e; /*...*/ return &e; }
void f1() {
foo(); // nodiscard type itself is not returned, no warning
}
// nodiscard( string-literal ):
[[nodiscard("PURE FUN")]] int strategic_value(int x, int y) { return x ^ y; }
int main()
{
strategic_value(4,2); // compiler may warn on discarding a nodiscard value
int z = strategic_value(0,0); // OK: return value is not discarded
return z;
}
```
Possible output:
```
game.cpp:5:4: warning: ignoring return value of function declared with 'nodiscard' attribute
game.cpp:17:5: warning: ignoring return value of function declared with 'nodiscard' attribute: PURE FUN
```
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/attributes/nodiscard "cpp/language/attributes/nodiscard") for `nodiscard` |
c C attribute: noreturn, _Noreturn (since C23)
C attribute: noreturn, \_Noreturn (since C23)
=============================================
Indicates that the function does not return.
### Syntax
| | | |
| --- | --- | --- |
| `[[` `noreturn` `]]``[[` `__noreturn__` `]]` | | |
| `[[` `_Noreturn` `]]``[[` `___Noreturn__` `]]` | | (deprecated) |
### Explanation
Indicates that the function does not return.
This attribute applies to the name of the function and specifies that the function does not return by executing the return statement or by reaching the end of the function body (it may return by executing `[longjmp](../../program/longjmp "c/program/longjmp")`). The behavior is undefined if the function with this attribute actually returns. A compiler diagnostic is recommended if this can be detected.
It has been previously donated by the keyword [`_Noreturn`](../_noreturn "c/language/ Noreturn") until it was deprecated since C23 and replaced by this attribute.
### Standard library
The following standard functions are declared with `noreturn` attribute (they used to be declared with [`_Noreturn`](../_noreturn "c/language/ Noreturn") specifier until C23):
* `[abort()](../../program/abort "c/program/abort")`
* `[exit()](../../program/exit "c/program/exit")`
* `[\_Exit()](../../program/_exit "c/program/ Exit")`
* `[quick\_exit()](../../program/quick_exit "c/program/quick exit")`
* `[thrd\_exit()](../../thread/thrd_exit "c/thread/thrd exit")`
* `[longjmp()](../../program/longjmp "c/program/longjmp")`
### See also
| |
| --- |
| [C documentation](../_noreturn "c/language/ Noreturn") for `_Noreturn` |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/attributes/noreturn "cpp/language/attributes/noreturn") for `[[noreturn]]` |
c C attribute: maybe_unused (since C23)
C attribute: maybe\_unused (since C23)
======================================
Suppresses warnings on unused entities.
### Syntax
| | | |
| --- | --- | --- |
| `[[` `maybe_unused` `]]``[[` `__maybe_unused__` `]]` | | |
### Explanation
This attribute can appear in the declaration of the following entities:
* [struct](../struct "c/language/struct")/[union](../union "c/language/union"): `struct [[maybe_unused]] S;`,
* [typedef name](../typedef "c/language/typedef"): `[[maybe_unused]] typedef S* PS;`,
* object: `[[maybe_unused]] int x;`,
* struct/union member: `union U { [[maybe_unused]] int n; };`,
* [function](../function_definition "c/language/function definition"): `[[maybe_unused]] void f(void);`,
* [enumeration](../enum "c/language/enum"): `enum [[maybe_unused]] E {};`,
* enumerator: `enum { A [[maybe_unused]], B [[maybe_unused]] = 42 };`.
If the compiler issues warnings on unused entities, that warning is suppressed for any entity declared `maybe_unused`.
### Example
```
#include <assert.h>
[[maybe_unused]] void f([[maybe_unused]] _Bool cond1, [[maybe_unused]] _Bool cond2)
{
[[maybe_unused]] _Bool b = cond1 && cond2;
assert(b); // in release mode, assert is compiled out, and b is unused
// no warning because it is declared [[maybe_unused]]
} // parameters cond1 and cond2 are not used, no warning
int main(void)
{
f(1, 1);
}
```
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/attributes/maybe_unused "cpp/language/attributes/maybe unused") for `maybe_unused` |
c C attribute: deprecated (since C23)
C attribute: deprecated (since C23)
===================================
Indicates that the name or entity declared with this attribute is [deprecated](https://en.wikipedia.org/wiki/Deprecation "enwiki:Deprecation"), that is, the use is allowed, but discouraged for some reason.
### Syntax
| | | |
| --- | --- | --- |
| `[[` `deprecated` `]]``[[` `__deprecated__` `]]` | (1) | |
| `[[` `deprecated` `(` string-literal `)` `]]``[[` `__deprecated__` `(` string-literal `)` `]]` | (2) | |
| | | |
| --- | --- | --- |
| string-literal | - | text that could be used to explain the rationale for deprecation and/or to suggest a replacing entity |
### Explanation
Indicates that the use of the name or entity declared with this attribute is allowed, but discouraged for some reason. Compilers typically issue warnings on such uses. The string-literal, if specified, is usually included in the warnings.
This attribute is allowed in declarations of the following names or entities:
* [struct](../struct "c/language/struct")/[union](../union "c/language/union"): `struct [[deprecated]] S;`,
* [typedef-name](../typedef "c/language/typedef"): `[[deprecated]] typedef S* PS;`,
* objects: `[[deprecated]] int x;`,
* struct/union member: `union U { [[deprecated]] int n; };`,
* [function](../function_definition "c/language/function definition"): `[[deprecated]] void f(void);`,
* [enumeration](../enum "c/language/enum"): `enum [[deprecated]] E {};`,
* enumerator: `enum { A [[deprecated]], B [[deprecated]] = 42 };`.
A name declared non-deprecated may be redeclared deprecated. A name declared deprecated cannot be un-deprecated by redeclaring it without this attribute.
### Example
```
#include <stdio.h>
[[deprecated]]
void TriassicPeriod(void)
{
puts("Triassic Period: [251.9 - 208.5] million years ago.");
}
[[deprecated("Use NeogenePeriod() instead.")]]
void JurassicPeriod(void)
{
puts("Jurassic Period: [201.3 - 152.1] million years ago.");
}
[[deprecated("Use calcSomethingDifferently(int).")]]
int calcSomething(int x)
{
return x * 2;
}
int main(void)
{
TriassicPeriod();
JurassicPeriod();
}
```
Possible output:
```
Triassic Period: [251.9 - 208.5] million years ago.
Jurassic Period: [201.3 - 152.1] million years ago.
prog.c:23:5: warning: 'TriassicPeriod' is deprecated [-Wdeprecated-declarations]
TriassicPeriod();
^
prog.c:3:3: note: 'TriassicPeriod' has been explicitly marked deprecated here
[[deprecated]]
^
prog.c:24:5: warning: 'JurassicPeriod' is deprecated: Use NeogenePeriod() instead. [-Wdeprecated-declarations]
JurassicPeriod();
^
prog.c:9:3: note: 'JurassicPeriod' has been explicitly marked deprecated here
[[deprecated("Use NeogenePeriod() instead.")]]
^
2 warnings generated.
```
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/attributes/deprecated "cpp/language/attributes/deprecated") for `deprecated` |
c bsearch, bsearch_s bsearch, bsearch\_s
===================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
void* bsearch( const void *key, const void *ptr, size_t count, size_t size,
int (*comp)(const void*, const void*) );
```
| (1) | |
|
```
void* bsearch_s( const void *key, const void *ptr, rsize_t count, rsize_t size,
int (*comp)(const void *, const void *, void *),
void *context );
```
| (2) | (since C11) |
1) Finds an element equal to element pointed to by `key` in an array pointed to by `ptr`. The array contains `count` elements of `size` bytes and must be partitioned with respect to `key`, that is, all the elements that compare less than must appear before all the elements that compare equal to, and those must appear before all the elements that compare greater than the key object. A fully sorted array satisfies these requirements. The elements are compared using function pointed to by `comp`. The behavior is undefined if the array is not already partitioned with respect to `*key` in ascending order according to the same criterion that `comp` uses.
2) Same as (1), except that the additional context argument `context` is passed to `comp` and that the following errors are detected at runtime and call the currently installed [constraint handler](../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `count` or `size` is greater than `RSIZE_MAX`
* `key`, `ptr` or `comp` is a null pointer (unless `count` is zero)
As with all bounds-checked functions, `bsearch_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<stdlib.h>`.
If the array contains several elements that `comp` would indicate as equal to the element searched for, then it is unspecified which element the function will return as the result.
### Parameters
| | | |
| --- | --- | --- |
| key | - | pointer to the element to search for |
| ptr | - | pointer to the array to examine |
| count | - | number of element in the array |
| size | - | size of each element in the array in bytes |
| comp | - | comparison function which returns a negative integer value if the first argument is *less* than the second, a positive integer value if the first argument is *greater* than the second and zero if the arguments are equivalent. `key` is passed as the first argument, an element from the array as the second. The signature of the comparison function should be equivalent to the following:
int cmp(const void \*a, const void \*b);
The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array.
|
| context | - | additional information (e.g., collating sequence), passed to `comp` as the third argument |
### Return value
1) Pointer to an element in the array that compares equal to `*key`, or null pointer if such element has not been found.
2) Same as (1), except that the null pointer is also returned on runtime constraints violations. ### Notes
Despite the name, neither C nor POSIX standards require this function to be implemented using binary search or make any complexity guarantees.
Unlike other bounds-checked functions, `bsearch_s` does not treat arrays of zero size as a runtime constraint violation and instead indicates element not found (the other function that accepts arrays of zero size is `qsort_s`).
Until `bsearch_s`, users of `bsearch` often used global variables to pass additional context to the comparison function.
### Example
```
#include <stdlib.h>
#include <stdio.h>
struct data {
int nr;
char const *value;
} dat[] = {
{1, "Foo"}, {2, "Bar"}, {3, "Hello"}, {4, "World"}
};
int data_cmp(void const *lhs, void const *rhs)
{
struct data const *const l = lhs;
struct data const *const r = rhs;
if (l->nr < r->nr) return -1;
else if (l->nr > r->nr) return 1;
else return 0;
// return (l->nr > r->nr) - (l->nr < r->nr); // possible shortcut
// return l->nr - r->nr; // erroneous shortcut (fails if INT_MIN is present)
}
int main(void)
{
struct data key = { .nr = 3 };
struct data const *res = bsearch(&key, dat, sizeof dat / sizeof dat[0],
sizeof dat[0], data_cmp);
if (res) {
printf("No %d: %s\n", res->nr, res->value);
} else {
printf("No %d not found\n", key.nr);
}
}
```
Output:
```
No 3: Hello
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.5.1 The bsearch function (p: 258)
+ K.3.6.3.1 The bsearch\_s function (p: 441-442)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.5.1 The bsearch function (p: 355)
+ K.3.6.3.1 The bsearch\_s function (p: 608-609)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.5.1 The bsearch function (p: 318-319)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.5.1 The bsearch function
### See also
| | |
| --- | --- |
| [qsortqsort\_s](qsort "c/algorithm/qsort")
(C11) | sorts a range of elements with unspecified type (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/algorithm/bsearch "cpp/algorithm/bsearch") for `bsearch` |
| programming_docs |
c qsort, qsort_s qsort, qsort\_s
===============
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
void qsort( void *ptr, size_t count, size_t size,
int (*comp)(const void *, const void *) );
```
| (1) | |
|
```
errno_t qsort_s( void *ptr, rsize_t count, rsize_t size,
int (*comp)(const void *, const void *, void *),
void *context );
```
| (2) | (since C11) |
1) Sorts the given array pointed to by `ptr` in ascending order. The array contains `count` elements of `size` bytes. Function pointed to by `comp` is used for object comparison.
2) Same as (1), except that the additional context parameter `context` is passed to `comp` and that the following errors are detected at runtime and call the currently installed [constraint handler](../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `count` or `size` is greater than `RSIZE_MAX`
* `ptr` or `comp` is a null pointer (unless `count` is zero)
As with all bounds-checked functions, `qsort_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<stdlib.h>`.
If `comp` indicates two elements as equivalent, their order in the resulting sorted array is unspecified.
### Parameters
| | | |
| --- | --- | --- |
| ptr | - | pointer to the array to sort |
| count | - | number of elements in the array |
| size | - | size of each element in the array in bytes |
| comp | - | comparison function which returns a negative integer value if the first argument is *less* than the second, a positive integer value if the first argument is *greater* than the second and zero if the arguments are equivalent. The signature of the comparison function should be equivalent to the following:
int cmp(const void \*a, const void \*b);
The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array.
|
| context | - | additional information (e.g., collating sequence), passed to `comp` as the third argument |
### Return value
1) (none)
2) zero on success, non-zero if a runtime constraints violation was detected ### Notes
Despite the name, neither C nor POSIX standards require this function to be implemented using [quicksort](https://en.wikipedia.org/wiki/Quicksort "enwiki:Quicksort") or make any complexity or stability guarantees.
Unlike other bounds-checked functions, `qsort_s` does not treat arrays of zero size as a runtime constraint violation and instead returns successfully without altering the array (the other function that accepts arrays of zero size is `bsearch_s`).
Until `qsort_s`, users of `qsort` often used global variables to pass additional context to the comparison function.
### Example
```
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int compare_ints(const void* a, const void* b)
{
int arg1 = *(const int*)a;
int arg2 = *(const int*)b;
if (arg1 < arg2) return -1;
if (arg1 > arg2) return 1;
return 0;
// return (arg1 > arg2) - (arg1 < arg2); // possible shortcut
// return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present)
}
int main(void)
{
int ints[] = { -2, 99, 0, -743, 2, INT_MIN, 4 };
int size = sizeof ints / sizeof *ints;
qsort(ints, size, sizeof(int), compare_ints);
for (int i = 0; i < size; i++) {
printf("%d ", ints[i]);
}
printf("\n");
}
```
Output:
```
-2147483648 -743 -2 0 2 4 99
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.5.2 The qsort function (p: 258-259)
+ K.3.6.3.2 The qsort\_s function (p: 442-443)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.5.2 The qsort function (p: 355-356)
+ K.3.6.3.2 The qsort\_s function (p: 609)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.5.2 The qsort function (p: 319)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.5.2 The qsort function
### See also
| | |
| --- | --- |
| [bsearchbsearch\_s](bsearch "c/algorithm/bsearch")
(C11) | searches an array for an element of unspecified type (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/algorithm/qsort "cpp/algorithm/qsort") for `qsort` |
c atomic_exchange, atomic_exchange_explicit atomic\_exchange, atomic\_exchange\_explicit
============================================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
C atomic_exchange( volatile A* obj, C desired );
```
| (1) | (since C11) |
|
```
C atomic_exchange_explicit( volatile A* obj, C desired, memory_order order );
```
| (2) | (since C11) |
Atomically replaces the value pointed by `obj` with `desired` and returns the value `obj` held previously. The operation is read-modify-write operation. The first version orders memory accesses according to `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")`, the second version orders memory accesses according to `order`.
This is a [generic function](../language/generic "c/language/generic") defined for all [atomic object types](../language/atomic "c/language/atomic") `A`. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic objects, and volatile semantic is preserved when applying this operation to volatile atomic objects. `C` is the non-atomic type corresponding to `A`.
It is unspecified whether the name of a generic function is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual function (e.g. parenthesized like `(atomic_exchange)(...)`), or a program defines an external identifier with the name of a generic function, the behavior is undefined..
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to the atomic object to modify |
| desired | - | the value to replace the atomic object with |
| order | - | the memory synchronization ordering for this operation: all values are permitted |
### Return value
The value held previously be the atomic object pointed to by `obj`.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.7.3 The atomic\_exchange generic functions (p: 207)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.7.3 The atomic\_exchange generic functions (p: 283)
### See also
| | |
| --- | --- |
| [atomic\_compare\_exchange\_strongatomic\_compare\_exchange\_strong\_explicitatomic\_compare\_exchange\_weakatomic\_compare\_exchange\_weak\_explicit](atomic_compare_exchange "c/atomic/atomic compare exchange")
(C11) | swaps a value with an atomic object if the old value is what is expected, otherwise reads the old value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_exchange "cpp/atomic/atomic exchange") for `atomic_exchange, atomic_exchange_explicit` |
c atomic_store, atomic_store_explicit atomic\_store, atomic\_store\_explicit
======================================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
void atomic_store( volatile A* obj , C desired);
```
| (1) | (since C11) |
|
```
void atomic_store_explicit( volatile A* obj, C desired, memory_order order );
```
| (2) | (since C11) |
Atomically replaces the value of the atomic variable pointed to by `obj` with `desired`. The operation is atomic write operation.
The first version orders memory accesses according to `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")`, the second version orders memory accesses according to `order`. `order` must be one of `[memory\_order\_relaxed](memory_order "c/atomic/memory order")`, `[memory\_order\_release](memory_order "c/atomic/memory order")` or `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")`. Otherwise the behavior is undefined.
This is a [generic function](../language/generic "c/language/generic") defined for all [atomic object types](../language/atomic "c/language/atomic") `A`. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic objects, and volatile semantic is preserved when applying this operation to volatile atomic objects. `C` is the non-atomic type corresponding to `A`.
It is unspecified whether the name of a generic function is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual function (e.g. parenthesized like `(atomic_store)(...)`), or a program defines an external identifier with the name of a generic function, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to the atomic object to modify |
| order | - | the memory synchronization ordering for this operation |
### Return value
(none).
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.7.1 The atomic\_store generic functions (p: 206)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.7.1 The atomic\_store generic functions (p: 282)
### See also
| | |
| --- | --- |
| [atomic\_loadatomic\_load\_explicit](atomic_load "c/atomic/atomic load")
(C11) | reads a value from an atomic object (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_store "cpp/atomic/atomic store") for `atomic_store, atomic_store_explicit` |
c atomic_flag_clear, atomic_flag_clear_explicit atomic\_flag\_clear, atomic\_flag\_clear\_explicit
==================================================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
void atomic_flag_clear( volatile atomic_flag* obj );
```
| (1) | (since C11) |
|
```
void atomic_flag_clear_explicit( volatile atomic_flag* obj, memory_order order );
```
| (2) | (since C11) |
Atomically changes the state of a `atomic_flag` pointed to by `obj` to clear (`false`). The first version orders memory accesses according to `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")`, the second version orders memory accesses according to `order`.
The argument is pointer to a volatile atomic flag to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic flags.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to the atomic flag object to modify |
| order | - | the memory synchronization ordering for this operation: all values are permitted |
### Return value
(none).
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.8.2 The atomic\_flag\_clear functions (p: 209)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.8.2 The atomic\_flag\_clear functions (p: 286)
### See also
| | |
| --- | --- |
| [atomic\_flag\_test\_and\_setatomic\_flag\_test\_and\_set\_explicit](atomic_flag_test_and_set "c/atomic/atomic flag test and set")
(C11) | sets an atomic\_flag to true and returns the old value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_flag_clear "cpp/atomic/atomic flag clear") for `atomic_flag_clear, atomic_flag_clear_explicit` |
c ATOMIC_FLAG_INIT ATOMIC\_FLAG\_INIT
==================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
#define ATOMIC_FLAG_INIT /* unspecified */
```
| | (since C11) |
Expands to an initializer that can be used to initialize `[atomic\_flag](atomic_flag "c/atomic/atomic flag")` type to the clear state. The value `atomic_flag` that is not initialized using this macro is indeterminate.
### Example
```
#include <stdatomic.h>
atomic_flag flag = ATOMIC_FLAG_INIT;
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.1/3 ATOMIC\_FLAG\_INIT (p: 200)
+ 7.17.8/4 ATOMIC\_FLAG\_INIT (p: 208)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.1/3 ATOMIC\_FLAG\_INIT (p: 273)
+ 7.17.8/4 ATOMIC\_FLAG\_INIT (p: 285)
### See also
| | |
| --- | --- |
| [ATOMIC\_VAR\_INIT](atomic_var_init "c/atomic/ATOMIC VAR INIT")
(C11)(deprecated in C17)(removed in C23) | initializes a new atomic object (function macro) |
| [atomic\_flag](atomic_flag "c/atomic/atomic flag")
(C11) | lock-free atomic boolean flag (struct) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/ATOMIC_FLAG_INIT "cpp/atomic/ATOMIC FLAG INIT") for `ATOMIC_FLAG_INIT` |
c atomic_fetch_sub, atomic_fetch_sub_explicit atomic\_fetch\_sub, atomic\_fetch\_sub\_explicit
================================================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
C atomic_fetch_sub( volatile A* obj, M arg );
```
| (1) | (since C11) |
|
```
C atomic_fetch_sub_explicit( volatile A* obj, M arg, memory_order order );
```
| (2) | (since C11) |
Atomically replaces the value pointed by `obj` with the result of subtraction of `arg` from the old value of `obj`, and returns the value `obj` held previously. The operation is read-modify-write operation. The first version orders memory accesses according to `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")`, the second version orders memory accesses according to `order`.
This is a [generic function](../language/generic "c/language/generic") defined for all [atomic object types](../language/atomic "c/language/atomic") `A`. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic objects, and volatile semantic is preserved when applying this operation to volatile atomic objects. `M` is either the non-atomic type corresponding to `A` if `A` is atomic integer type, or `[ptrdiff\_t](../types/ptrdiff_t "c/types/ptrdiff t")` if `A` is atomic pointer type.
It is unspecified whether the name of a generic function is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual function (e.g. parenthesized like `(atomic_fetch_sub)(...)`), or a program defines an external identifier with the name of a generic function, the behavior is undefined.
For signed integer types, arithmetic is defined to use two’s complement representation. There are no undefined results. For pointer types, the result may be an undefined address, but the operations otherwise have no undefined behavior.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to the atomic object to modify |
| arg | - | the value to subtract from the value stored in the atomic object |
| order | - | the memory synchronization ordering for this operation: all values are permitted |
### Return value
The value held previously by the atomic object pointed to by `obj`.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.7.5 The atomic\_fetch and modify generic functions (p: 208)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.7.5 The atomic\_fetch and modify generic functions (p: 284-285)
### See also
| | |
| --- | --- |
| [atomic\_fetch\_addatomic\_fetch\_add\_explicit](atomic_fetch_add "c/atomic/atomic fetch add")
(C11) | atomic addition (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_fetch_sub "cpp/atomic/atomic fetch sub") for `atomic_fetch_sub, atomic_fetch_sub_explicit` |
c atomic_fetch_and, atomic_fetch_and_explicit atomic\_fetch\_and, atomic\_fetch\_and\_explicit
================================================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
C atomic_fetch_and( volatile A* obj, M arg );
```
| (1) | (since C11) |
|
```
C atomic_fetch_and_explicit( volatile A* obj, M arg, memory_order order );
```
| (2) | (since C11) |
Atomically replaces the value pointed by `obj` with the result of bitwise AND between the old value of `obj` and `arg`, and returns the value `obj` held previously. The operation is read-modify-write operation. The first version orders memory accesses according to `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")`, the second version orders memory accesses according to `order`.
This is a [generic function](../language/generic "c/language/generic") defined for all [atomic object types](../language/atomic "c/language/atomic") `A`. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic objects, and volatile semantic is preserved when applying this operation to volatile atomic objects. `M` is either the non-atomic type corresponding to `A` if `A` is atomic integer type, or `[ptrdiff\_t](../types/ptrdiff_t "c/types/ptrdiff t")` if `A` is atomic pointer type.
It is unspecified whether the name of a generic function is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual function (e.g. parenthesized like `(atomic_fetch_and)(...)`), or a program defines an external identifier with the name of a generic function, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to the atomic object to modify |
| arg | - | the value to bitwise AND to the value stored in the atomic object |
| order | - | the memory sycnhronization ordering for this operation: all values are permitted |
### Return value
The value held previously be the atomic object pointed to by `obj`.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.7.5 The atomic\_fetch and modify generic functions (p: 208)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.7.5 The atomic\_fetch and modify generic functions (p: 284-285)
### See also
| | |
| --- | --- |
| [atomic\_fetch\_oratomic\_fetch\_or\_explicit](atomic_fetch_or "c/atomic/atomic fetch or")
(C11) | atomic bitwise OR (function) |
| [atomic\_fetch\_xoratomic\_fetch\_xor\_explicit](atomic_fetch_xor "c/atomic/atomic fetch xor")
(C11) | atomic bitwise exclusive OR (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_fetch_and "cpp/atomic/atomic fetch and") for `atomic_fetch_and, atomic_fetch_and_explicit` |
c atomic_is_lock_free atomic\_is\_lock\_free
======================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
_Bool atomic_is_lock_free( const volatile A* obj );
```
| | (since C11) |
Determines if the atomic operations on all objects of the type `A` (the type of the object pointed to by `obj`) are lock-free. In any given program execution, the result of calling `atomic_is_lock_free` is the same for all pointers of the same type.
This is a [generic function](../language/generic "c/language/generic") defined for all [atomic object types](../language/atomic "c/language/atomic") `A`. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic objects, and volatile semantic is preserved when applying this operation to volatile atomic objects.
It is unspecified whether the name of a generic function is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual function (e.g. parenthesized like `(atomic_is_lock_free)(...)`), or a program defines an external identifier with the name of a generic function, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to the atomic object to inspect |
### Return value
`true` if the operations on all objects of the type `A` are lock-free, `false` otherwise.
### Example
```
#include <stdio.h>
#include <stdatomic.h>
_Atomic struct A { int a[100]; } a;
_Atomic struct B { int x, y; } b;
int main(void)
{
printf("_Atomic struct A is lock free? %s\n",
atomic_is_lock_free(&a) ? "true" : "false");
printf("_Atomic struct B is lock free? %s\n",
atomic_is_lock_free(&b) ? "true" : "false");
}
```
Possible output:
```
_Atomic struct A is lock free? false
_Atomic struct B is lock free? true
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [DR 465](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_465) | C11 | this function was per-object | this functions is per-type |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.5.1 The atomic\_is\_lock\_free generic function (p: 205)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.5.1 The atomic\_is\_lock\_free generic function (p: 280)
### See also
| | |
| --- | --- |
| [ATOMIC\_BOOL\_LOCK\_FREEATOMIC\_CHAR\_LOCK\_FREEATOMIC\_CHAR16\_T\_LOCK\_FREEATOMIC\_CHAR32\_T\_LOCK\_FREEATOMIC\_WCHAR\_T\_LOCK\_FREEATOMIC\_SHORT\_LOCK\_FREEATOMIC\_INT\_LOCK\_FREEATOMIC\_LONG\_LOCK\_FREEATOMIC\_LLONG\_LOCK\_FREEATOMIC\_POINTER\_LOCK\_FREE](atomic_lock_free_consts "c/atomic/ATOMIC LOCK FREE consts")
(C11) | indicates that the given atomic type is lock-free (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_is_lock_free "cpp/atomic/atomic is lock free") for `atomic_is_lock_free` |
| programming_docs |
c kill_dependency kill\_dependency
================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
A kill_dependency(A y);
```
| | (since C11) |
Informs the compiler that the dependency tree started by an `[memory\_order\_consume](memory_order "c/atomic/memory order")` atomic load operation does not extend past the return value of `kill_dependency`; that is, the argument does not carry a dependency into the return value.
The function is implemented as a macro. `A` is the type of `y`.
### Parameters
| | | |
| --- | --- | --- |
| y | - | the expression whose return value is to be removed from a dependency tree |
### Return value
Returns `y`, no longer a part of a dependency tree.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.3.1 The kill\_dependency macro (p: 203-204)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.3.1 The kill\_dependency macro (p: 278)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/kill_dependency "cpp/atomic/kill dependency") for `kill_dependency` |
c ATOMIC_VAR_INIT ATOMIC\_VAR\_INIT
=================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
#define ATOMIC_VAR_INIT(value) /* unspecified */
```
| | (since C11) (deprecated in C17) (removed in C23) |
Expands to an expression that can be used to initialize an atomic variable of the same type as `value`.
The initial value of atomic object of automatic storage duration that is not explicitly initialized is indeterminate. The default (zero) initialization of static and thread-local variables produces a valid value however.
When initializing an atomic variable, any concurrent access, even through an atomic operation, is a data race (it may happen if the address is immediately passed to another thread with a `[memory\_order\_relaxed](memory_order "c/atomic/memory order")` operation).
### Notes
This macro was a part of early draft design for C11 atomic types. It is not needed in C11, and is deprecated in C17 and removed in C23.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [DR 485](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_485) | C11 | the specification was redundant and contradictory to the core language | fixed |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.2.1 The ATOMIC\_VAR\_INIT macro (p: 201)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.2.1 The ATOMIC\_VAR\_INIT macro (p: 274)
### See also
| | |
| --- | --- |
| [ATOMIC\_FLAG\_INIT](atomic_flag_init "c/atomic/ATOMIC FLAG INIT")
(C11) | initializes a new `[atomic\_flag](http://en.cppreference.com/w/c/atomic/atomic_flag)` (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/ATOMIC_VAR_INIT "cpp/atomic/ATOMIC VAR INIT") for `ATOMIC_VAR_INIT` |
c atomic_fetch_xor, atomic_fetch_xor_explicit atomic\_fetch\_xor, atomic\_fetch\_xor\_explicit
================================================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
C atomic_fetch_xor( volatile A* obj, M arg );
```
| (1) | (since C11) |
|
```
C atomic_fetch_xor_explicit( volatile A* obj, M arg, memory_order order );
```
| (2) | (since C11) |
Atomically replaces the value pointed by `obj` with the result of bitwise XOR between the old value of `obj` and `arg`, and returns the value `obj` held previously. The operation is read-modify-write operation. The first version orders memory accesses according to `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")`, the second version orders memory accesses according to `order`.
This is a [generic function](../language/generic "c/language/generic") defined for all [atomic object types](../language/atomic "c/language/atomic") `A`. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic objects, and volatile semantic is preserved when applying this operation to volatile atomic objects. `M` is either the non-atomic type corresponding to `A` if `A` is atomic integer type, or `[ptrdiff\_t](../types/ptrdiff_t "c/types/ptrdiff t")` if `A` is atomic pointer type.
It is unspecified whether the name of a generic function is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual function (e.g. parenthesized like `(atomic_fetch_xor)(...)`), or a program defines an external identifier with the name of a generic function, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to the atomic object to modify |
| arg | - | the value to bitwise XOR to the value stored in the atomic object |
| order | - | the memory synchronization ordering for this operation: all values are permitted |
### Return value
The value held previously be the atomic object pointed to by `obj`.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.7.5 The atomic\_fetch and modify generic functions (p: 208)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.7.5 The atomic\_fetch and modify generic functions (p: 284-285)
### See also
| | |
| --- | --- |
| [atomic\_fetch\_oratomic\_fetch\_or\_explicit](atomic_fetch_or "c/atomic/atomic fetch or")
(C11) | atomic bitwise OR (function) |
| [atomic\_fetch\_andatomic\_fetch\_and\_explicit](atomic_fetch_and "c/atomic/atomic fetch and")
(C11) | atomic bitwise AND (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_fetch_xor "cpp/atomic/atomic fetch xor") for `atomic_fetch_xor, atomic_fetch_xor_explicit` |
c atomic_compare_exchange_weak, atomic_compare_exchange_strong, atomic_compare_exchange_weak_explicit, atomic_compare_exchange_strong_explicit atomic\_compare\_exchange\_weak, atomic\_compare\_exchange\_strong, atomic\_compare\_exchange\_weak\_explicit, atomic\_compare\_exchange\_strong\_explicit
==========================================================================================================================================================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
_Bool atomic_compare_exchange_strong( volatile A* obj,
C* expected, C desired );
```
| (1) | (since C11) |
|
```
_Bool atomic_compare_exchange_weak( volatile A *obj,
C* expected, C desired );
```
| (2) | (since C11) |
|
```
_Bool atomic_compare_exchange_strong_explicit( volatile A* obj,
C* expected, C desired,
memory_order succ,
memory_order fail );
```
| (3) | (since C11) |
|
```
_Bool atomic_compare_exchange_weak_explicit( volatile A *obj,
C* expected, C desired,
memory_order succ,
memory_order fail );
```
| (4) | (since C11) |
Atomically compares the contents of memory pointed to by `obj` with the contents of memory pointed to by `expected`, and if those are bitwise equal, replaces the former with `desired` (performs read-modify-write operation). Otherwise, loads the actual contents of memory pointed to by `obj` into `*expected` (performs load operation).
The memory models for the read-modify-write and load operations are `succ` and `fail` respectively. The (1-2) versions use `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")` by default.
The weak forms ((2) and (4)) of the functions are allowed to fail spuriously, that is, act as if `*obj != *expected` even if they are equal. When a compare-and-exchange is in a loop, the weak version will yield better performance on some platforms. When a weak compare-and-exchange would require a loop and a strong one would not, the strong one is preferable.
This is a [generic function](../language/generic "c/language/generic") defined for all [atomic object types](../language/atomic "c/language/atomic") `A`. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic objects, and volatile semantic is preserved when applying this operation to volatile atomic objects. `C` is the non-atomic type corresponding to `A`.
It is unspecified whether the name of a generic function is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual function (e.g. parenthesized like `(atomic_compare_exchange)(...)`), or a program defines an external identifier with the name of a generic function, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to the atomic object to test and modify |
| expected | - | pointer to the value expected to be found in the atomic object |
| desired | - | the value to store in the atomic object if it is as expected |
| succ | - | the memory synchronization ordering for the read-modify-write operation if the comparison succeeds. All values are permitted. |
| fail | - | the memory synchronization ordering for the load operation if the comparison fails. Cannot be `[memory\_order\_release](memory_order "c/atomic/memory order")` or `[memory\_order\_acq\_rel](memory_order "c/atomic/memory order")` and cannot specify stronger ordering than `succ` |
### Return value
The result of the comparison: `true` if `*obj` was equal to `*exp`, `false` otherwise.
### Notes
The behavior of `atomic_compare_exchange_*` family is as if the following was executed atomically:
```
if (memcmp(obj, expected, sizeof *obj) == 0) {
memcpy(obj, &desired, sizeof *obj);
return true;
} else {
memcpy(expected, obj, sizeof *obj);
return false;
}
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.7.4 The atomic\_compare\_exchange generic functions (p: 207)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.7.4 The atomic\_compare\_exchange generic functions (p: 283-284)
### See also
| | |
| --- | --- |
| [atomic\_exchangeatomic\_exchange\_explicit](atomic_exchange "c/atomic/atomic exchange")
(C11) | swaps a value with the value of an atomic object (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_compare_exchange "cpp/atomic/atomic compare exchange") for `atomic_compare_exchange_weak, atomic_compare_exchange_strong, atomic_compare_exchange_weak_explicit, atomic_compare_exchange_strong_explicit` |
c atomic_thread_fence atomic\_thread\_fence
=====================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
void atomic_thread_fence( memory_order order );
```
| | (since C11) |
Establishes memory synchronization ordering of non-atomic and relaxed atomic accesses, as instructed by `order`, without an associated atomic operation. For example, all non-atomic and relaxed atomic stores that happen before a `[memory\_order\_release](memory_order "c/atomic/memory order")` fence in thread A will be synchronized with non-atomic and relaxed atomic loads from the same locations made in thread B after an `[memory\_order\_acquire](memory_order "c/atomic/memory order")` fence.
### Parameters
| | | |
| --- | --- | --- |
| order | - | the memory ordering executed by this fence |
### Return value
(none).
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.4.1 The atomic\_thread\_fence function (p: 204)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.4.1 The atomic\_thread\_fence function (p: 278-279)
### See also
| | |
| --- | --- |
| [atomic\_signal\_fence](atomic_signal_fence "c/atomic/atomic signal fence")
(C11) | fence between a thread and a signal handler executed in the same thread (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_thread_fence "cpp/atomic/atomic thread fence") for `atomic_thread_fence` |
c atomic_fetch_or, atomic_fetch_or_explicit atomic\_fetch\_or, atomic\_fetch\_or\_explicit
==============================================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
C atomic_fetch_or( volatile A* obj, M arg );
```
| (1) | (since C11) |
|
```
C atomic_fetch_or_explicit( volatile A* obj, M arg, memory_order order );
```
| (2) | (since C11) |
Atomically replaces the value pointed by `obj` with the result of bitwise OR between the old value of `obj` and `arg`, and returns the value `obj` held previously. The operation is read-modify-write operation. The first version orders memory accesses according to `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")`, the second version orders memory accesses according to `order`.
This is a [generic function](../language/generic "c/language/generic") defined for all [atomic object types](../language/atomic "c/language/atomic") `A`. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic objects, and volatile semantic is preserved when applying this operation to volatile atomic objects. `M` is either the non-atomic type corresponding to `A` if `A` is atomic integer type, or `[ptrdiff\_t](../types/ptrdiff_t "c/types/ptrdiff t")` if `A` is atomic pointer type.
It is unspecified whether the name of a generic function is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual function (e.g. parenthesized like `(atomic_fetch_or)(...)`), or a program defines an external identifier with the name of a generic function, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to the atomic object to modify |
| arg | - | the value to bitwise OR to the value stored in the atomic object |
| order | - | the memory synchronization ordering for this operation: all values are permitted |
### Return value
The value held previously be the atomic object pointed to by `obj`.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.7.5 The atomic\_fetch and modify generic functions (p: 208)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.7.5 The atomic\_fetch and modify generic functions (p: 284-285)
### See also
| | |
| --- | --- |
| [atomic\_fetch\_andatomic\_fetch\_and\_explicit](atomic_fetch_and "c/atomic/atomic fetch and")
(C11) | atomic bitwise AND (function) |
| [atomic\_fetch\_xoratomic\_fetch\_xor\_explicit](atomic_fetch_xor "c/atomic/atomic fetch xor")
(C11) | atomic bitwise exclusive OR (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_fetch_or "cpp/atomic/atomic fetch or") for `atomic_fetch_or, atomic_fetch_or_explicit` |
c atomic_fetch_add, atomic_fetch_add_explicit atomic\_fetch\_add, atomic\_fetch\_add\_explicit
================================================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
C atomic_fetch_add( volatile A* obj, M arg );
```
| (1) | (since C11) |
|
```
C atomic_fetch_add_explicit( volatile A* obj, M arg, memory_order order );
```
| (2) | (since C11) |
Atomically replaces the value pointed by `obj` with the result of addition of `arg` to the old value of `obj`, and returns the value `obj` held previously. The operation is read-modify-write operation. The first version orders memory accesses according to `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")`, the second version orders memory accesses according to `order`.
This is a [generic function](../language/generic "c/language/generic") defined for all [atomic object types](../language/atomic "c/language/atomic") `A`. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic objects, and volatile semantic is preserved when applying this operation to volatile atomic objects. `M` is either the non-atomic type corresponding to `A` if `A` is atomic integer type, or `[ptrdiff\_t](../types/ptrdiff_t "c/types/ptrdiff t")` if `A` is atomic pointer type.
It is unspecified whether the name of a generic function is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual function (e.g. parenthesized like `(atomic_fetch_add)(...)`), or a program defines an external identifier with the name of a generic function, the behavior is undefined.
For signed integer types, arithmetic is defined to use two’s complement representation. There are no undefined results. For pointer types, the result may be an undefined address, but the operations otherwise have no undefined behavior.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to the atomic object to modify |
| arg | - | the value to add to the value stored in the atomic object |
| order | - | the memory synchronization ordering for this operation: all values are permitted |
### Return value
The value held previously by the atomic object pointed to by `obj`.
### Example
```
#include <stdio.h>
#include <threads.h>
#include <stdatomic.h>
atomic_int acnt;
int cnt;
int f(void* thr_data)
{
for(int n = 0; n < 1000; ++n) {
atomic_fetch_add_explicit(&acnt, 1, memory_order_relaxed); // atomic
++cnt; // undefined behavior, in practice some updates missed
}
return 0;
}
int main(void)
{
thrd_t thr[10];
for(int n = 0; n < 10; ++n)
thrd_create(&thr[n], f, NULL);
for(int n = 0; n < 10; ++n)
thrd_join(thr[n], NULL);
printf("The atomic counter is %u\n", acnt);
printf("The non-atomic counter is %u\n", cnt);
}
```
Possible output:
```
The atomic counter is 10000
The non-atomic counter is 9511
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.7.5 The atomic\_fetch and modify generic functions (p: 208)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.7.5 The atomic\_fetch and modify generic functions (p: 284-285)
### See also
| | |
| --- | --- |
| [atomic\_fetch\_subatomic\_fetch\_sub\_explicit](atomic_fetch_sub "c/atomic/atomic fetch sub")
(C11) | atomic subtraction (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_fetch_add "cpp/atomic/atomic fetch add") for `atomic_fetch_add, atomic_fetch_add_explicit` |
c atomic_flag atomic\_flag
============
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
struct atomic_flag;
```
| | (since C11) |
`atomic_flag` is an atomic boolean type. Unlike other atomic types, it is guaranteed to be lock-free. Unlike [`atomic_bool`](../thread#Atomic_operations "c/thread"), `atomic_flag` does not provide load or store operations.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.1/4 atomic\_flag (p: 200)
+ 7.17.8 Atomic flag type and operations (p: 208-209)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.1/4 atomic\_flag (p: 273)
+ 7.17.8 Atomic flag type and operations (p: 285-286)
### See also
| | |
| --- | --- |
| [ATOMIC\_FLAG\_INIT](atomic_flag_init "c/atomic/ATOMIC FLAG INIT")
(C11) | initializes a new `atomic_flag` (macro constant) |
| [atomic\_flag\_test\_and\_setatomic\_flag\_test\_and\_set\_explicit](atomic_flag_test_and_set "c/atomic/atomic flag test and set")
(C11) | sets an atomic\_flag to true and returns the old value (function) |
| [atomic\_flag\_clearatomic\_flag\_clear\_explicit](atomic_flag_clear "c/atomic/atomic flag clear")
(C11) | sets an atomic\_flag to false (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_flag "cpp/atomic/atomic flag") for `atomic_flag` |
| programming_docs |
c atomic_init atomic\_init
============
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
void atomic_init( volatile A* obj, C desired );
```
| | (since C11) |
Initializes the default-constructed atomic object `obj` with the value `desired`. The function is not atomic: concurrent access from another thread, even through an atomic operation, is a data race.
This is a [generic function](../language/generic "c/language/generic") defined for all [atomic object types](../language/atomic "c/language/atomic") `A`. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic objects, and volatile semantic is preserved when applying this operation to volatile atomic objects. `C` is the non-atomic type corresponding to `A`.
It is unspecified whether the name of a generic function is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual function (e.g. parenthesized like `(atomic_init)(...)`), or a program defines an external identifier with the name of a generic function, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to an atomic object to initialize |
| desired | - | the value to initialize atomic object with |
### Return value
(none).
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.2.2 The atomic\_init generic function (p: 201)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.2.2 The atomic\_init generic function (p: 274-275)
### See also
| | |
| --- | --- |
| [ATOMIC\_VAR\_INIT](atomic_var_init "c/atomic/ATOMIC VAR INIT")
(C11)(deprecated in C17)(removed in C23) | initializes a new atomic object (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_init "cpp/atomic/atomic init") for `atomic_init` |
c atomic_load, atomic_load_explicit atomic\_load, atomic\_load\_explicit
====================================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
C atomic_load( const volatile A* obj );
```
| (1) | (since C11) |
|
```
C atomic_load_explicit( const volatile A* obj, memory_order order );
```
| (2) | (since C11) |
Atomically loads and returns the current value of the atomic variable pointed to by `obj`. The operation is atomic read operation.
The first version orders memory accesses according to `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")`, the second version orders memory accesses according to `order`. `order` must be one of `[memory\_order\_relaxed](memory_order "c/atomic/memory order")`, `[memory\_order\_consume](memory_order "c/atomic/memory order")`, `[memory\_order\_acquire](memory_order "c/atomic/memory order")` or `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")`. Otherwise the behavior is undefined.
This is a [generic function](../language/generic "c/language/generic") defined for all [atomic object types](../language/atomic "c/language/atomic") `A`. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic objects, and volatile semantic is preserved when applying this operation to volatile atomic objects. `C` is the non-atomic type corresponding to `A`.
It is unspecified whether the name of a generic function is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual function (e.g. parenthesized like `(atomic_load)(...)`), or a program defines an external identifier with the name of a generic function, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to the atomic object to access |
| order | - | the memory synchronization ordering for this operation |
### Return value
The current value of the atomic variable pointed to by `obj`.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.7.2 The atomic\_load generic functions (p: 206)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.7.2 The atomic\_load generic functions (p: 282)
### See also
| | |
| --- | --- |
| [atomic\_storeatomic\_store\_explicit](atomic_store "c/atomic/atomic store")
(C11) | stores a value in an atomic object (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_load "cpp/atomic/atomic load") for `atomic_load, atomic_load_explicit` |
c memory_order memory\_order
=============
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
enum memory_order {
memory_order_relaxed,
memory_order_consume,
memory_order_acquire,
memory_order_release,
memory_order_acq_rel,
memory_order_seq_cst
};
```
| | (since C11) |
`memory_order` specifies how memory accesses, including regular, non-atomic memory accesses, are to be ordered around an atomic operation. Absent any constraints on a multi-core system, when multiple threads simultaneously read and write to several variables, one thread can observe the values change in an order different from the order another thread wrote them. Indeed, the apparent order of changes can even differ among multiple reader threads. Some similar effects can occur even on uniprocessor systems due to compiler transformations allowed by the memory model.
The default behavior of all atomic operations in the [language](../language/atomic "c/language/atomic") and the library provides for *sequentially consistent ordering* (see discussion below). That default can hurt performance, but the library's atomic operations can be given an additional `memory_order` argument to specify the exact constraints, beyond atomicity, that the compiler and processor must enforce for that operation.
### Constants
| Defined in header `<stdatomic.h>` |
| --- |
| Value | Explanation |
| `memory_order_relaxed` | Relaxed operation: there are no synchronization or ordering constraints imposed on other reads or writes, only this operation's atomicity is guaranteed (see [Relaxed ordering](#Relaxed_ordering) below) |
| `memory_order_consume` | A load operation with this memory order performs a *consume operation* on the affected memory location: no reads or writes in the current thread dependent on the value currently loaded can be reordered before this load. Writes to data-dependent variables in other threads that release the same atomic variable are visible in the current thread. On most platforms, this affects compiler optimizations only (see [Release-Consume ordering](#Release-Consume_ordering) below) |
| `memory_order_acquire` | A load operation with this memory order performs the *acquire operation* on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread (see [Release-Acquire ordering](#Release-Acquire_ordering) below) |
| `memory_order_release` | A store operation with this memory order performs the *release operation*: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable (see [Release-Acquire ordering](#Release-Acquire_ordering) below) and writes that carry a dependency into the atomic variable become visible in other threads that consume the same atomic (see [Release-Consume ordering](#Release-Consume_ordering) below). |
| `memory_order_acq_rel` | A read-modify-write operation with this memory order is both an *acquire operation* and a *release operation*. No memory reads or writes in the current thread can be reordered before the load, nor after the store. All writes in other threads that release the same atomic variable are visible before the modification and the modification is visible in other threads that acquire the same atomic variable. |
| `memory_order_seq_cst` | A load operation with this memory order performs an *acquire operation*, a store performs a *release operation*, and read-modify-write performs both an *acquire operation* and a *release operation*, plus a single total order exists in which all threads observe all modifications in the same order (see [Sequentially-consistent ordering](#Sequentially-consistent_ordering) below) |
#### Relaxed ordering
Atomic operations tagged `memory_order_relaxed` are not synchronization operations; they do not impose an order among concurrent memory accesses. They only guarantee atomicity and modification order consistency.
For example, with `x` and `y` initially zero,
`// Thread 1:
r1 = [atomic\_load\_explicit](http://en.cppreference.com/w/c/atomic/atomic_load)(y, memory_order_relaxed); // A
[atomic\_store\_explicit](http://en.cppreference.com/w/c/atomic/atomic_store)(x, r1, memory_order_relaxed); // B
// Thread 2:
r2 = [atomic\_load\_explicit](http://en.cppreference.com/w/c/atomic/atomic_load)(x, memory_order_relaxed); // C
[atomic\_store\_explicit](http://en.cppreference.com/w/c/atomic/atomic_store)(y, 42, memory_order_relaxed); // D`.
is allowed to produce `r1 == r2 == 42` because, although A is *sequenced-before* B within thread 1 and C is *sequenced before* D within thread 2, nothing prevents D from appearing before A in the modification order of y, and B from appearing before C in the modification order of x. The side-effect of D on y could be visible to the load A in thread 1 while the side effect of B on x could be visible to the load C in thread 2. In particular, this may occur if D is completed before C in thread 2, either due to compiler reordering or at runtime.
Typical use for relaxed memory ordering is incrementing counters, such as the reference counters , since this only requires atomicity, but not ordering or synchronization (note that decrementing the shared\_ptr counters requires acquire-release synchronization with the destructor).
#### Release-Consume ordering
If an atomic store in thread A is tagged `memory_order_release` and an atomic load in thread B from the same variable that read the stored value is tagged `memory_order_consume`, all memory writes (non-atomic and relaxed atomic) that *happened-before* the atomic store from the point of view of thread A, become *visible side-effects* within those operations in thread B into which the load operation *carries dependency*, that is, once the atomic load is completed, those operators and functions in thread B that use the value obtained from the load are guaranteed to see what thread A wrote to memory.
The synchronization is established only between the threads *releasing* and *consuming* the same atomic variable. Other threads can see different order of memory accesses than either or both of the synchronized threads.
On all mainstream CPUs other than DEC Alpha, dependency ordering is automatic, no additional CPU instructions are issued for this synchronization mode, only certain compiler optimizations are affected (e.g. the compiler is prohibited from performing speculative loads on the objects that are involved in the dependency chain).
Typical use cases for this ordering involve read access to rarely written concurrent data structures (routing tables, configuration, security policies, firewall rules, etc) and publisher-subscriber situations with pointer-mediated publication, that is, when the producer publishes a pointer through which the consumer can access information: there is no need to make everything else the producer wrote to memory visible to the consumer (which may be an expensive operation on weakly-ordered architectures). An example of such scenario is [rcu\_dereference](https://en.wikipedia.org/wiki/Read-copy-update "enwiki:Read-copy-update").
Note that currently (2/2015) no known production compilers track dependency chains: consume operations are lifted to acquire operations.
#### Release sequence
If some atomic is store-released and several other threads perform read-modify-write operations on that atomic, a "release sequence" is formed: all threads that perform the read-modify-writes to the same atomic synchronize with the first thread and each other even if they have no `memory_order_release` semantics. This makes single producer - multiple consumers situations possible without imposing unnecessary synchronization between individual consumer threads.
#### Release-Acquire ordering
If an atomic store in thread A is tagged `memory_order_release` and an atomic load in thread B from the same variable is tagged `memory_order_acquire`, all memory writes (non-atomic and relaxed atomic) that *happened-before* the atomic store from the point of view of thread A, become *visible side-effects* in thread B. That is, once the atomic load is completed, thread B is guaranteed to see everything thread A wrote to memory. This promise only holds if B actually returns the value that A stored, or a value from later in the release sequence.
The synchronization is established only between the threads *releasing* and *acquiring* the same atomic variable. Other threads can see different order of memory accesses than either or both of the synchronized threads.
On strongly-ordered systems — x86, SPARC TSO, IBM mainframe, etc. — release-acquire ordering is automatic for the majority of operations. No additional CPU instructions are issued for this synchronization mode; only certain compiler optimizations are affected (e.g., the compiler is prohibited from moving non-atomic stores past the atomic store-release or performing non-atomic loads earlier than the atomic load-acquire). On weakly-ordered systems (ARM, Itanium, PowerPC), special CPU load or memory fence instructions are used.
Mutual exclusion locks, such as [mutexes](../thread#Mutual_exclusion "c/thread") or [atomic spinlocks](atomic_flag_test_and_set "c/atomic/atomic flag test and set"), are an example of release-acquire synchronization: when the lock is released by thread A and acquired by thread B, everything that took place in the critical section (before the release) in the context of thread A has to be visible to thread B (after the acquire) which is executing the same critical section.
#### Sequentially-consistent ordering
Atomic operations tagged `memory_order_seq_cst` not only order memory the same way as release/acquire ordering (everything that *happened-before* a store in one thread becomes a *visible side effect* in the thread that did a load), but also establish a *single total modification order* of all atomic operations that are so tagged.
Formally,
Each `memory_order_seq_cst` operation B that loads from atomic variable M, observes one of the following:
* the result of the last operation A that modified M, which appears before B in the single total order
* OR, if there was such an A, B may observe the result of some modification on M that is not `memory_order_seq_cst` and does not *happen-before* A
* OR, if there wasn't such an A, B may observe the result of some unrelated modification of M that is not `memory_order_seq_cst`
If there was a `memory_order_seq_cst` `[atomic\_thread\_fence](atomic_thread_fence "c/atomic/atomic thread fence")` operation X *sequenced-before* B, then B observes one of the following:
* the last `memory_order_seq_cst` modification of M that appears before X in the single total order
* some unrelated modification of M that appears later in M's modification order
For a pair of atomic operations on M called A and B, where A writes and B reads M's value, if there are two `memory_order_seq_cst` `[atomic\_thread\_fence](atomic_thread_fence "c/atomic/atomic thread fence")`s X and Y, and if A is *sequenced-before* X, Y is *sequenced-before* B, and X appears before Y in the Single Total Order, then B observes either:
* the effect of A
* some unrelated modification of M that appears after A in M's modification order
For a pair of atomic modifications of M called A and B, B occurs after A in M's modification order if.
* there is a `memory_order_seq_cst` `[atomic\_thread\_fence](atomic_thread_fence "c/atomic/atomic thread fence")` X such that A is *sequenced-before* X and X appears before B in the Single Total Order
* or, there is a `memory_order_seq_cst` `[atomic\_thread\_fence](atomic_thread_fence "c/atomic/atomic thread fence")` Y such that Y is *sequenced-before* B and A appears before Y in the Single Total Order
* or, there are `memory_order_seq_cst` `[atomic\_thread\_fence](atomic_thread_fence "c/atomic/atomic thread fence")`s X and Y such that A is *sequenced-before* X, Y is *sequenced-before* B, and X appears before Y in the Single Total Order.
Note that this means that:
1) as soon as atomic operations that are not tagged `memory_order_seq_cst` enter the picture, the sequential consistency is lost
2) the sequentially-consistent fences are only establishing total ordering for the fences themselves, not for the atomic operations in the general case (*sequenced-before* is not a cross-thread relationship, unlike *happens-before*) Sequential ordering may be necessary for multiple producer-multiple consumer situations where all consumers must observe the actions of all producers occurring in the same order.
Total sequential ordering requires a full memory fence CPU instruction on all multi-core systems. This may become a performance bottleneck since it forces the affected memory accesses to propagate to every core.
### Relationship with volatile
Within a thread of execution, accesses (reads and writes) through [volatile lvalues](../language/volatile "c/language/volatile") cannot be reordered past observable side-effects (including other volatile accesses) that are separated by a sequence point within the same thread, but this order is not guaranteed to be observed by another thread, since volatile access does not establish inter-thread synchronization.
In addition, volatile accesses are not atomic (concurrent read and write is a [data race](../language/memory_model "c/language/memory model")) and do not order memory (non-volatile memory accesses may be freely reordered around the volatile access).
One notable exception is Visual Studio, where, with default settings, every volatile write has release semantics and every volatile read has acquire semantics ([Microsoft Docs](https://docs.microsoft.com/en-us/cpp/cpp/volatile-cpp)), and thus volatiles may be used for inter-thread synchronization. Standard `volatile` semantics are not applicable to multithreaded programming, although they are sufficient for e.g. communication with a `[signal](../program/signal "c/program/signal")` handler that runs in the same thread when applied to `[sig\_atomic\_t](http://en.cppreference.com/w/c/program/sig_atomic_t)` variables.
### Examples
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.1/4 memory\_order (p: 200)
+ 7.17.3 Order and consistency (p: 201-203)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.1/4 memory\_order (p: 273)
+ 7.17.3 Order and consistency (p: 275-277)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/memory_order "cpp/atomic/memory order") for memory order |
### External links
* [MOESI protocol](https://en.wikipedia.org/wiki/MOESI_protocol "enwiki:MOESI protocol")
* [x86-TSO: A Rigorous and Usable Programmer’s Model for x86 Multiprocessors](http://www.cl.cam.ac.uk/~pes20/weakmemory/cacm.pdf) P. Sewell et. al., 2010
* [A Tutorial Introduction to the ARM and POWER Relaxed Memory Models](http://www.cl.cam.ac.uk/~pes20/ppc-supplemental/test7.pdf) P. Sewell et al, 2012
* [MESIF: A Two-Hop Cache Coherency Protocol for Point-to-Point Interconnects](https://researchspace.auckland.ac.nz/bitstream/handle/2292/11594/MESIF-2009.pdf?sequence=6) J.R. Goodman, H.H.J. Hum, 2009
| programming_docs |
c atomic_flag_test_and_set, atomic_flag_test_and_set_explicit atomic\_flag\_test\_and\_set, atomic\_flag\_test\_and\_set\_explicit
====================================================================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
_Bool atomic_flag_test_and_set( volatile atomic_flag* obj );
```
| (1) | (since C11) |
|
```
_Bool atomic_flag_test_and_set_explicit( volatile atomic_flag* obj, memory_order order );
```
| (2) | (since C11) |
Atomically changes the state of a `atomic_flag` pointed to by `obj` to set (`true`) and returns the previous value. The first version orders memory accesses according to `[memory\_order\_seq\_cst](memory_order "c/atomic/memory order")`, the second version orders memory accesses according to `order`.
The argument is pointer to a volatile atomic flag to accept addresses of both non-volatile and [volatile](../language/volatile "c/language/volatile") (e.g. memory-mapped I/O) atomic flags.
### Parameters
| | | |
| --- | --- | --- |
| obj | - | pointer to the atomic flag object to modify |
| order | - | the memory synchronization ordering for this operation: all values are permitted |
### Return value
The previous value held by the atomic flag pointed to by `obj`.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.8.1 The atomic\_flag\_test\_and\_set functions (p: 209)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.8.1 The atomic\_flag\_test\_and\_set functions (p: 285-286)
### See also
| | |
| --- | --- |
| [atomic\_flag\_clearatomic\_flag\_clear\_explicit](atomic_flag_clear "c/atomic/atomic flag clear")
(C11) | sets an atomic\_flag to false (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_flag_test_and_set "cpp/atomic/atomic flag test and set") for `atomic_flag_test_and_set, atomic_flag_test_and_set_explicit` |
c atomic_signal_fence atomic\_signal\_fence
=====================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
void atomic_signal_fence( memory_order order );
```
| | (since C11) |
Establishes memory synchronization ordering of non-atomic and relaxed atomic accesses, as instructed by `order`, between a thread and a signal handler executed on the same thread. This is equivalent to `[atomic\_thread\_fence](atomic_thread_fence "c/atomic/atomic thread fence")`, except no CPU instructions for memory ordering are issued. Only reordering of the instructions by the compiler is suppressed as `order` instructs. For example, a fence with release semantics prevents reads or writes from being moved past subsequent writes and a fence with acquire semantics prevents reads or writes from being moved ahead of preceding reads.
### Parameters
| | | |
| --- | --- | --- |
| order | - | the memory ordering executed by this fence |
### Return value
(none).
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.4.2 The atomic\_signal\_fence function (p: 204-205)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.4.2 The atomic\_signal\_fence function (p: 279)
### See also
| | |
| --- | --- |
| [atomic\_thread\_fence](atomic_thread_fence "c/atomic/atomic thread fence")
(C11) | generic memory order-dependent fence synchronization primitive (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic_signal_fence "cpp/atomic/atomic signal fence") for `atomic_signal_fence` |
c ATOMIC_*_LOCK_FREE ATOMIC\_\*\_LOCK\_FREE
======================
| Defined in header `<stdatomic.h>` | | |
| --- | --- | --- |
|
```
#define ATOMIC_BOOL_LOCK_FREE /* implementation-defined */
#define ATOMIC_CHAR_LOCK_FREE /* implementation-defined */
#define ATOMIC_CHAR16_T_LOCK_FREE /* implementation-defined */
#define ATOMIC_CHAR32_T_LOCK_FREE /* implementation-defined */
#define ATOMIC_WCHAR_T_LOCK_FREE /* implementation-defined */
#define ATOMIC_SHORT_LOCK_FREE /* implementation-defined */
#define ATOMIC_INT_LOCK_FREE /* implementation-defined */
#define ATOMIC_LONG_LOCK_FREE /* implementation-defined */
#define ATOMIC_LLONG_LOCK_FREE /* implementation-defined */
#define ATOMIC_POINTER_LOCK_FREE /* implementation-defined */
```
| | (since C11) |
|
```
#define ATOMIC_CHAR8_T_LOCK_FREE /* implementation-defined */
```
| | (since C23) |
Expands to [preprocessor constant expressions](../language/constant_expression "c/language/constant expression") that evaluate to either `0`, `1`, or `2` which indicate the lock-free property of the corresponding [atomic types](../thread#Atomic_operations "c/thread") (both signed and unsigned).
| Value | Explanation |
| --- | --- |
| `0` | The atomic type is never lock-free |
| `1` | The atomic type is sometimes lock-free |
| `2` | The atomic type is always lock-free |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.17.1/3 atomic lock-free macros (p: 200)
* C11 standard (ISO/IEC 9899:2011):
+ 7.17.1/3 atomic lock-free macros (p: 273)
c Pseudo-random number generation Pseudo-random number generation
===============================
| Defined in header `<stdlib.h>` |
| --- |
| [rand](random/rand "c/numeric/random/rand") | generates a pseudo-random number (function) |
| [srand](random/srand "c/numeric/random/srand") | seeds pseudo-random number generator (function) |
| [RAND\_MAX](random/rand_max "c/numeric/random/RAND MAX") | maximum possible value generated by `[rand](http://en.cppreference.com/w/c/numeric/random/rand)()` (macro constant) |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.2 Pseudo-random sequence generation functions (p: 252-253)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.2 Pseudo-random sequence generation functions (p: 346-347)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.2 Pseudo-random sequence generation functions (p: 312-313)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.2 Pseudo-random sequence generation functions
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/random "cpp/numeric/random") for Pseudo-random number generation |
c Type-generic math Type-generic math
=================
The header `<tgmath.h>` includes the headers `<math.h>` and `<complex.h>` and defines several type-generic macros that determine which real or, when applicable, complex function to call based on the types of the arguments.
For each macro, the parameters whose corresponding real type in the unsuffixed math.h function is `double` are known as *generic parameters* (for example, both parameters of `[pow](math/pow "c/numeric/math/pow")` are generic parameters, but only the first parameter of `[scalbn](math/scalbn "c/numeric/math/scalbn")` is a generic parameter).
When a `<tgmath.h>` macro is used the types of the arguments passed to the generic parameters determine which function is selected by the macro as described below. If the types of the arguments are not [compatible](../language/type#Compatible_types "c/language/type") with the parameter types of the selected function, the behavior is undefined (e.g. if a complex argument is passed into a real-only `<tgmath.h>`'s macro: `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex) fc; [ceil](http://en.cppreference.com/w/c/numeric/math/ceil)(fc);` or `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex) dc; double d; [fmax](http://en.cppreference.com/w/c/numeric/math/fmax)(dc, d);` are examples of undefined behavior).
Note: type-generic macros were implemented in implementation-defined manner in C99, but C11 keyword [`_Generic`](../keyword/_generic "c/keyword/ Generic") makes it possible to implement these macros in portable manner.
### Complex/real type-generic macros
For all functions that have both real and complex counterparts, a type-generic macro `XXX` exists, which calls either of:
* real function:
+ `float` variant `XXXf`
+ `double` variant `XXX`
+ `long double` variant `XXXl`
* complex function:
+ `float` variant `cXXXf`
+ `double` variant `cXXX`
+ `long double` variant `cXXXl`
An exception to the above rule is the `fabs` macro (see the table below).
The function to call is determined as follows:
* If any of the arguments for the generic parameters is imaginary, the behavior is specified on each function reference page individually (in particular, `sin`, `cos`, `tag`, `cosh`, `sinh`, `tanh`, `asin`, `atan`, `asinh`, and `atanh` call *real* functions, the return types of `sin`, `tan`, `sinh`, `tanh`, `asin`, `atan`, `asinh`, and `atanh` are imaginary, and the return types of `cos` and `cosh` are real).
* If any of the arguments for the generic parameters is complex, then the complex function is called, otherwise the real function is called.
* If any of the arguments for the generic parameters is `long double`, then the `long double` variant is called. Otherwise, if any of the parameters is `double` or integer, then the `double` variant is called. Otherwise, `float` variant is called.
The type-generic macros are as follows:
| Type-generic macro | Real function variants | Complex function variants |
| --- | --- | --- |
| | `float` | `double` | `long double` | `float` | `double` | `long double` |
| fabs | [`fabsf`](math/fabs "c/numeric/math/fabs") | [`fabs`](math/fabs "c/numeric/math/fabs") | [`fabsl`](math/fabs "c/numeric/math/fabs") | [`cabsf`](complex/cabs "c/numeric/complex/cabs") | [`cabs`](complex/cabs "c/numeric/complex/cabs") | [`cabsl`](complex/cabs "c/numeric/complex/cabs") |
| exp | [`expf`](math/exp "c/numeric/math/exp") | [`exp`](math/exp "c/numeric/math/exp") | [`expl`](math/exp "c/numeric/math/exp") | [`cexpf`](complex/cexp "c/numeric/complex/cexp") | [`cexp`](complex/cexp "c/numeric/complex/cexp") | [`cexpl`](complex/cexp "c/numeric/complex/cexp") |
| log | [`logf`](math/log "c/numeric/math/log") | [`log`](math/log "c/numeric/math/log") | [`logl`](math/log "c/numeric/math/log") | [`clogf`](complex/clog "c/numeric/complex/clog") | [`clog`](complex/clog "c/numeric/complex/clog") | [`clogl`](complex/clog "c/numeric/complex/clog") |
| pow | [`powf`](math/pow "c/numeric/math/pow") | [`pow`](math/pow "c/numeric/math/pow") | [`powl`](math/pow "c/numeric/math/pow") | [`cpowf`](complex/cpow "c/numeric/complex/cpow") | [`cpow`](complex/cpow "c/numeric/complex/cpow") | [`cpowl`](complex/cpow "c/numeric/complex/cpow") |
| sqrt | [`sqrtf`](math/sqrt "c/numeric/math/sqrt") | [`sqrt`](math/sqrt "c/numeric/math/sqrt") | [`sqrtl`](math/sqrt "c/numeric/math/sqrt") | [`csqrtf`](complex/csqrt "c/numeric/complex/csqrt") | [`csqrt`](complex/csqrt "c/numeric/complex/csqrt") | [`csqrtl`](complex/csqrt "c/numeric/complex/csqrt") |
| sin | [`sinf`](math/sin "c/numeric/math/sin") | [`sin`](math/sin "c/numeric/math/sin") | [`sinl`](math/sin "c/numeric/math/sin") | [`csinf`](complex/csin "c/numeric/complex/csin") | [`csin`](complex/csin "c/numeric/complex/csin") | [`csinl`](complex/csin "c/numeric/complex/csin") |
| cos | [`cosf`](math/cos "c/numeric/math/cos") | [`cos`](math/cos "c/numeric/math/cos") | [`cosl`](math/cos "c/numeric/math/cos") | [`ccosf`](complex/ccos "c/numeric/complex/ccos") | [`ccos`](complex/ccos "c/numeric/complex/ccos") | [`ccosl`](complex/ccos "c/numeric/complex/ccos") |
| tan | [`tanf`](math/tan "c/numeric/math/tan") | [`tan`](math/tan "c/numeric/math/tan") | [`tanl`](math/tan "c/numeric/math/tan") | [`ctanf`](complex/ctan "c/numeric/complex/ctan") | [`ctan`](complex/ctan "c/numeric/complex/ctan") | [`ctanl`](complex/ctan "c/numeric/complex/ctan") |
| asin | [`asinf`](math/asin "c/numeric/math/asin") | [`asin`](math/asin "c/numeric/math/asin") | [`asinl`](math/asin "c/numeric/math/asin") | [`casinf`](complex/casin "c/numeric/complex/casin") | [`casin`](complex/casin "c/numeric/complex/casin") | [`casinl`](complex/casin "c/numeric/complex/casin") |
| acos | [`acosf`](math/acos "c/numeric/math/acos") | [`acos`](math/acos "c/numeric/math/acos") | [`acosl`](math/acos "c/numeric/math/acos") | [`cacosf`](complex/cacos "c/numeric/complex/cacos") | [`cacos`](complex/cacos "c/numeric/complex/cacos") | [`cacosl`](complex/cacos "c/numeric/complex/cacos") |
| atan | [`atanf`](math/atan "c/numeric/math/atan") | [`atan`](math/atan "c/numeric/math/atan") | [`atanl`](math/atan "c/numeric/math/atan") | [`catanf`](complex/catan "c/numeric/complex/catan") | [`catan`](complex/catan "c/numeric/complex/catan") | [`catanl`](complex/catan "c/numeric/complex/catan") |
| sinh | [`sinhf`](math/sinh "c/numeric/math/sinh") | [`sinh`](math/sinh "c/numeric/math/sinh") | [`sinhl`](math/sinh "c/numeric/math/sinh") | [`csinhf`](complex/csinh "c/numeric/complex/csinh") | [`csinh`](complex/csinh "c/numeric/complex/csinh") | [`csinhl`](complex/csinh "c/numeric/complex/csinh") |
| cosh | [`coshf`](math/cosh "c/numeric/math/cosh") | [`cosh`](math/cosh "c/numeric/math/cosh") | [`coshl`](math/cosh "c/numeric/math/cosh") | [`ccoshf`](complex/ccosh "c/numeric/complex/ccosh") | [`ccosh`](complex/ccosh "c/numeric/complex/ccosh") | [`ccoshl`](complex/ccosh "c/numeric/complex/ccosh") |
| tanh | [`tanhf`](math/tanh "c/numeric/math/tanh") | [`tanh`](math/tanh "c/numeric/math/tanh") | [`tanhl`](math/tanh "c/numeric/math/tanh") | [`ctanhf`](complex/ctanh "c/numeric/complex/ctanh") | [`ctanh`](complex/ctanh "c/numeric/complex/ctanh") | [`ctanhl`](complex/ctanh "c/numeric/complex/ctanh") |
| asinh | [`asinhf`](math/asinh "c/numeric/math/asinh") | [`asinh`](math/asinh "c/numeric/math/asinh") | [`asinhl`](math/asinh "c/numeric/math/asinh") | [`casinhf`](complex/casinh "c/numeric/complex/casinh") | [`casinh`](complex/casinh "c/numeric/complex/casinh") | [`casinhl`](complex/casinh "c/numeric/complex/casinh") |
| acosh | [`acoshf`](math/acosh "c/numeric/math/acosh") | [`acosh`](math/acosh "c/numeric/math/acosh") | [`acoshl`](math/acosh "c/numeric/math/acosh") | [`cacoshf`](complex/cacosh "c/numeric/complex/cacosh") | [`cacosh`](complex/cacosh "c/numeric/complex/cacosh") | [`cacoshl`](complex/cacosh "c/numeric/complex/cacosh") |
| atanh | [`atanhf`](math/atanh "c/numeric/math/atanh") | [`atanh`](math/atanh "c/numeric/math/atanh") | [`atanhl`](math/atanh "c/numeric/math/atanh") | [`catanhf`](complex/catanh "c/numeric/complex/catanh") | [`catanh`](complex/catanh "c/numeric/complex/catanh") | [`catanhl`](complex/catanh "c/numeric/complex/catanh") |
### Real-only functions
For all functions that do not have complex counterparts, with the exception of `modf`, a type-generic macro `XXX` exists, which calls either of the variants of a real function:
* `float` variant `XXXf`
* `double` variant `XXX`
* `long double` variant `XXXl`
The function to call is determined as follows:
* If any of the arguments for the generic parameters is `long double`, then the `long double` variant is called. Otherwise, if any of the arguments for the generic parameters is `double`, then the `double` variant is called. Otherwise, `float` variant is called.
| Type-generic macro | Real function variants |
| --- | --- |
| | `float` | `double` | `long double` |
| atan2 | [`atan2f`](math/atan2 "c/numeric/math/atan2") | [`atan2`](math/atan2 "c/numeric/math/atan2") | [`atan2l`](math/atan2 "c/numeric/math/atan2") |
| cbrt | [`cbrtf`](math/cbrt "c/numeric/math/cbrt") | [`cbrt`](math/cbrt "c/numeric/math/cbrt") | [`cbrtl`](math/cbrt "c/numeric/math/cbrt") |
| ceil | [`ceilf`](math/ceil "c/numeric/math/ceil") | [`ceil`](math/ceil "c/numeric/math/ceil") | [`ceill`](math/ceil "c/numeric/math/ceil") |
| copysign | [`copysignf`](math/copysign "c/numeric/math/copysign") | [`copysign`](math/copysign "c/numeric/math/copysign") | [`copysignl`](math/copysign "c/numeric/math/copysign") |
| erf | [`erff`](math/erf "c/numeric/math/erf") | [`erf`](math/erf "c/numeric/math/erf") | [`erfl`](math/erf "c/numeric/math/erf") |
| erfc | [`erfcf`](math/erfc "c/numeric/math/erfc") | [`erfc`](math/erfc "c/numeric/math/erfc") | [`erfcl`](math/erfc "c/numeric/math/erfc") |
| exp2 | [`exp2f`](math/exp2 "c/numeric/math/exp2") | [`exp2`](math/exp2 "c/numeric/math/exp2") | [`exp2l`](math/exp2 "c/numeric/math/exp2") |
| expm1 | [`expm1f`](math/expm1 "c/numeric/math/expm1") | [`expm1`](math/expm1 "c/numeric/math/expm1") | [`expm1l`](math/expm1 "c/numeric/math/expm1") |
| fdim | [`fdimf`](math/fdim "c/numeric/math/fdim") | [`fdim`](math/fdim "c/numeric/math/fdim") | [`fdiml`](math/fdim "c/numeric/math/fdim") |
| floor | [`floorf`](math/floor "c/numeric/math/floor") | [`floor`](math/floor "c/numeric/math/floor") | [`floorl`](math/floor "c/numeric/math/floor") |
| fma | [`fmaf`](math/fma "c/numeric/math/fma") | [`fma`](math/fma "c/numeric/math/fma") | [`fmal`](math/fma "c/numeric/math/fma") |
| fmax | [`fmaxf`](math/fmax "c/numeric/math/fmax") | [`fmax`](math/fmax "c/numeric/math/fmax") | [`fmaxl`](math/fmax "c/numeric/math/fmax") |
| fmin | [`fminf`](math/fmin "c/numeric/math/fmin") | [`fmin`](math/fmin "c/numeric/math/fmin") | [`fminl`](math/fmin "c/numeric/math/fmin") |
| fmod | [`fmodf`](math/fmod "c/numeric/math/fmod") | [`fmod`](math/fmod "c/numeric/math/fmod") | [`fmodl`](math/fmod "c/numeric/math/fmod") |
| frexp | [`frexpf`](math/frexp "c/numeric/math/frexp") | [`frexp`](math/frexp "c/numeric/math/frexp") | [`frexpl`](math/frexp "c/numeric/math/frexp") |
| hypot | [`hypotf`](math/hypot "c/numeric/math/hypot") | [`hypot`](math/hypot "c/numeric/math/hypot") | [`hypotl`](math/hypot "c/numeric/math/hypot") |
| ilogb | [`ilogbf`](math/ilogb "c/numeric/math/ilogb") | [`ilogb`](math/ilogb "c/numeric/math/ilogb") | [`ilogbl`](math/ilogb "c/numeric/math/ilogb") |
| ldexp | [`ldexpf`](math/ldexp "c/numeric/math/ldexp") | [`ldexp`](math/ldexp "c/numeric/math/ldexp") | [`ldexpl`](math/ldexp "c/numeric/math/ldexp") |
| lgamma | [`lgammaf`](math/lgamma "c/numeric/math/lgamma") | [`lgamma`](math/lgamma "c/numeric/math/lgamma") | [`lgammal`](math/lgamma "c/numeric/math/lgamma") |
| llrint | [`llrintf`](math/rint "c/numeric/math/rint") | [`llrint`](math/rint "c/numeric/math/rint") | [`llrintl`](math/rint "c/numeric/math/rint") |
| llround | [`llroundf`](math/round "c/numeric/math/round") | [`llround`](math/round "c/numeric/math/round") | [`llroundl`](math/round "c/numeric/math/round") |
| log10 | [`log10f`](math/log10 "c/numeric/math/log10") | [`log10`](math/log10 "c/numeric/math/log10") | [`log10l`](math/log10 "c/numeric/math/log10") |
| log1p | [`log1pf`](math/log1p "c/numeric/math/log1p") | [`log1p`](math/log1p "c/numeric/math/log1p") | [`log1pl`](math/log1p "c/numeric/math/log1p") |
| log2 | [`log2f`](math/log2 "c/numeric/math/log2") | [`log2`](math/log2 "c/numeric/math/log2") | [`log2l`](math/log2 "c/numeric/math/log2") |
| logb | [`logbf`](math/logb "c/numeric/math/logb") | [`logb`](math/logb "c/numeric/math/logb") | [`logbl`](math/logb "c/numeric/math/logb") |
| lrint | [`lrintf`](math/rint "c/numeric/math/rint") | [`lrint`](math/rint "c/numeric/math/rint") | [`lrintl`](math/rint "c/numeric/math/rint") |
| lround | [`lroundf`](math/round "c/numeric/math/round") | [`lround`](math/round "c/numeric/math/round") | [`lroundl`](math/round "c/numeric/math/round") |
| nearbyint | [`nearbyintf`](math/nearbyint "c/numeric/math/nearbyint") | [`nearbyint`](math/nearbyint "c/numeric/math/nearbyint") | [`nearbyintl`](math/nearbyint "c/numeric/math/nearbyint") |
| nextafter | [`nextafterf`](math/nextafter "c/numeric/math/nextafter") | [`nextafter`](math/nextafter "c/numeric/math/nextafter") | [`nextafterl`](math/nextafter "c/numeric/math/nextafter") |
| nexttoward | [`nexttowardf`](math/nextafter "c/numeric/math/nextafter") | [`nexttoward`](math/nextafter "c/numeric/math/nextafter") | [`nexttowardl`](math/nextafter "c/numeric/math/nextafter") |
| remainder | [`remainderf`](math/remainder "c/numeric/math/remainder") | [`remainder`](math/remainder "c/numeric/math/remainder") | [`remainderl`](math/remainder "c/numeric/math/remainder") |
| remquo | [`remquof`](math/remquo "c/numeric/math/remquo") | [`remquo`](math/remquo "c/numeric/math/remquo") | [`remquol`](math/remquo "c/numeric/math/remquo") |
| rint | [`rintf`](math/rint "c/numeric/math/rint") | [`rint`](math/rint "c/numeric/math/rint") | [`rintl`](math/rint "c/numeric/math/rint") |
| round | [`roundf`](math/round "c/numeric/math/round") | [`round`](math/round "c/numeric/math/round") | [`roundl`](math/round "c/numeric/math/round") |
| scalbln | [`scalblnf`](math/scalbn "c/numeric/math/scalbn") | [`scalbln`](math/scalbn "c/numeric/math/scalbn") | [`scalblnl`](math/scalbn "c/numeric/math/scalbn") |
| scalbn | [`scalbnf`](math/scalbn "c/numeric/math/scalbn") | [`scalbn`](math/scalbn "c/numeric/math/scalbn") | [`scalbnl`](math/scalbn "c/numeric/math/scalbn") |
| tgamma | [`tgammaf`](math/tgamma "c/numeric/math/tgamma") | [`tgamma`](math/tgamma "c/numeric/math/tgamma") | [`tgammal`](math/tgamma "c/numeric/math/tgamma") |
| trunc | [`truncf`](math/trunc "c/numeric/math/trunc") | [`trunc`](math/trunc "c/numeric/math/trunc") | [`truncl`](math/trunc "c/numeric/math/trunc") |
### Complex-only functions
For all complex number functions that do not have real counterparts, a type-generic macro `cXXX` exists, which calls either of the variants of a complex function:
* `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)` variant `cXXXf`
* `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)` variant `cXXX`
* `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)` variant `cXXXl`
The function to call is determined as follows:
* If any of the arguments for the generic parameters is real, complex, or imaginary, then the appropriate complex function is called.
| Type-generic macro | Complex function variants |
| --- | --- |
| | `float` | `double` | `long double` |
| carg | [`cargf`](complex/carg "c/numeric/complex/carg") | [`carg`](complex/carg "c/numeric/complex/carg") | [`cargl`](complex/carg "c/numeric/complex/carg") |
| conj | [`conjf`](complex/conj "c/numeric/complex/conj") | [`conj`](complex/conj "c/numeric/complex/conj") | [`conjl`](complex/conj "c/numeric/complex/conj") |
| creal | [`crealf`](complex/creal "c/numeric/complex/creal") | [`creal`](complex/creal "c/numeric/complex/creal") | [`creall`](complex/creal "c/numeric/complex/creal") |
| cimag | [`cimagf`](complex/cimag "c/numeric/complex/cimag") | [`cimag`](complex/cimag "c/numeric/complex/cimag") | [`cimagl`](complex/cimag "c/numeric/complex/cimag") |
| cproj | [`cprojf`](complex/cproj "c/numeric/complex/cproj") | [`cproj`](complex/cproj "c/numeric/complex/cproj") | [`cprojl`](complex/cproj "c/numeric/complex/cproj") |
### Example
```
#include <stdio.h>
#include <tgmath.h>
int main(void)
{
int i = 2;
printf("sqrt(2) = %f\n", sqrt(i)); // argument type is int, calls sqrt
float f = 0.5;
printf("sin(0.5f) = %f\n", sin(f)); // argument type is float, calls sinf
float complex dc = 1 + 0.5*I;
float complex z = sqrt(dc); // argument type is float complex, calls csqrtf
printf("sqrt(1 + 0.5i) = %f+%fi\n",
creal(z), // argument type is float complex, calls crealf
cimag(z)); // argument type is float complex, calls cimagf
}
```
Output:
```
sqrt(2) = 1.414214
sin(0.5f) = 0.479426
sqrt(1 + 0.5i) = 1.029086+0.242934i
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
* C11 standard (ISO/IEC 9899:2011):
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
* C99 standard (ISO/IEC 9899:1999):
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
| programming_docs |
c Common mathematical functions Common mathematical functions
=============================
### Functions
| Defined in header `<stdlib.h>` |
| --- |
| [abslabsllabs](math/abs "c/numeric/math/abs")
(C99) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) |
| [divldivlldiv](math/div "c/numeric/math/div")
(C99) | computes quotient and remainder of integer division (function) |
| Defined in header `<inttypes.h>` |
| [imaxabs](math/abs "c/numeric/math/abs")
(C99) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) |
| [imaxdiv](math/div "c/numeric/math/div")
(C99) | computes quotient and remainder of integer division (function) |
| Defined in header `<math.h>` |
| Basic operations |
| [fabsfabsffabsl](math/fabs "c/numeric/math/fabs")
(C99)(C99) | computes absolute value of a floating-point value (\(\small{|x|}\)|x|) (function) |
| [fmodfmodffmodl](math/fmod "c/numeric/math/fmod")
(C99)(C99) | computes remainder of the floating-point division operation (function) |
| [remainderremainderfremainderl](math/remainder "c/numeric/math/remainder")
(C99)(C99)(C99) | computes signed remainder of the floating-point division operation (function) |
| [remquoremquofremquol](math/remquo "c/numeric/math/remquo")
(C99)(C99)(C99) | computes signed remainder as well as the three last bits of the division operation (function) |
| [fmafmaffmal](math/fma "c/numeric/math/fma")
(C99)(C99)(C99) | computes fused multiply-add operation (function) |
| [fmaxfmaxffmaxl](math/fmax "c/numeric/math/fmax")
(C99)(C99)(C99) | determines larger of two floating-point values (function) |
| [fminfminffminl](math/fmin "c/numeric/math/fmin")
(C99)(C99)(C99) | determines smaller of two floating-point values (function) |
| [fdimfdimffdiml](math/fdim "c/numeric/math/fdim")
(C99)(C99)(C99) | determines positive difference of two floating-point values (\({\small\max{(0, x-y)} }\)max(0, x-y)) (function) |
| [nannanfnanl](math/nan "c/numeric/math/nan")
(C99)(C99)(C99) | returns a NaN (not-a-number) (function) |
| Exponential functions |
| [expexpfexpl](math/exp "c/numeric/math/exp")
(C99)(C99) | computes *e* raised to the given power (\({\small e^x}\)ex) (function) |
| [exp2exp2fexp2l](math/exp2 "c/numeric/math/exp2")
(C99)(C99)(C99) | computes *2* raised to the given power (\({\small 2^x}\)2x) (function) |
| [expm1expm1fexpm1l](math/expm1 "c/numeric/math/expm1")
(C99)(C99)(C99) | computes *e* raised to the given power, minus one (\({\small e^x-1}\)ex-1) (function) |
| [loglogflogl](math/log "c/numeric/math/log")
(C99)(C99) | computes natural (base-*e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [log10log10flog10l](math/log10 "c/numeric/math/log10")
(C99)(C99) | computes common (base-*10*) logarithm (\({\small \log\_{10}{x} }\)log10(x)) (function) |
| [log2log2flog2l](math/log2 "c/numeric/math/log2")
(C99)(C99)(C99) | computes base-2 logarithm (\({\small \log\_{2}{x} }\)log2(x)) (function) |
| [log1plog1pflog1pl](math/log1p "c/numeric/math/log1p")
(C99)(C99)(C99) | computes natural (base-*e*) logarithm of 1 plus the given number (\({\small \ln{(1+x)} }\)ln(1+x)) (function) |
| Power functions |
| [powpowfpowl](math/pow "c/numeric/math/pow")
(C99)(C99) | computes a number raised to the given power (\(\small{x^y}\)xy) (function) |
| [sqrtsqrtfsqrtl](math/sqrt "c/numeric/math/sqrt")
(C99)(C99) | computes square root (\(\small{\sqrt{x} }\)√x) (function) |
| [cbrtcbrtfcbrtl](math/cbrt "c/numeric/math/cbrt")
(C99)(C99)(C99) | computes cubic root (\(\small{\sqrt[3]{x} }\)3√x) (function) |
| [hypothypotfhypotl](math/hypot "c/numeric/math/hypot")
(C99)(C99)(C99) | computes square root of the sum of the squares of two given numbers (\(\scriptsize{\sqrt{x^2+y^2} }\)√x2+y2) (function) |
| Trigonometric functions |
| [sinsinfsinl](math/sin "c/numeric/math/sin")
(C99)(C99) | computes sine (\({\small\sin{x} }\)sin(x)) (function) |
| [coscosfcosl](math/cos "c/numeric/math/cos")
(C99)(C99) | computes cosine (\({\small\cos{x} }\)cos(x)) (function) |
| [tantanftanl](math/tan "c/numeric/math/tan")
(C99)(C99) | computes tangent (\({\small\tan{x} }\)tan(x)) (function) |
| [asinasinfasinl](math/asin "c/numeric/math/asin")
(C99)(C99) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) |
| [acosacosfacosl](math/acos "c/numeric/math/acos")
(C99)(C99) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [atanatanfatanl](math/atan "c/numeric/math/atan")
(C99)(C99) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [atan2atan2fatan2l](math/atan2 "c/numeric/math/atan2")
(C99)(C99) | computes arc tangent, using signs to determine quadrants (function) |
| Hyperbolic functions |
| [sinhsinhfsinhl](math/sinh "c/numeric/math/sinh")
(C99)(C99) | computes hyperbolic sine (\({\small\sinh{x} }\)sinh(x)) (function) |
| [coshcoshfcoshl](math/cosh "c/numeric/math/cosh")
(C99)(C99) | computes hyperbolic cosine (\({\small\cosh{x} }\)cosh(x)) (function) |
| [tanhtanhftanhl](math/tanh "c/numeric/math/tanh")
(C99)(C99) | computes hyperbolic tangent (\({\small\tanh{x} }\)tanh(x)) (function) |
| [asinhasinhfasinhl](math/asinh "c/numeric/math/asinh")
(C99)(C99)(C99) | computes inverse hyperbolic sine (\({\small\operatorname{arsinh}{x} }\)arsinh(x)) (function) |
| [acoshacoshfacoshl](math/acosh "c/numeric/math/acosh")
(C99)(C99)(C99) | computes inverse hyperbolic cosine (\({\small\operatorname{arcosh}{x} }\)arcosh(x)) (function) |
| [atanhatanhfatanhl](math/atanh "c/numeric/math/atanh")
(C99)(C99)(C99) | computes inverse hyperbolic tangent (\({\small\operatorname{artanh}{x} }\)artanh(x)) (function) |
| Error and gamma functions |
| [erferfferfl](math/erf "c/numeric/math/erf")
(C99)(C99)(C99) | computes error function (function) |
| [erfcerfcferfcl](math/erfc "c/numeric/math/erfc")
(C99)(C99)(C99) | computes complementary error function (function) |
| [tgammatgammaftgammal](math/tgamma "c/numeric/math/tgamma")
(C99)(C99)(C99) | computes gamma function (function) |
| [lgammalgammaflgammal](math/lgamma "c/numeric/math/lgamma")
(C99)(C99)(C99) | computes natural (base-*e*) logarithm of the gamma function (function) |
| Nearest integer floating-point operations |
| [ceilceilfceill](math/ceil "c/numeric/math/ceil")
(C99)(C99) | computes smallest integer not less than the given value (function) |
| [floorfloorffloorl](math/floor "c/numeric/math/floor")
(C99)(C99) | computes largest integer not greater than the given value (function) |
| [trunctruncftruncl](math/trunc "c/numeric/math/trunc")
(C99)(C99)(C99) | rounds to nearest integer not greater in magnitude than the given value (function) |
| [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](math/round "c/numeric/math/round")
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) | rounds to nearest integer, rounding away from zero in halfway cases (function) |
| [nearbyintnearbyintfnearbyintl](math/nearbyint "c/numeric/math/nearbyint")
(C99)(C99)(C99) | rounds to an integer using current rounding mode (function) |
| [rintrintfrintllrintlrintflrintlllrintllrintfllrintl](math/rint "c/numeric/math/rint")
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) | rounds to an integer using current rounding mode with exception if the result differs (function) |
| Floating-point manipulation functions |
| [frexpfrexpffrexpl](math/frexp "c/numeric/math/frexp")
(C99)(C99) | breaks a number into significand and a power of `2` (function) |
| [ldexpldexpfldexpl](math/ldexp "c/numeric/math/ldexp")
(C99)(C99) | multiplies a number by `2` raised to a power (function) |
| [modfmodffmodfl](math/modf "c/numeric/math/modf")
(C99)(C99) | breaks a number into integer and fractional parts (function) |
| [scalbnscalbnfscalbnlscalblnscalblnfscalblnl](math/scalbn "c/numeric/math/scalbn")
(C99)(C99)(C99)(C99)(C99)(C99) | computes efficiently a number times `[FLT\_RADIX](../types/limits "c/types/limits")` raised to a power (function) |
| [ilogbilogbfilogbl](math/ilogb "c/numeric/math/ilogb")
(C99)(C99)(C99) | extracts exponent of the given number (function) |
| [logblogbflogbl](math/logb "c/numeric/math/logb")
(C99)(C99)(C99) | extracts exponent of the given number (function) |
| [nextafternextafterfnextafterlnexttowardnexttowardfnexttowardl](math/nextafter "c/numeric/math/nextafter")
(C99)(C99)(C99)(C99)(C99)(C99) | determines next representable floating-point value towards the given value (function) |
| [copysigncopysignfcopysignl](math/copysign "c/numeric/math/copysign")
(C99)(C99)(C99) | produces a value with the magnitude of a given value and the sign of another given value (function) |
| Classification and comparison |
| [fpclassify](math/fpclassify "c/numeric/math/fpclassify")
(C99) | classifies the given floating-point value (function macro) |
| [isfinite](math/isfinite "c/numeric/math/isfinite")
(C99) | checks if the given number has finite value (function macro) |
| [isinf](math/isinf "c/numeric/math/isinf")
(C99) | checks if the given number is infinite (function macro) |
| [isnan](math/isnan "c/numeric/math/isnan")
(C99) | checks if the given number is NaN (function macro) |
| [isnormal](math/isnormal "c/numeric/math/isnormal")
(C99) | checks if the given number is normal (function macro) |
| [signbit](math/signbit "c/numeric/math/signbit")
(C99) | checks if the given number is negative (function macro) |
| [isgreater](math/isgreater "c/numeric/math/isgreater")
(C99) | checks if the first floating-point argument is greater than the second (function macro) |
| [isgreaterequal](math/isgreaterequal "c/numeric/math/isgreaterequal")
(C99) | checks if the first floating-point argument is greater or equal than the second (function macro) |
| [isless](math/isless "c/numeric/math/isless")
(C99) | checks if the first floating-point argument is less than the second (function macro) |
| [islessequal](math/islessequal "c/numeric/math/islessequal")
(C99) | checks if the first floating-point argument is less or equal than the second (function macro) |
| [islessgreater](math/islessgreater "c/numeric/math/islessgreater")
(C99) | checks if the first floating-point argument is less or greater than the second (function macro) |
| [isunordered](math/isunordered "c/numeric/math/isunordered")
(C99) | checks if two floating-point values are unordered (function macro) |
### Types
| Defined in header `<stdlib.h>` |
| --- |
| [div\_t](math/div "c/numeric/math/div") | structure type, return of the `[div](http://en.cppreference.com/w/c/numeric/math/div)` function (typedef) |
| [ldiv\_t](math/div "c/numeric/math/div") | structure type, return of the `[ldiv](http://en.cppreference.com/w/c/numeric/math/div)` function (typedef) |
| [lldiv\_t](math/div "c/numeric/math/div")
(C99) | structure type, return of the `lldiv` function (typedef) |
| Defined in header `<inttypes.h>` |
| [imaxdiv\_t](math/div "c/numeric/math/div")
(C99) | structure type, return of the `imaxdiv` function (typedef) |
| Defined in header `<math.h>` |
| [float\_tdouble\_t](math/float_t "c/numeric/math/float t")
(C99)(C99) | most efficient floating-point type at least as wide as `float` or `double` (typedef) |
### Macro constants
| Defined in header `<math.h>` |
| --- |
| [HUGE\_VALFHUGE\_VALHUGE\_VALL](math/huge_val "c/numeric/math/HUGE VAL")
(C99)(C99) | indicates value too big to be representable (infinity) by `float`, `double` and `long double` respectively (macro constant) |
| [INFINITY](math/infinity "c/numeric/math/INFINITY")
(C99) | evaluates to positive infinity or the value guaranteed to overflow a `float` (macro constant) |
| [NAN](math/nan "c/numeric/math/NAN")
(C99) | evaluates to a quiet NaN of type `float` (macro constant) |
| [FP\_FAST\_FMAFFP\_FAST\_FMAFP\_FAST\_FMAL](math/fma "c/numeric/math/fma")
(C99)(C99)(C99) | indicates that the fma function generally executes about as fast as, or faster than, a multiply and an add of double operands (macro constant) |
| [FP\_ILOGB0FP\_ILOGBNAN](math/ilogb "c/numeric/math/ilogb")
(C99)(C99) | evaluates to ilogb(x) if x is zero or NaN, respectively (macro constant) |
| [math\_errhandlingMATH\_ERRNOMATH\_ERREXCEPT](math/math_errhandling "c/numeric/math/math errhandling")
(C99)(C99)(C99) | defines the error handling mechanism used by the common mathematical functions (macro constant) |
| Classification |
| [FP\_NORMALFP\_SUBNORMALFP\_ZEROFP\_INFINITEFP\_NAN](math/fp_categories "c/numeric/math/FP categories")
(C99)(C99)(C99)(C99)(C99) | indicates a floating-point category (macro constant) |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.8 Format conversion of integer types <inttypes.h> (p: 158-160)
+ 7.12 Mathematics <math.h> (p: 169-190)
+ 7.22 General utilities <stdlib.h> (p: 248-262)
+ 7.31.5 Format conversion of integer types <inttypes.h> (p: 332)
+ 7.31.12 General utilities <stdlib.h> (p: 333)
* C11 standard (ISO/IEC 9899:2011):
+ 7.8 Format conversion of integer types <inttypes.h> (p: 217-220)
+ 7.12 Mathematics <math.h> (p: 231-261)
+ 7.22 General utilities <stdlib.h> (p: 340-360)
+ 7.31.5 Format conversion of integer types <inttypes.h> (p: 455)
+ 7.31.12 General utilities <stdlib.h> (p: 456)
* C99 standard (ISO/IEC 9899:1999):
+ 7.8 Format conversion of integer types <inttypes.h> (p: 198-201)
+ 7.12 Mathematics <math.h> (p: 212-242)
+ 7.20 General utilities <stdlib.h> (p: 306-324)
+ 7.26.4 Format conversion of integer types <inttypes.h> (p: 401)
+ 7.26.10 General utilities <stdlib.h> (p: 402)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5 MATHEMATICS <math.h>
+ 4.10 GENERAL UTILITIES <stdlib.h>
+ 4.13.4 Mathematics <math.h>
+ 7.13.7 General utilities <stdlib.h>
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math "cpp/numeric/math") for Common mathematical functions |
c Floating-point environment Floating-point environment
==========================
The floating-point environment is the set of floating-point status flags and control modes supported by the implementation. It is thread-local, each thread inherits the initial state of its floating-point environment from the parent thread. Floating-point operations modify the floating-point status flags to indicate abnormal results or auxiliary information. The state of floating-point control modes affects the outcomes of some floating-point operations.
The floating-point environment access and modification is only meaningful when [`#pragma STDC FENV_ACCESS`](https://en.cppreference.com/w/cpp/preprocessor/impl "cpp/preprocessor/impl") is set to `ON`. Otherwise the implementation is free to assume that floating-point control modes are always the default ones and that floating-point status flags are never tested or modified. In practice, few current compilers, such as HP aCC, Oracle Studio, and IBM XL, support the `#pragma` explicitly, but most compilers allow meaningful access to the floating-point environment anyway.
### Types
| Defined in header `<fenv.h>` |
| --- |
| `fenv_t` | The type representing the entire floating-point environment |
| `fexcept_t` | The type representing all floating-point status flags collectively |
### Functions
| | |
| --- | --- |
| [feclearexcept](fenv/feclearexcept "c/numeric/fenv/feclearexcept")
(C99) | clears the specified floating-point status flags (function) |
| [fetestexcept](fenv/fetestexcept "c/numeric/fenv/fetestexcept")
(C99) | determines which of the specified floating-point status flags are set (function) |
| [feraiseexcept](fenv/feraiseexcept "c/numeric/fenv/feraiseexcept")
(C99) | raises the specified floating-point exceptions (function) |
| [fegetexceptflagfesetexceptflag](fenv/feexceptflag "c/numeric/fenv/feexceptflag")
(C99)(C99) | copies the state of the specified floating-point status flags from or to the floating-point environment (function) |
| [fegetroundfesetround](fenv/feround "c/numeric/fenv/feround")
(C99)(C99) | gets or sets rounding direction (function) |
| [fegetenvfesetenv](fenv/feenv "c/numeric/fenv/feenv")
(C99) | saves or restores the current floating-point environment (function) |
| [feholdexcept](fenv/feholdexcept "c/numeric/fenv/feholdexcept")
(C99) | saves the environment, clears all status flags and ignores all future errors (function) |
| [feupdateenv](fenv/feupdateenv "c/numeric/fenv/feupdateenv")
(C99) | restores the floating-point environment and raises the previously raise exceptions (function) |
### Macros
| | |
| --- | --- |
| [FE\_ALL\_EXCEPTFE\_DIVBYZEROFE\_INEXACTFE\_INVALIDFE\_OVERFLOWFE\_UNDERFLOW](fenv/fe_exceptions "c/numeric/fenv/FE exceptions")
(C99) | floating-point exceptions (macro constant) |
| [FE\_DOWNWARDFE\_TONEARESTFE\_TOWARDZEROFE\_UPWARD](fenv/fe_round "c/numeric/fenv/FE round")
(C99) | floating-point rounding direction (macro constant) |
| [FE\_DFL\_ENV](fenv/fe_dfl_env "c/numeric/fenv/FE DFL ENV")
(C99) | default floating-point environment (macro constant) |
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.6 Floating-point environment <fenv.h> (p: 206-215)
+ 7.31.4 Floating-point environment <fenv.h> (p: 455)
* C99 standard (ISO/IEC 9899:1999):
+ 7.6 Floating-point environment <fenv.h> (p: 187-196)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/fenv "cpp/numeric/fenv") for `Floating-point environment` |
c Complex number arithmetic Complex number arithmetic
=========================
| | |
| --- | --- |
| If the macro constant `__STDC_NO_COMPLEX__` is defined by the implementation, the complex types, the header `<complex.h>` and all of the names listed here are not provided. | (since C11) |
The C programming language, as of C99, supports complex number math with the three built-in types `double _Complex`, `float _Complex`, and `long double _Complex` (see [`_Complex`](../keyword/_complex "c/keyword/ Complex")). When the header `<complex.h>` is included, the three complex number types are also accessible as `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`.
In addition to the complex types, the three imaginary types may be supported: `double _Imaginary`, `float _Imaginary`, and `long double _Imaginary` (see [`_Imaginary`](../keyword/_imaginary "c/keyword/ Imaginary")). When the header `<complex.h>` is included, the three imaginary types are also accessible as `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, `float [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, and `long double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`.
Standard arithmetic operators `+, -, *, /` can be used with real, complex, and imaginary types in any combination.
| | |
| --- | --- |
| A compiler that defines `__STDC_IEC_559_COMPLEX__` is recommended, but not required to support imaginary numbers. POSIX recommends checking if the macro `[\_Imaginary\_I](complex/imaginary_i "c/numeric/complex/Imaginary I")` is defined to identify imaginary number support. | (since C99)(until C11) |
| Imaginary numbers are supported if `__STDC_IEC_559_COMPLEX__` or `__STDC_IEC_60559_COMPLEX__` (since C23) is defined. | (since C11) |
| Defined in header `<complex.h>` |
| --- |
| Types |
| [imaginary](complex/imaginary "c/numeric/complex/imaginary")
(C99) | imaginary type macro (keyword macro) |
| [complex](complex/complex "c/numeric/complex/complex")
(C99) | complex type macro (keyword macro) |
| The imaginary constant |
| [\_Imaginary\_I](complex/imaginary_i "c/numeric/complex/Imaginary I")
(C99) | the imaginary unit constant i (macro constant) |
| [\_Complex\_I](complex/complex_i "c/numeric/complex/Complex I")
(C99) | the complex unit constant i (macro constant) |
| [I](complex/i "c/numeric/complex/I")
(C99) | the complex or imaginary unit constant i (macro constant) |
| Manipulation |
| [CMPLXCMPLXFCMPLXL](complex/cmplx "c/numeric/complex/CMPLX")
(C11)(C11)(C11) | constructs a complex number from real and imaginary parts (function macro) |
| [crealcrealfcreall](complex/creal "c/numeric/complex/creal")
(C99)(C99)(C99) | computes the real part of a complex number (function) |
| [cimagcimagfcimagl](complex/cimag "c/numeric/complex/cimag")
(C99)(C99)(C99) | computes the imaginary part a complex number (function) |
| [cabscabsfcabsl](complex/cabs "c/numeric/complex/cabs")
(C99)(C99)(C99) | computes the magnitude of a complex number (function) |
| [cargcargfcargl](complex/carg "c/numeric/complex/carg")
(C99)(C99)(C99) | computes the phase angle of a complex number (function) |
| [conjconjfconjl](complex/conj "c/numeric/complex/conj")
(C99)(C99)(C99) | computes the complex conjugate (function) |
| [cprojcprojfcprojl](complex/cproj "c/numeric/complex/cproj")
(C99)(C99)(C99) | computes the projection on Riemann sphere (function) |
| Exponential functions |
| [cexpcexpfcexpl](complex/cexp "c/numeric/complex/cexp")
(C99)(C99)(C99) | computes the complex base-e exponential (function) |
| [clogclogfclogl](complex/clog "c/numeric/complex/clog")
(C99)(C99)(C99) | computes the complex natural logarithm (function) |
| Power functions |
| [cpowcpowfcpowl](complex/cpow "c/numeric/complex/cpow")
(C99)(C99)(C99) | computes the complex power function (function) |
| [csqrtcsqrtfcsqrtl](complex/csqrt "c/numeric/complex/csqrt")
(C99)(C99)(C99) | computes the complex square root (function) |
| Trigonometric functions |
| [csincsinfcsinl](complex/csin "c/numeric/complex/csin")
(C99)(C99)(C99) | computes the complex sine (function) |
| [ccosccosfccosl](complex/ccos "c/numeric/complex/ccos")
(C99)(C99)(C99) | computes the complex cosine (function) |
| [ctanctanfctanl](complex/ctan "c/numeric/complex/ctan")
(C99)(C99)(C99) | computes the complex tangent (function) |
| [casincasinfcasinl](complex/casin "c/numeric/complex/casin")
(C99)(C99)(C99) | computes the complex arc sine (function) |
| [cacoscacosfcacosl](complex/cacos "c/numeric/complex/cacos")
(C99)(C99)(C99) | computes the complex arc cosine (function) |
| [catancatanfcatanl](complex/catan "c/numeric/complex/catan")
(C99)(C99)(C99) | computes the complex arc tangent (function) |
| Hyperbolic functions |
| [csinhcsinhfcsinhl](complex/csinh "c/numeric/complex/csinh")
(C99)(C99)(C99) | computes the complex hyperbolic sine (function) |
| [ccoshccoshfccoshl](complex/ccosh "c/numeric/complex/ccosh")
(C99)(C99)(C99) | computes the complex hyperbolic cosine (function) |
| [ctanhctanhfctanhl](complex/ctanh "c/numeric/complex/ctanh")
(C99)(C99)(C99) | computes the complex hyperbolic tangent (function) |
| [casinhcasinhfcasinhl](complex/casinh "c/numeric/complex/casinh")
(C99)(C99)(C99) | computes the complex arc hyperbolic sine (function) |
| [cacoshcacoshfcacoshl](complex/cacosh "c/numeric/complex/cacosh")
(C99)(C99)(C99) | computes the complex arc hyperbolic cosine (function) |
| [catanhcatanhfcatanhl](complex/catanh "c/numeric/complex/catanh")
(C99)(C99)(C99) | computes the complex arc hyperbolic tangent (function) |
### Notes
The following function names are potentially (since C23) reserved for future addition to `complex.h` and are not available for use in the programs that include that header: `cerf`, `cerfc`, `cexp2`, `cexpm1`, `clog10`, `clog1p`, `clog2`, `clgamma`, `ctgamma`, `csinpi`, `ccospi`, `ctanpi`, `casinpi`, `cacospi`, `catanpi`, `ccompoundn`, `cpown`, `cpowr`, `crootn`, `crsqrt`, `cexp10m1`, `cexp10`, `cexp2m1`, `clog10p1`, `clog2p1`, `clogp1` (since C23), along with their -f and -l suffixed variants.
Although the C standard names the inverse hyperbolics with "complex arc hyperbolic sine" etc., the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct names are "complex inverse hyperbolic sine" etc. Some authors use "complex area hyperbolic sine" etc.
A complex or imaginary number is infinite if one of its components is infinite, even if the other component is NaN.
A complex or imaginary number is finite if both components are neither infinities nor NaNs.
A complex or imaginary number is a zero if both components are positive or negative zeroes.
### Example
```
#include <stdio.h>
#include <complex.h>
#include <tgmath.h>
int main(void)
{
double complex z1 = I * I; // imaginary unit squared
printf("I * I = %.1f%+.1fi\n", creal(z1), cimag(z1));
double complex z2 = pow(I, 2); // imaginary unit squared
printf("pow(I, 2) = %.1f%+.1fi\n", creal(z2), cimag(z2));
double PI = acos(-1);
double complex z3 = exp(I * PI); // Euler's formula
printf("exp(I*PI) = %.1f%+.1fi\n", creal(z3), cimag(z3));
double complex z4 = 1+2*I, z5 = 1-2*I; // conjugates
printf("(1+2i)*(1-2i) = %.1f%+.1fi\n", creal(z4*z5), cimag(z4*z5));
}
```
Output:
```
I * I = -1.0+0.0i
pow(I, 2) = -1.0+0.0i
exp(I*PI) = -1.0+0.0i
(1+2i)*(1-2i) = 5.0+0.0i
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.10.8.3/1/2 `__STDC_NO_COMPLEX__` (p: 128)
+ 6.10.8.3/1/2 `__STDC_IEC_559_COMPLEX__` (p: 128)
+ 7.3 Complex arithmetic `<complex.h>` (p: 136-144)
+ 7.25 Type-generic math `<tgmath.h>` (p: 272-273)
+ 7.31.1 Complex arithmetic `<complex.h>` (p: 391)
+ Annex G (normative) IEC 60559-compatible complex arithmetic (p: 469-479)
* C11 standard (ISO/IEC 9899:2011):
+ 6.10.8.3/1/2 `__STDC_NO_COMPLEX__` (p: 177)
+ 6.10.8.3/1/2 `__STDC_IEC_559_COMPLEX__` (p: 177)
+ 7.3 Complex arithmetic `<complex.h>` (p: 188-199)
+ 7.25 Type-generic math `<tgmath.h>` (p: 373-375)
+ 7.31.1 Complex arithmetic `<complex.h>` (p: 455)
+ Annex G (normative) IEC 60559-compatible complex arithmetic (p: 532-545)
* C99 standard (ISO/IEC 9899:1999):
+ 6.10.8/2 `__STDC_IEC_559_COMPLEX__` (p: 161)
+ 7.3 Complex arithmetic `<complex.h>` (p: 170-180)
+ 7.22 Type-generic math `<tgmath.h>` (p: 335-337)
+ 7.26.1 Complex arithmetic `<complex.h>` (p: 401)
+ Annex G (informative) IEC 60559-compatible complex arithmetic (p: 467-480)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex "cpp/numeric/complex") for Complex number arithmetic |
| programming_docs |
c _Complex_I \_Complex\_I
============
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
#define _Complex_I /* unspecified */
```
| | (since C99) |
The `_Complex_I` macro expands to a value of type `const float _Complex` with the value of the imaginary unit.
### Notes
This macro may be used when `I` is not available, such as when it has been undefined by the application.
Unlike `[\_Imaginary\_I](imaginary_i "c/numeric/complex/Imaginary I")` and `[CMPLX](cmplx "c/numeric/complex/CMPLX")`, use of this macro to construct a complex number may lose the sign of zero on the imaginary component.
### Example
```
#include <stdio.h>
#include <complex.h>
#undef I
#define J _Complex_I // can be used to redefine I
int main(void)
{
// can be used to construct a complex number
double complex z = 1.0 + 2.0 * _Complex_I;
printf("1.0 + 2.0 * _Complex_I = %.1f%+.1fi\n", creal(z), cimag(z));
// sign of zero may not be preserved
double complex z2 = 0.0 + -0.0 * _Complex_I;
printf("0.0 + -0.0 * _Complex_I = %.1f%+.1fi\n", creal(z2), cimag(z2));
}
```
Possible output:
```
1.0 + 2.0 * _Complex_I = 1.0+2.0i
0.0 + -0.0 * _Complex_I = 0.0+0.0i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.1/4 \_Complex\_I (p: 188)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.1/2 \_Complex\_I (p: 170)
### See also
| | |
| --- | --- |
| [\_Imaginary\_I](imaginary_i "c/numeric/complex/Imaginary I")
(C99) | the imaginary unit constant i (macro constant) |
| [I](i "c/numeric/complex/I")
(C99) | the complex or imaginary unit constant i (macro constant) |
c cimagf, cimag, cimagl cimagf, cimag, cimagl
=====================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float cimagf( float complex z );
```
| (1) | (since C99) |
|
```
double cimag( double complex z );
```
| (2) | (since C99) |
|
```
long double cimagl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define cimag( z )
```
| (4) | (since C99) |
1-3) Returns the imaginary part of `z`.
4) Type-generic macro: if `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `long double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, or `long double`, `cimagl` is called. If `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `float [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, or `float`, `cimagf` is called. If `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, `double`, or any integer type, `cimag` is called. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
The imaginary part of `z`.
This function is fully specified for all possible inputs and is not subject to any errors described in [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling").
### Notes
For any complex variable `z`, `z == [creal](http://en.cppreference.com/w/c/numeric/complex/creal)(z) + I\*cimag(z)`.
### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
double complex z = 1.0 + 2.0*I;
printf("%f%+fi\n", creal(z), cimag(z));
}
```
Output:
```
1.000000+2.000000i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.9.2 The cimag functions (p: 197)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.9.2 The cimag functions (p: 178-179)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [crealcrealfcreall](creal "c/numeric/complex/creal")
(C99)(C99)(C99) | computes the real part of a complex number (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/imag2 "cpp/numeric/complex/imag2") for `imag` |
c catanf, catan, catanl catanf, catan, catanl
=====================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex catanf( float complex z );
```
| (1) | (since C99) |
|
```
double complex catan( double complex z );
```
| (2) | (since C99) |
|
```
long double complex catanl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define atan( z )
```
| (4) | (since C99) |
1-3) Computes the complex arc tangent of `z` with branch cuts outside the interval [−i,+i] along the imaginary axis.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `catanl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `catan` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `catanf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`atanf`, `[atan](http://en.cppreference.com/w/c/numeric/math/atan)`, `atanl`). If `z` is imaginary, then the macro invokes the corresponding real version of the function `[atanh](../math/atanh "c/numeric/math/atanh")`, implementing the formula atan(iy) = i atanh(y), and the return type of the macro is imaginary. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, complex arc tangent of `z` is returned, in the range of a strip unbounded along the imaginary axis and in the interval [−π/2; +π/2] along the real axis.
Errors and special cases are handled as if the operation is implemented by `-I \* [catanh](http://en.cppreference.com/w/c/numeric/complex/catanh)(I\*z)`.
### Notes
Inverse tangent (or arc tangent) is a multivalued function and requires a branch cut on the complex plane. The branch cut is conventionally placed at the line segments (-∞i,-i) and (+i,+∞i) of the imaginary axis. The mathematical definition of the principal value of inverse tangent is atan z = -
1/2 i [ln(1 - iz) - ln (1 + iz] ### Example
```
#include <stdio.h>
#include <float.h>
#include <complex.h>
int main(void)
{
double complex z = catan(2*I);
printf("catan(+0+2i) = %f%+fi\n", creal(z), cimag(z));
double complex z2 = catan(-conj(2*I)); // or CMPLX(-0.0, 2)
printf("catan(-0+2i) (the other side of the cut) = %f%+fi\n", creal(z2), cimag(z2));
double complex z3 = 2*catan(2*I*DBL_MAX); // or CMPLX(0, INFINITY)
printf("2*catan(+0+i*Inf) = %f%+fi\n", creal(z3), cimag(z3));
}
```
Output:
```
catan(+0+2i) = 1.570796+0.549306i
catan(-0+2i) (the other side of the cut) = -1.570796+0.549306i
2*catan(+0+i*Inf) = 3.141593+0.000000i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.5.3 The catan functions (p: 191)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.5.3 The catan functions (p: 173)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [casincasinfcasinl](casin "c/numeric/complex/casin")
(C99)(C99)(C99) | computes the complex arc sine (function) |
| [cacoscacosfcacosl](cacos "c/numeric/complex/cacos")
(C99)(C99)(C99) | computes the complex arc cosine (function) |
| [ctanctanfctanl](ctan "c/numeric/complex/ctan")
(C99)(C99)(C99) | computes the complex tangent (function) |
| [atanatanfatanl](../math/atan "c/numeric/math/atan")
(C99)(C99) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/atan "cpp/numeric/complex/atan") for `atan` |
c clogf, clog, clogl clogf, clog, clogl
==================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex clogf( float complex z );
```
| (1) | (since C99) |
|
```
double complex clog( double complex z );
```
| (2) | (since C99) |
|
```
long double complex clogl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define log( z )
```
| (4) | (since C99) |
1-3) Computes the complex natural (base-*e*) logarithm of `z` with branch cut along the negative real axis.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `clogl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `clog` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `clogf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`logf`, `[log](http://en.cppreference.com/w/c/numeric/math/log)`, `logl`). If `z` is imaginary, the corresponding complex number version is called. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, the complex natural logarithm of `z` is returned, in the range of a strip in the interval [−iπ, +iπ] along the imaginary axis and mathematically unbounded along the real axis.
### Error handling and special values
Errors are reported consistent with [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic,
* The function is continuous onto the branch cut taking into account the sign of imaginary part
* `clog([conj](http://en.cppreference.com/w/c/numeric/complex/conj)(z)) == [conj](http://en.cppreference.com/w/c/numeric/complex/conj)(clog(z))`
* If `z` is `-0+0i`, the result is `-∞+πi` and `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `z` is `+0+0i`, the result is `-∞+0i` and `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `z` is `x+∞i` (for any finite x), the result is `+∞+πi/2`
* If `z` is `x+NaNi` (for any finite x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `-∞+yi` (for any finite positive y), the result is `+∞+πi`
* If `z` is `+∞+yi` (for any finite positive y), the result is `+∞+0i`
* If `z` is `-∞+∞i`, the result is `+∞+3πi/4`
* If `z` is `+∞+∞i`, the result is `+∞+πi/4`
* If `z` is `±∞+NaNi`, the result is `+∞+NaNi`
* If `z` is `NaN+yi` (for any finite y), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `NaN+∞i`, the result is `+∞+NaNi`
* If `z` is `NaN+NaNi`, the result is `NaN+NaNi`
### Notes
The natural logarithm of a complex number z with polar coordinate components (r,θ) equals ln r + i(θ+2nπ), with the principal value ln r + iθ
### Example
```
#include <stdio.h>
#include <math.h>
#include <complex.h>
int main(void)
{
double complex z = clog(I); // r = 1, θ = pi/2
printf("2*log(i) = %.1f%+fi\n", creal(2*z), cimag(2*z));
double complex z2 = clog(sqrt(2)/2 + sqrt(2)/2*I); // r = 1, θ = pi/4
printf("4*log(sqrt(2)/2+sqrt(2)i/2) = %.1f%+fi\n", creal(4*z2), cimag(4*z2));
double complex z3 = clog(-1); // r = 1, θ = pi
printf("log(-1+0i) = %.1f%+fi\n", creal(z3), cimag(z3));
double complex z4 = clog(conj(-1)); // or clog(CMPLX(-1, -0.0)) in C11
printf("log(-1-0i) (the other side of the cut) = %.1f%+fi\n", creal(z4), cimag(z4));
}
```
Output:
```
2*log(i) = 0.0+3.141593i
4*log(sqrt(2)/2+sqrt(2)i/2) = 0.0+3.141593i
log(-1+0i) = 0.0+3.141593i
log(-1-0i) (the other side of the cut) = 0.0-3.141593i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.7.2 The clog functions (p: 195)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.6.3.2 The clog functions (p: 543-544)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.7.2 The clog functions (p: 176-177)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.6.3.2 The clog functions (p: 478-479)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [cexpcexpfcexpl](cexp "c/numeric/complex/cexp")
(C99)(C99)(C99) | computes the complex base-e exponential (function) |
| [loglogflogl](../math/log "c/numeric/math/log")
(C99)(C99) | computes natural (base-*e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/log "cpp/numeric/complex/log") for `log` |
c casinf, casin, casinl casinf, casin, casinl
=====================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex casinf( float complex z );
```
| (1) | (since C99) |
|
```
double complex casin( double complex z );
```
| (2) | (since C99) |
|
```
long double complex casinl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define asin( z )
```
| (4) | (since C99) |
1-3) Computes the complex arc sine of `z` with branch cuts outside the interval [−1,+1] along the real axis.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `casinl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `casin` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `casinf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`asinf`, `[asin](http://en.cppreference.com/w/c/numeric/math/asin)`, `asinl`). If `z` is imaginary, then the macro invokes the corresponding real version of the function `[asinh](../math/asinh "c/numeric/math/asinh")`, implementing the formula asin(iy) = i asinh(y), and the return type of the macro is imaginary. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, complex arc sine of `z` is returned, in the range of a strip unbounded along the imaginary axis and in the interval [−π/2; +π/2] along the real axis.
Errors and special cases are handled as if the operation is implemented by `-I \* [casinh](http://en.cppreference.com/w/c/numeric/complex/casinh)(I\*z)`.
### Notes
Inverse sine (or arc sine) is a multivalued function and requires a branch cut on the complex plane. The branch cut is conventionally placed at the line segments (-∞,-1) and (1,∞) of the real axis.
The mathematical definition of the principal value of arc sine is asin z = -*i*ln(*i*z + √1-z2
) For any z, asin(z) = acos(-z) -
π/2 ### Example
```
#include <stdio.h>
#include <math.h>
#include <complex.h>
int main(void)
{
double complex z = casin(-2);
printf("casin(-2+0i) = %f%+fi\n", creal(z), cimag(z));
double complex z2 = casin(conj(-2)); // or CMPLX(-2, -0.0)
printf("casin(-2-0i) (the other side of the cut) = %f%+fi\n", creal(z2), cimag(z2));
// for any z, asin(z) = acos(-z) - pi/2
double pi = acos(-1);
double complex z3 = csin(cacos(conj(-2))-pi/2);
printf("csin(cacos(-2-0i)-pi/2) = %f%+fi\n", creal(z3), cimag(z3));
}
```
Output:
```
casin(-2+0i) = -1.570796+1.316958i
casin(-2-0i) (the other side of the cut) = -1.570796-1.316958i
csin(cacos(-2-0i)-pi/2) = 2.000000+0.000000i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.5.2 The casin functions (p: 190)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.5.2 The casin functions (p: 172)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [cacoscacosfcacosl](cacos "c/numeric/complex/cacos")
(C99)(C99)(C99) | computes the complex arc cosine (function) |
| [catancatanfcatanl](catan "c/numeric/complex/catan")
(C99)(C99)(C99) | computes the complex arc tangent (function) |
| [csincsinfcsinl](csin "c/numeric/complex/csin")
(C99)(C99)(C99) | computes the complex sine (function) |
| [asinasinfasinl](../math/asin "c/numeric/math/asin")
(C99)(C99) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/asin "cpp/numeric/complex/asin") for `asin` |
c ccoshf, ccosh, ccoshl ccoshf, ccosh, ccoshl
=====================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex ccoshf( float complex z );
```
| (1) | (since C99) |
|
```
double complex ccosh( double complex z );
```
| (2) | (since C99) |
|
```
long double complex ccoshl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define cosh( z )
```
| (4) | (since C99) |
1-3) Computes the complex hyperbolic cosine of `z`.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `ccoshl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `ccosh` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `ccoshf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`coshf`, `[cosh](http://en.cppreference.com/w/c/numeric/math/cosh)`, `coshl`). If `z` is imaginary, then the macro invokes the corresponding real version of the function `[cos](../math/cos "c/numeric/math/cos")`, implementing the formula cosh(iy) = cos(y), and the return type is real. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, complex hyperbolic cosine of `z` is returned.
### Error handling and special values
Errors are reported consistent with [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic,
* `ccosh([conj](http://en.cppreference.com/w/c/numeric/complex/conj)(z)) == [conj](http://en.cppreference.com/w/c/numeric/complex/conj)(ccosh(z))`
* `ccosh(z) == ccosh(-z)`
* If `z` is `+0+0i`, the result is `1+0i`
* If `z` is `+0+∞i`, the result is `NaN±0i` (the sign of the imaginary part is unspecified) and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `z` is `+0+NaNi`, the result is `NaN±0i` (the sign of the imaginary part is unspecified)
* If `z` is `x+∞i` (for any finite non-zero x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `z` is `x+NaNi` (for any finite non-zero x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `+∞+0i`, the result is `+∞+0i`
* If `z` is `+∞+yi` (for any finite non-zero y), the result is `+∞cis(y)`
* If `z` is `+∞+∞i`, the result is `±∞+NaNi` (the sign of the real part is unspecified) and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `z` is `+∞+NaN`, the result is `+∞+NaN`
* If `z` is `NaN+0i`, the result is `NaN±0i` (the sign of the imaginary part is unspecified)
* If `z` is `NaN+yi` (for any finite non-zero y), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `NaN+NaNi`, the result is `NaN+NaNi`
where cis(y) is cos(y) + i sin(y).
### Notes
Mathematical definition of hyperbolic cosine is cosh z = ez+e-z/2 Hyperbolic cosine is an entire function in the complex plane and has no branch cuts. It is periodic with respect to the imaginary component, with period 2πi.
### Example
```
#include <stdio.h>
#include <math.h>
#include <complex.h>
int main(void)
{
double complex z = ccosh(1); // behaves like real cosh along the real line
printf("cosh(1+0i) = %f%+fi (cosh(1)=%f)\n", creal(z), cimag(z), cosh(1));
double complex z2 = ccosh(I); // behaves like real cosine along the imaginary line
printf("cosh(0+1i) = %f%+fi ( cos(1)=%f)\n", creal(z2), cimag(z2), cos(1));
}
```
Output:
```
cosh(1+0i) = 1.543081+0.000000i (cosh(1)=1.543081)
cosh(0+1i) = 0.540302+0.000000i ( cos(1)=0.540302)
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.6.4 The ccosh functions (p: 193)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.6.2.4 The ccosh functions (p: 541)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.6.4 The ccosh functions (p: 175)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.6.2.4 The ccosh functions (p: 476)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [csinhcsinhfcsinhl](csinh "c/numeric/complex/csinh")
(C99)(C99)(C99) | computes the complex hyperbolic sine (function) |
| [ctanhctanhfctanhl](ctanh "c/numeric/complex/ctanh")
(C99)(C99)(C99) | computes the complex hyperbolic tangent (function) |
| [cacoshcacoshfcacoshl](cacosh "c/numeric/complex/cacosh")
(C99)(C99)(C99) | computes the complex arc hyperbolic cosine (function) |
| [coshcoshfcoshl](../math/cosh "c/numeric/math/cosh")
(C99)(C99) | computes hyperbolic cosine (\({\small\cosh{x} }\)cosh(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/cosh "cpp/numeric/complex/cosh") for `cosh` |
| programming_docs |
c cabsf, cabs, cabsl cabsf, cabs, cabsl
==================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float cabsf( float complex z );
```
| (1) | (since C99) |
|
```
double cabs( double complex z );
```
| (2) | (since C99) |
|
```
long double cabsl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define fabs( z )
```
| (4) | (since C99) |
1-3) Computes the complex absolute value (also known as norm, modulus, or magnitude) of `z`.
4) Type-generic macro: if `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)` or `long double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, `cabsl` is called. If `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)` or `float [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, `cabsf` is called. If `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)` or `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, `cabs` is called. For real and integer types, the corresponding version of `[fabs](../math/fabs "c/numeric/math/fabs")` is called. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, returns the absolute value (norm, magnitude) of `z`.
Errors and special cases are handled as if the function is implemented as `[hypot](http://en.cppreference.com/w/c/numeric/math/hypot)([creal](http://en.cppreference.com/w/c/numeric/complex/creal)(z), [cimag](http://en.cppreference.com/w/c/numeric/complex/cimag)(z))`.
### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
double complex z = 1.0 + 1.0*I;
printf("%.1f%+.1fi cartesian is rho=%f theta=%f polar\n",
creal(z), cimag(z), cabs(z), carg(z));
}
```
Output:
```
1.0+1.0i cartesian is rho=1.414214 theta=0.785398 polar
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.8.1 The cabs functions (p: 195)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.8.1 The cabs functions (p: 177)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [cargcargfcargl](carg "c/numeric/complex/carg")
(C99)(C99)(C99) | computes the phase angle of a complex number (function) |
| [abslabsllabs](../math/abs "c/numeric/math/abs")
(C99) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) |
| [fabsfabsffabsl](../math/fabs "c/numeric/math/fabs")
(C99)(C99) | computes absolute value of a floating-point value (\(\small{|x|}\)|x|) (function) |
| [hypothypotfhypotl](../math/hypot "c/numeric/math/hypot")
(C99)(C99)(C99) | computes square root of the sum of the squares of two given numbers (\(\scriptsize{\sqrt{x^2+y^2} }\)√x2+y2) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/abs "cpp/numeric/complex/abs") for `abs` |
c ctanhf, ctanh, ctanhl ctanhf, ctanh, ctanhl
=====================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex ctanhf( float complex z );
```
| (1) | (since C99) |
|
```
double complex ctanh( double complex z );
```
| (2) | (since C99) |
|
```
long double complex ctanhl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define tanh( z )
```
| (4) | (since C99) |
1-3) Computes the complex hyperbolic tangent of `z`.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `ctanhl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `ctanh` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `ctanhf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`tanhf`, `[tanh](http://en.cppreference.com/w/c/numeric/math/tanh)`, `tanhl`). If `z` is imaginary, then the macro invokes the corresponding real version of the function `[tan](../math/tan "c/numeric/math/tan")`, implementing the formula tanh(iy) = i tan(y), and the return type is imaginary. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, complex hyperbolic tangent of `z` is returned.
### Error handling and special values
Errors are reported consistent with [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic,
* `ctanh([conj](http://en.cppreference.com/w/c/numeric/complex/conj)(z)) == [conj](http://en.cppreference.com/w/c/numeric/complex/conj)(ctanh(z))`
* `ctanh(-z) == -ctanh(z)`
* If `z` is `+0+0i`, the result is `+0+0i`
* If `z` is `x+∞i` (for any[[1]](#cite_note-1) finite x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `z` is `x+NaN` (for any[[2]](#cite_note-2) finite x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `+∞+yi` (for any finite positive y), the result is `1+0i`
* If `z` is `+∞+∞i`, the result is `1±0i` (the sign of the imaginary part is unspecified)
* If `z` is `+∞+NaNi`, the result is `1±0i` (the sign of the imaginary part is unspecified)
* If `z` is `NaN+0i`, the result is `NaN+0i`
* If `z` is `NaN+yi` (for any non-zero y), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `NaN+NaNi`, the result is `NaN+NaNi`
1. per [DR471](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1892.htm#dr_471), this only holds for non-zero x. If `z` is `0+∞i`, the result should be `0+NaNi`
2. per [DR471](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1892.htm#dr_471), this only holds for non-zero x. If `z` is `0+NaNi`, the result should be `0+NaNi`
### Notes
Mathematical definition of hyperbolic tangent is tanh z = ez-e-z/ez+e-z Hyperbolic tangent is an analytical function on the complex plane and has no branch cuts. It is periodic with respect to the imaginary component, with period πi, and has poles of the first order along the imaginary line, at coordinates (0, π(1/2 + n)). However no common floating-point representation is able to represent π/2 exactly, thus there is no value of the argument for which a pole error occurs.
### Example
```
#include <stdio.h>
#include <math.h>
#include <complex.h>
int main(void)
{
double complex z = ctanh(1); // behaves like real tanh along the real line
printf("tanh(1+0i) = %f%+fi (tanh(1)=%f)\n", creal(z), cimag(z), tanh(1));
double complex z2 = ctanh(I); // behaves like tangent along the imaginary line
printf("tanh(0+1i) = %f%+fi ( tan(1)=%f)\n", creal(z2), cimag(z2), tan(1));
}
```
Output:
```
tanh(1+0i) = 0.761594+0.000000i (tanh(1)=0.761594)
tanh(0+1i) = 0.000000+1.557408i ( tan(1)=1.557408)
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.6.6 The ctanh functions (p: 194)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.6.2.6 The ctanh functions (p: 542)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.6.6 The ctanh functions (p: 176)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.6.2.6 The ctanh functions (p: 477)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [csinhcsinhfcsinhl](csinh "c/numeric/complex/csinh")
(C99)(C99)(C99) | computes the complex hyperbolic sine (function) |
| [ccoshccoshfccoshl](ccosh "c/numeric/complex/ccosh")
(C99)(C99)(C99) | computes the complex hyperbolic cosine (function) |
| [catanhcatanhfcatanhl](catanh "c/numeric/complex/catanh")
(C99)(C99)(C99) | computes the complex arc hyperbolic tangent (function) |
| [tanhtanhftanhl](../math/tanh "c/numeric/math/tanh")
(C99)(C99) | computes hyperbolic tangent (\({\small\tanh{x} }\)tanh(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/tanh "cpp/numeric/complex/tanh") for `tanh` |
c casinhf, casinh, casinhl casinhf, casinh, casinhl
========================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex casinhf( float complex z );
```
| (1) | (since C99) |
|
```
double complex casinh( double complex z );
```
| (2) | (since C99) |
|
```
long double complex casinhl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define asinh( z )
```
| (4) | (since C99) |
1-3) Computes the complex arc hyperbolic sine of `z` with branch cuts outside the interval [−i; +i] along the imaginary axis.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `casinhl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `casinh` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `casinhf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`asinhf`, `[asinh](http://en.cppreference.com/w/c/numeric/math/asinh)`, `asinhl`). If `z` is imaginary, then the macro invokes the corresponding real version of the function `[asin](../math/asin "c/numeric/math/asin")`, implementing the formula asinh(iy) = i asin(y), and the return type is imaginary. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, the complex arc hyperbolic sine of `z` is returned, in the range of a strip mathematically unbounded along the real axis and in the interval [−iπ/2; +iπ/2] along the imaginary axis.
### Error handling and special values
Errors are reported consistent with [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic,
* `casinh([conj](http://en.cppreference.com/w/c/numeric/complex/conj)(z)) == [conj](http://en.cppreference.com/w/c/numeric/complex/conj)(casinh(z))`
* `casinh(-z) == -casinh(z)`
* If `z` is `+0+0i`, the result is `+0+0i`
* If `z` is `x+∞i` (for any positive finite x), the result is `+∞+π/2`
* If `z` is `x+NaNi` (for any finite x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `+∞+yi` (for any positive finite y), the result is `+∞+0i`
* If `z` is `+∞+∞i`, the result is `+∞+iπ/4`
* If `z` is `+∞+NaNi`, the result is `+∞+NaNi`
* If `z` is `NaN+0i`, the result is `NaN+0i`
* If `z` is `NaN+yi` (for any finite nonzero y), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `NaN+∞i`, the result is `±∞+NaNi` (the sign of the real part is unspecified)
* If `z` is `NaN+NaNi`, the result is `NaN+NaNi`
### Notes
Although the C standard names this function "complex arc hyperbolic sine", the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct name is "complex inverse hyperbolic sine", and, less common, "complex area hyperbolic sine".
Inverse hyperbolic sine is a multivalued function and requires a branch cut on the complex plane. The branch cut is conventionally placed at the line segments (-*i*∞,-*i*) and (*i*,*i*∞) of the imaginary axis.
The mathematical definition of the principal value of the inverse hyperbolic sine is asinh z = ln(z + √1+z2
) For any z, asinh(z) =
asin(iz)/i ### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
double complex z = casinh(0+2*I);
printf("casinh(+0+2i) = %f%+fi\n", creal(z), cimag(z));
double complex z2 = casinh(-conj(2*I)); // or casinh(CMPLX(-0.0, 2)) in C11
printf("casinh(-0+2i) (the other side of the cut) = %f%+fi\n", creal(z2), cimag(z2));
// for any z, asinh(z) = asin(iz)/i
double complex z3 = casinh(1+2*I);
printf("casinh(1+2i) = %f%+fi\n", creal(z3), cimag(z3));
double complex z4 = casin((1+2*I)*I)/I;
printf("casin(i * (1+2i))/i = %f%+fi\n", creal(z4), cimag(z4));
}
```
Output:
```
casinh(+0+2i) = 1.316958+1.570796i
casinh(-0+2i) (the other side of the cut) = -1.316958+1.570796i
casinh(1+2i) = 1.469352+1.063440i
casin(i * (1+2i))/i = 1.469352+1.063440i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.6.2 The casinh functions (p: 192-193)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.6.2.2 The casinh functions (p: 540)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.6.2 The casinh functions (p: 174-175)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.6.2.2 The casinh functions (p: 475)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [cacoshcacoshfcacoshl](cacosh "c/numeric/complex/cacosh")
(C99)(C99)(C99) | computes the complex arc hyperbolic cosine (function) |
| [catanhcatanhfcatanhl](catanh "c/numeric/complex/catanh")
(C99)(C99)(C99) | computes the complex arc hyperbolic tangent (function) |
| [csinhcsinhfcsinhl](csinh "c/numeric/complex/csinh")
(C99)(C99)(C99) | computes the complex hyperbolic sine (function) |
| [asinhasinhfasinhl](../math/asinh "c/numeric/math/asinh")
(C99)(C99)(C99) | computes inverse hyperbolic sine (\({\small\operatorname{arsinh}{x} }\)arsinh(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/asinh "cpp/numeric/complex/asinh") for `asinh` |
c csqrtf, csqrt, csqrtl csqrtf, csqrt, csqrtl
=====================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex csqrtf( float complex z );
```
| (1) | (since C99) |
|
```
double complex csqrt( double complex z );
```
| (2) | (since C99) |
|
```
long double complex csqrtl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define sqrt( z )
```
| (4) | (since C99) |
1-3) Computes the complex square root of `z` with branch cut along the negative real axis.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `csqrtl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `csqrt` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `csqrtf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`sqrtf`, `[sqrt](http://en.cppreference.com/w/c/numeric/math/sqrt)`, `sqrtl`). If `z` is imaginary, the corresponding complex number version is called. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, returns the square root of `z`, in the range of the right half-plane, including the imaginary axis ([0; +∞) along the real axis and (−∞; +∞) along the imaginary axis.).
### Error handling and special values
Errors are reported consistent with [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic,
* The function is continuous onto the branch cut taking into account the sign of imaginary part
* `csqrt([conj](http://en.cppreference.com/w/c/numeric/complex/conj)(z)) == [conj](http://en.cppreference.com/w/c/numeric/complex/conj)(csqrt(z))`
* If `z` is `±0+0i`, the result is `+0+0i`
* If `z` is `x+∞i`, the result is `+∞+∞i` even if x is NaN
* If `z` is `x+NaNi`, the result is `NaN+NaNi` (unless x is ±∞) and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `-∞+yi`, the result is `+0+∞i` for finite positive y
* If `z` is `+∞+yi`, the result is `+∞+0i)` for finite positive y
* If `z` is `-∞+NaNi`, the result is `NaN±∞i` (sign of imaginary part unspecified)
* If `z` is `+∞+NaNi`, the result is `+∞+NaNi`
* If `z` is `NaN+yi`, the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `NaN+NaNi`, the result is `NaN+NaNi`
### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
double complex z1 = csqrt(-4);
printf("Square root of -4 is %.1f%+.1fi\n", creal(z1), cimag(z1));
double complex z2 = csqrt(conj(-4)); // or, in C11, CMPLX(-4, -0.0)
printf("Square root of -4-0i, the other side of the cut, is "
"%.1f%+.1fi\n", creal(z2), cimag(z2));
}
```
Output:
```
Square root of -4 is 0.0+2.0i
Square root of -4-0i, the other side of the cut, is 0.0-2.0i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.8.3 The csqrt functions (p: 196)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.6.4.2 The csqrt functions (p: 544)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.8.3 The csqrt functions (p: 178)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.6.4.2 The csqrt functions (p: 479)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [cpowcpowfcpowl](cpow "c/numeric/complex/cpow")
(C99)(C99)(C99) | computes the complex power function (function) |
| [sqrtsqrtfsqrtl](../math/sqrt "c/numeric/math/sqrt")
(C99)(C99) | computes square root (\(\small{\sqrt{x} }\)√x) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/sqrt "cpp/numeric/complex/sqrt") for `sqrt` |
c csinf, csin, csinl csinf, csin, csinl
==================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex csinf( float complex z );
```
| (1) | (since C99) |
|
```
double complex csin( double complex z );
```
| (2) | (since C99) |
|
```
long double complex csinl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define sin( z )
```
| (4) | (since C99) |
1-3) Computes the complex sine of `z`.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `csinl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `csin` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `csinf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`sinf`, `[sin](http://en.cppreference.com/w/c/numeric/math/sin)`, `sinl`). If `z` is imaginary, then the macro invokes the corresponding real version of the function `[sinh](../math/sinh "c/numeric/math/sinh")`, implementing the formula sin(iy) = i ∙ sinh(y), and the return type of the macro is imaginary. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, the complex sine of `z`.
Errors and special cases are handled as if the operation is implemented by `-I \* [csinh](http://en.cppreference.com/w/c/numeric/complex/csinh)(I\*z)`.
### Notes
The sine is an entire function on the complex plane, and has no branch cuts. Mathematical definition of the sine is sin z =
eiz-e-iz/2i ### Example
```
#include <stdio.h>
#include <math.h>
#include <complex.h>
int main(void)
{
double complex z = csin(1); // behaves like real sine along the real line
printf("sin(1+0i) = %f%+fi ( sin(1)=%f)\n", creal(z), cimag(z), sin(1));
double complex z2 = csin(I); // behaves like sinh along the imaginary line
printf("sin(0+1i) = %f%+fi (sinh(1)=%f)\n", creal(z2), cimag(z2), sinh(1));
}
```
Output:
```
sin(1+0i) = 0.841471+0.000000i ( sin(1)=0.841471)
sin(0+1i) = 0.000000+1.175201i (sinh(1)=1.175201)
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.3.5.5 The csin functions (p: 138-139)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ G.7 Type-generic math <tgmath.h> (p: 397)
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.5.5 The csin functions (p: 191-192)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.5.5 The csin functions (p: 173)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [ccosccosfccosl](ccos "c/numeric/complex/ccos")
(C99)(C99)(C99) | computes the complex cosine (function) |
| [ctanctanfctanl](ctan "c/numeric/complex/ctan")
(C99)(C99)(C99) | computes the complex tangent (function) |
| [casincasinfcasinl](casin "c/numeric/complex/casin")
(C99)(C99)(C99) | computes the complex arc sine (function) |
| [sinsinfsinl](../math/sin "c/numeric/math/sin")
(C99)(C99) | computes sine (\({\small\sin{x} }\)sin(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/sin "cpp/numeric/complex/sin") for `sin` |
| programming_docs |
c ctanf, ctan, ctanl ctanf, ctan, ctanl
==================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex ctanf( float complex z );
```
| (1) | (since C99) |
|
```
double complex ctan( double complex z );
```
| (2) | (since C99) |
|
```
long double complex ctanl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define tan( z )
```
| (4) | (since C99) |
1-3) Computes the complex tangent of `z`.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `ctanl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `ctan` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `ctanf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`tanf`, `[tan](http://en.cppreference.com/w/c/numeric/math/tan)`, `tanl`). If `z` is imaginary, then the macro invokes the corresponding real version of the function `[tanh](../math/tanh "c/numeric/math/tanh")`, implementing the formula tan(iy) = i tanh(y), and the return type is imaginary. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, the complex tangent of `z` is returned.
Errors and special cases are handled as if the operation is implemented by `-i \* [ctanh](http://en.cppreference.com/w/c/numeric/complex/ctanh)(i\*z)`, where `i` is the imaginary unit.
### Notes
Tangent is an analytical function on the complex plain and has no branch cuts. It is periodic with respect to the real component, with period πi, and has poles of the first order along the real line, at coordinates (π(1/2 + n), 0). However no common floating-point representation is able to represent π/2 exactly, thus there is no value of the argument for which a pole error occurs. Mathematical definition of the tangent is tan z =
i(e-iz-eiz)/e-iz+eiz ### Example
```
#include <stdio.h>
#include <math.h>
#include <complex.h>
int main(void)
{
double complex z = ctan(1); // behaves like real tangent along the real line
printf("tan(1+0i) = %f%+fi ( tan(1)=%f)\n", creal(z), cimag(z), tan(1));
double complex z2 = ctan(I); // behaves like tanh along the imaginary line
printf("tan(0+1i) = %f%+fi (tanh(1)=%f)\n", creal(z2), cimag(z2), tanh(1));
}
```
Output:
```
tan(1+0i) = 1.557408+0.000000i ( tan(1)=1.557408)
tan(0+1i) = 0.000000+0.761594i (tanh(1)=0.761594)
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.5.6 The ctan functions (p: 192)
+ 7.25 Type-generic complex <tgmath.h> (p: 373-375)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.5.6 The ctan functions (p: 174)
+ 7.22 Type-generic complex <tgcomplex.h> (p: 335-337)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [ctanhctanhfctanhl](ctanh "c/numeric/complex/ctanh")
(C99)(C99)(C99) | computes the complex hyperbolic tangent (function) |
| [csincsinfcsinl](csin "c/numeric/complex/csin")
(C99)(C99)(C99) | computes the complex sine (function) |
| [ccosccosfccosl](ccos "c/numeric/complex/ccos")
(C99)(C99)(C99) | computes the complex cosine (function) |
| [catancatanfcatanl](catan "c/numeric/complex/catan")
(C99)(C99)(C99) | computes the complex arc tangent (function) |
| [tantanftanl](../math/tan "c/numeric/math/tan")
(C99)(C99) | computes tangent (\({\small\tan{x} }\)tan(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/tan "cpp/numeric/complex/tan") for `tan` |
c I I
=
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
#define I /* unspecified */
```
| | (since C99) |
The `I` macro expands to either `[\_Complex\_I](complex_i "c/numeric/complex/Complex I")` or `[\_Imaginary\_I](imaginary_i "c/numeric/complex/Imaginary I")`. If the implementation does not support imaginary types, then the macro always expands to `[\_Complex\_I](complex_i "c/numeric/complex/Complex I")`.
A program may undefine and perhaps then redefine the macro `I`.
### Notes
The macro is not named `i`, which is the name of the imaginary unit in mathematics, because the name `i` was already used in many C programs, e.g. as a loop counter variable.
The macro `I` is often used to form complex numbers, with expressions such as `x + y*I`. If `I` is defined as `[\_Complex\_I](complex_i "c/numeric/complex/Complex I")`, then such expression may create a value with imaginary component `+0.0` even when `y` is `-0.0`, which is significant for complex number functions with branch cuts. The macro `[CMPLX](cmplx "c/numeric/complex/CMPLX")` provides a way to construct a complex number precisely.
GCC provides a non-portable extension that allows imaginary constants to be specified with the suffix `i` on integer literals: `1.0fi`, `1.0i`, and `1.0li` are imaginary units in GNU C. A similar approach is part of standard C++ as of C++14 (`1.0if`, `1.0i`, and `1.0il` are the imaginary units in C++).
### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
printf("I = %.1f%+.1fi\n", creal(I), cimag(I));
double complex z1 = I * I; // imaginary unit squared
printf("I * I = %.1f%+.1fi\n", creal(z1), cimag(z1));
double complex z = 1.0 + 2.0*I; // usual way to form a complex number pre-C11
printf("z = %.1f%+.1fi\n", creal(z), cimag(z));
}
```
Output:
```
I = 0.0+1.0i
I * I = -1.0+0.0i
z = 1.0+2.0i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.1/6 I (p: 188)
+ G.6/1 I (p: 537)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.1/4 I (p: 170)
+ G.6/1 I (p: 472)
### See also
| | |
| --- | --- |
| [\_Imaginary\_I](imaginary_i "c/numeric/complex/Imaginary I")
(C99) | the imaginary unit constant i (macro constant) |
| [\_Complex\_I](complex_i "c/numeric/complex/Complex I")
(C99) | the complex unit constant i (macro constant) |
| [CMPLXCMPLXFCMPLXL](cmplx "c/numeric/complex/CMPLX")
(C11)(C11)(C11) | constructs a complex number from real and imaginary parts (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/operator%22%22i "cpp/numeric/complex/operator\"\"i") for `operator""i` |
c cargf, carg, cargl cargf, carg, cargl
==================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float cargf( float complex z );
```
| (1) | (since C99) |
|
```
double carg( double complex z );
```
| (2) | (since C99) |
|
```
long double cargl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define carg( z )
```
| (4) | (since C99) |
1-3) Computes the argument (also called phase angle) of `z`, with a branch cut along the negative real axis.
4) Type-generic macro: if `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `long double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, or `long double`, `cargl` is called. If `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `float [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, or `float`, `cargf` is called. If `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, `double`, or any integer type, `carg` is called. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, returns the phase angle of `z` in the interval [−π; π].
Errors and special cases are handled as if the function is implemented as `[atan2](http://en.cppreference.com/w/c/numeric/math/atan2)([cimag](http://en.cppreference.com/w/c/numeric/complex/cimag)(z), [creal](http://en.cppreference.com/w/c/numeric/complex/creal)(z))`.
### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
double complex z1 = 1.0+0.0*I;
printf("phase angle of %.1f%+.1fi is %f\n", creal(z1), cimag(z1), carg(z1));
double complex z2 = 0.0+1.0*I;
printf("phase angle of %.1f%+.1fi is %f\n", creal(z2), cimag(z2), carg(z2));
double complex z3 = -1.0+0.0*I;
printf("phase angle of %.1f%+.1fi is %f\n", creal(z3), cimag(z3), carg(z3));
double complex z4 = conj(z3); // or CMPLX(-1, -0.0)
printf("phase angle of %.1f%+.1fi (the other side of the cut) is %f\n",
creal(z4), cimag(z4), carg(z4));
}
```
Output:
```
phase angle of 1.0+0.0i is 0.000000
phase angle of 0.0+1.0i is 1.570796
phase angle of -1.0+0.0i is 3.141593
phase angle of -1.0-0.0i (the other side of the cut) is -3.141593
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.9.1 The carg functions (p: 196)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.9.1 The carg functions (p: 178)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [cabscabsfcabsl](cabs "c/numeric/complex/cabs")
(C99)(C99)(C99) | computes the magnitude of a complex number (function) |
| [atan2atan2fatan2l](../math/atan2 "c/numeric/math/atan2")
(C99)(C99) | computes arc tangent, using signs to determine quadrants (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/arg "cpp/numeric/complex/arg") for `arg` |
c catanhf, catanh, catanhl catanhf, catanh, catanhl
========================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex catanhf( float complex z );
```
| (1) | (since C99) |
|
```
double complex catanh( double complex z );
```
| (2) | (since C99) |
|
```
long double complex catanhl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define atanh( z )
```
| (4) | (since C99) |
1-3) Computes the complex arc hyperbolic tangent of `z` with branch cuts outside the interval [−1; +1] along the real axis.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `catanhl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `catanh` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `catanhf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`atanhf`, `[atanh](http://en.cppreference.com/w/c/numeric/math/atanh)`, `atanhl`). If `z` is imaginary, then the macro invokes the corresponding real version of `[atan](http://en.cppreference.com/w/c/numeric/math/atan)`, implementing the formula atanh(iy) = i atan(y), and the return type is imaginary. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, the complex arc hyperbolic tangent of `z` is returned, in the range of a half-strip mathematically unbounded along the real axis and in the interval [−iπ/2; +iπ/2] along the imaginary axis.
### Error handling and special values
Errors are reported consistent with [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic,
* `catanh([conj](http://en.cppreference.com/w/c/numeric/complex/conj)(z)) == [conj](http://en.cppreference.com/w/c/numeric/complex/conj)(catanh(z))`
* `catanh(-z) == -catanh(z)`
* If `z` is `+0+0i`, the result is `+0+0i`
* If `z` is `+0+NaNi`, the result is `+0+NaNi`
* If `z` is `+1+0i`, the result is `+∞+0i` and `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `z` is `x+∞i` (for any finite positive x), the result is `+0+iπ/2`
* If `z` is `x+NaNi` (for any finite nonzero x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `+∞+yi` (for any finite positive y), the result is `+0+iπ/2`
* If `z` is `+∞+∞i`, the result is `+0+iπ/2`
* If `z` is `+∞+NaNi`, the result is `+0+NaNi`
* If `z` is `NaN+yi` (for any finite y), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `NaN+∞i`, the result is `±0+iπ/2` (the sign of the real part is unspecified)
* If `z` is `NaN+NaNi`, the result is `NaN+NaNi`
### Notes
Although the C standard names this function "complex arc hyperbolic tangent", the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct name is "complex inverse hyperbolic tangent", and, less common, "complex area hyperbolic tangent".
Inverse hyperbolic tangent is a multivalued function and requires a branch cut on the complex plane. The branch cut is conventionally placed at the line segmentd (-∞,-1] and [+1,+∞) of the real axis. The mathematical definition of the principal value of the inverse hyperbolic tangent is atanh z =
ln(1+z)-ln(z-1)/2.
For any z, atanh(z) =
atan(iz)/i ### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
double complex z = catanh(2);
printf("catanh(+2+0i) = %f%+fi\n", creal(z), cimag(z));
double complex z2 = catanh(conj(2)); // or catanh(CMPLX(2, -0.0)) in C11
printf("catanh(+2-0i) (the other side of the cut) = %f%+fi\n", creal(z2), cimag(z2));
// for any z, atanh(z) = atan(iz)/i
double complex z3 = catanh(1+2*I);
printf("catanh(1+2i) = %f%+fi\n", creal(z3), cimag(z3));
double complex z4 = catan((1+2*I)*I)/I;
printf("catan(i * (1+2i))/i = %f%+fi\n", creal(z4), cimag(z4));
}
```
Output:
```
catanh(+2+0i) = 0.549306+1.570796i
catanh(+2-0i) (the other side of the cut) = 0.549306-1.570796i
catanh(1+2i) = 0.173287+1.178097i
catan(i * (1+2i))/i = 0.173287+1.178097i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.6.3 The catanh functions (p: 193)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.6.2.3 The catanh functions (p: 540-541)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.6.3 The catanh functions (p: 175)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.6.2.3 The catanh functions (p: 475-476)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [casinhcasinhfcasinhl](casinh "c/numeric/complex/casinh")
(C99)(C99)(C99) | computes the complex arc hyperbolic sine (function) |
| [cacoshcacoshfcacoshl](cacosh "c/numeric/complex/cacosh")
(C99)(C99)(C99) | computes the complex arc hyperbolic cosine (function) |
| [ctanhctanhfctanhl](ctanh "c/numeric/complex/ctanh")
(C99)(C99)(C99) | computes the complex hyperbolic tangent (function) |
| [atanhatanhfatanhl](../math/atanh "c/numeric/math/atanh")
(C99)(C99)(C99) | computes inverse hyperbolic tangent (\({\small\operatorname{artanh}{x} }\)artanh(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/atanh "cpp/numeric/complex/atanh") for `atanh` |
c imaginary imaginary
=========
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
#define imaginary _Imaginary
```
| | (since C99) |
This macro expands to the keyword [`_Imaginary`](../../keyword/_imaginary "c/keyword/ Imaginary").
This is a convenience macro that makes it possible to use `float imaginary`, `double imaginary`, and `long double imaginary` as an alternative way to write the three pure imaginary C types `float _Imaginary`, `double _Imaginary`, and `long double _Imaginary`.
As with any pure imaginary number support in C, this macro is only defined if the imaginary numbers are supported.
| | |
| --- | --- |
| A compiler that defines `__STDC_IEC_559_COMPLEX__` is not required to support imaginary numbers. POSIX recommends checking if the macro `[\_Imaginary\_I](http://en.cppreference.com/w/c/numeric/complex/Imaginary_I)` is defined to identify imaginary number support. | (since C99)(until C11) |
| Imaginary numbers are supported if `__STDC_IEC_559_COMPLEX__` is defined. | (since C11) |
### Notes
Programs are allowed to undefine and perhaps redefine the `imaginary` macro.
### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
double imaginary i = -2.0*I; // pure imaginary
double f = 1.0; // pure real
double complex z = f + i; // complex number
printf("z = %.1f%+.1fi\n", creal(z), cimag(z));
}
```
Output:
```
z = 1.0-2.0i
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.3.1/5 imaginary (p: 136)
+ G.6/1 imaginary (p: 391-392)
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.1/5 imaginary (p: 188)
+ G.6/1 imaginary (p: 537)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.1/3 imaginary (p: 170)
+ G.6/1 imaginary (p: 472)
### See also
| | |
| --- | --- |
| [complex](complex "c/numeric/complex/complex")
(C99) | complex type macro (keyword macro) |
c csinhf, csinh, csinhl csinhf, csinh, csinhl
=====================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex csinhf( float complex z );
```
| (1) | (since C99) |
|
```
double complex csinh( double complex z );
```
| (2) | (since C99) |
|
```
long double complex csinhl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define sinh( z )
```
| (4) | (since C99) |
1-3) Computes the complex hyperbolic sine of `z`.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `csinhl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `csinh` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `csinhf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`sinhf`, `[sinh](http://en.cppreference.com/w/c/numeric/math/sinh)`, `sinhl`). If `z` is imaginary, then the macro invokes the corresponding real version of the function `[sin](../math/sin "c/numeric/math/sin")`, implementing the formula sinh(iy) = i sin(y), and the return type is imaginary. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, complex hyperbolic sine of `z` is returned.
### Error handling and special values
Errors are reported consistent with [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic,
* `csinh([conj](http://en.cppreference.com/w/c/numeric/complex/conj)(z)) == [conj](http://en.cppreference.com/w/c/numeric/complex/conj)(csinh(z))`
* `csinh(z) == -csinh(-z)`
* If `z` is `+0+0i`, the result is `+0+0i`
* If `z` is `+0+∞i`, the result is `±0+NaNi` (the sign of the real part is unspecified) and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `z` is `+0+NaNi`, the result is `±0+NaNi`
* If `z` is `x+∞i` (for any positive finite x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `z` is `x+NaNi` (for any positive finite x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `+∞+0i`, the result is `+∞+0i`
* If `z` is `+∞+yi` (for any positive finite y), the result is `+∞cis(y)`
* If `z` is `+∞+∞i`, the result is `±∞+NaNi` (the sign of the real part is unspecified) and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `z` is `+∞+NaNi`, the result is `±∞+NaNi` (the sign of the real part is unspecified)
* If `z` is `NaN+0i`, the result is `NaN+0i`
* If `z` is `NaN+yi` (for any finite nonzero y), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `NaN+NaNi`, the result is `NaN+NaNi`
where cis(y) is cos(y) + i sin(y).
### Notes
Mathematical definition of hyperbolic sine is sinh z = ez-e-z/2 Hyperbolic sine is an entire function in the complex plane and has no branch cuts. It is periodic with respect to the imaginary component, with period 2πi.
### Example
```
#include <stdio.h>
#include <math.h>
#include <complex.h>
int main(void)
{
double complex z = csinh(1); // behaves like real sinh along the real line
printf("sinh(1+0i) = %f%+fi (sinh(1)=%f)\n", creal(z), cimag(z), sinh(1));
double complex z2 = csinh(I); // behaves like sine along the imaginary line
printf("sinh(0+1i) = %f%+fi ( sin(1)=%f)\n", creal(z2), cimag(z2), sin(1));
}
```
Output:
```
sinh(1+0i) = 1.175201+0.000000i (sinh(1)=1.175201)
sinh(0+1i) = 0.000000+0.841471i ( sin(1)=0.841471)
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.6.5 The csinh functions (p: 194)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.6.2.5 The csinh functions (p: 541-542)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.6.5 The csinh functions (p: 175-176)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.6.2.5 The csinh functions (p: 476-477)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [ccoshccoshfccoshl](ccosh "c/numeric/complex/ccosh")
(C99)(C99)(C99) | computes the complex hyperbolic cosine (function) |
| [ctanhctanhfctanhl](ctanh "c/numeric/complex/ctanh")
(C99)(C99)(C99) | computes the complex hyperbolic tangent (function) |
| [casinhcasinhfcasinhl](casinh "c/numeric/complex/casinh")
(C99)(C99)(C99) | computes the complex arc hyperbolic sine (function) |
| [sinhsinhfsinhl](../math/sinh "c/numeric/math/sinh")
(C99)(C99) | computes hyperbolic sine (\({\small\sinh{x} }\)sinh(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/sinh "cpp/numeric/complex/sinh") for `sinh` |
| programming_docs |
c crealf, creal, creall crealf, creal, creall
=====================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float crealf( float complex z );
```
| (1) | (since C99) |
|
```
double creal( double complex z );
```
| (2) | (since C99) |
|
```
long double creall( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define creal( z )
```
| (4) | (since C99) |
1-3) Returns the real part of `z`.
4) Type-generic macro: if `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `long double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, or `long double`, `creall` is called. If `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `float [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, or `float`, `crealf` is called. If `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, `double`, or any integer type, `creal` is called. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
The real part of `z`.
This function is fully specified for all possible inputs and is not subject to any errors described in [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling").
### Notes
For any complex variable `z`, `z == creal(z) + I\*[cimag](http://en.cppreference.com/w/c/numeric/complex/cimag)(z)`.
### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
double complex z = 1.0 + 2.0*I;
printf("%f%+fi\n", creal(z), cimag(z));
}
```
Output:
```
1.000000+2.000000i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.9.6 The creal functions (p: 198-199)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.9.5 The creal functions (p: 180)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [cimagcimagfcimagl](cimag "c/numeric/complex/cimag")
(C99)(C99)(C99) | computes the imaginary part a complex number (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/real2 "cpp/numeric/complex/real2") for `real` |
c ccosf, ccos, ccosl ccosf, ccos, ccosl
==================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex ccosf( float complex z );
```
| (1) | (since C99) |
|
```
double complex ccos( double complex z );
```
| (2) | (since C99) |
|
```
long double complex ccosl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define cos( z )
```
| (4) | (since C99) |
1-3) Computes the complex cosine of `z`.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `ccosl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `ccos` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `ccosf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`cosf`, `[cos](http://en.cppreference.com/w/c/numeric/math/cos)`, `cosl`). If `z` is imaginary, then the macro invokes the corresponding real version of the function `[cosh](../math/cosh "c/numeric/math/cosh")`, implementing the formula cos(iy) = cosh(y), and the return type is real. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, the complex cosine of `z` is returned.
Errors and special cases are handled as if the operation is implemented by `[ccosh](http://en.cppreference.com/w/c/numeric/complex/ccosh)(I\*z)`.
### Notes
The cosine is an entire function on the complex plane, and has no branch cuts. Mathematical definition of the cosine is cos z =
eiz+e-iz/2 ### Example
```
#include <stdio.h>
#include <math.h>
#include <complex.h>
int main(void)
{
double complex z = ccos(1); // behaves like real cosine along the real line
printf("cos(1+0i) = %f%+fi ( cos(1)=%f)\n", creal(z), cimag(z), cos(1));
double complex z2 = ccos(I); // behaves like real cosh along the imaginary line
printf("cos(0+1i) = %f%+fi (cosh(1)=%f)\n", creal(z2), cimag(z2), cosh(1));
}
```
Output:
```
cos(1+0i) = 0.540302-0.000000i ( cos(1)=0.540302)
cos(0+1i) = 1.543081-0.000000i (cosh(1)=1.543081)
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.5.4 The ccos functions (p: 191)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.5.4 The ccos functions (p: 173)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [csincsinfcsinl](csin "c/numeric/complex/csin")
(C99)(C99)(C99) | computes the complex sine (function) |
| [ctanctanfctanl](ctan "c/numeric/complex/ctan")
(C99)(C99)(C99) | computes the complex tangent (function) |
| [cacoscacosfcacosl](cacos "c/numeric/complex/cacos")
(C99)(C99)(C99) | computes the complex arc cosine (function) |
| [coscosfcosl](../math/cos "c/numeric/math/cos")
(C99)(C99) | computes cosine (\({\small\cos{x} }\)cos(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/cos "cpp/numeric/complex/cos") for `cos` |
c cprojf, cproj, cprojl cprojf, cproj, cprojl
=====================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex cprojf( float complex z );
```
| (1) | (since C99) |
|
```
double complex cproj( double complex z );
```
| (2) | (since C99) |
|
```
long double complex cprojl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define cproj( z )
```
| (4) | (since C99) |
1-3) Computes the projection of `z` on the Riemann sphere.
4) Type-generic macro: if `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `long double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, or `long double`, `cprojl` is called. If `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `float [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, or `float`, `cprojf` is called. If `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, `double`, or any integer type, `cproj` is called. For most `z`, `cproj(z)==z`, but all complex infinities, even the numbers where one component is infinite and the other is NaN, become positive real infinity, `INFINITY+0.0*I` or `INFINITY-0.0*I`. The sign of the imaginary (zero) component is the sign of `[cimag](http://en.cppreference.com/w/c/numeric/complex/cimag)(z)`.
### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
The projection of `z` on the Riemann sphere.
This function is fully specified for all possible inputs and is not subject to any errors described in [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling").
### Notes
The `cproj` function helps model the Riemann sphere by mapping all infinities to one (give or take the sign of the imaginary zero), and should be used just before any operation, especially comparisons, that might give spurious results for any of the other infinities.
### Example
```
#include <stdio.h>
#include <complex.h>
#include <math.h>
int main(void)
{
double complex z1 = cproj(1 + 2*I);
printf("cproj(1+2i) = %.1f%+.1fi\n", creal(z1),cimag(z1));
double complex z2 = cproj(INFINITY+2.0*I);
printf("cproj(Inf+2i) = %.1f%+.1fi\n", creal(z2),cimag(z2));
double complex z3 = cproj(INFINITY-2.0*I);
printf("cproj(Inf-2i) = %.1f%+.1fi\n", creal(z3),cimag(z3));
}
```
Output:
```
cproj(1+2i) = 1.0+2.0i
cproj(Inf+2i) = inf+0.0i
cproj(Inf-2i) = inf-0.0i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.9.5 The cproj functions (p: 198)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.9.4 The cproj functions (p: 179)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/proj "cpp/numeric/complex/proj") for `proj` |
c _Imaginary_I \_Imaginary\_I
==============
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
#define _Imaginary_I /* unspecified */
```
| | (since C99) |
The `_Imaginary_I` macro expands to a value of type `const float _Imaginary` with the value of the imaginary unit.
As with any pure imaginary number support in C, this macro is only defined if the imaginary numbers are supported.
| | |
| --- | --- |
| A compiler that defines `__STDC_IEC_559_COMPLEX__` is not required to support imaginary numbers. POSIX recommends checking if the macro `_Imaginary_I` is defined to identify imaginary number support. | (since C99)(until C11) |
| Imaginary numbers are supported if `__STDC_IEC_559_COMPLEX__` is defined. | (since C11) |
### Notes
This macro allows for the precise way to assemble a complex number from its real and imaginary components, e.g. with `(double [complex](http://en.cppreference.com/w/c/numeric/complex/complex))((double)x + _Imaginary_I \* (double)y)`. This pattern was standardized in C11 as the macro `[CMPLX](http://en.cppreference.com/w/c/numeric/complex/CMPLX)`. Note that if `[\_Complex\_I](http://en.cppreference.com/w/c/numeric/complex/Complex_I)` is used instead, this expression is allowed to convert negative zero to positive zero in the imaginary position.
### Example
```
#include <stdio.h>
#include <complex.h>
#include <math.h>
int main(void)
{
double complex z1 = 0.0 + INFINITY * _Imaginary_I;
printf("z1 = %.1f%+.1fi\n", creal(z1), cimag(z1));
double complex z2 = 0.0 + INFINITY * _Complex_I;
printf("z2 = %.1f%+.1fi\n", creal(z2), cimag(z2));
}
```
Output:
```
z1 = 0.0+Infi
z2 = NaN+Infi
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.1/5 \_Imaginary\_I (p: 188)
+ G.6/1 \_Imaginary\_I (p: 537)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.1/3 \_Imaginary\_I (p: 170)
+ G.6/1 \_Imaginary\_I (p: 472)
### See also
| | |
| --- | --- |
| [\_Complex\_I](complex_i "c/numeric/complex/Complex I")
(C99) | the complex unit constant i (macro constant) |
| [I](i "c/numeric/complex/I")
(C99) | the complex or imaginary unit constant i (macro constant) |
c cexpf, cexp, cexpl cexpf, cexp, cexpl
==================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex cexpf( float complex z );
```
| (1) | (since C99) |
|
```
double complex cexp( double complex z );
```
| (2) | (since C99) |
|
```
long double complex cexpl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define exp( z )
```
| (4) | (since C99) |
1-3) Computes the complex base-*e* exponential of `z`.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `cexpl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `cexp` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `cexpf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`expf`, `[exp](http://en.cppreference.com/w/c/numeric/math/exp)`, `expl`). If `z` is imaginary, the corresponding complex argument version is called. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, *e* raised to the power of `z`, ez
is returned.
### Error handling and special values
Errors are reported consistent with [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic,
* `cexp([conj](http://en.cppreference.com/w/c/numeric/complex/conj)(z)) == [conj](http://en.cppreference.com/w/c/numeric/complex/conj)(cexp(z))`
* If `z` is `±0+0i`, the result is `1+0i`
* If `z` is `x+∞i` (for any finite x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* If `z` is `x+NaNi` (for any finite x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised.
* If `z` is `+∞+0i`, the result is `+∞+0i`
* If `z` is `-∞+yi` (for any finite y), the result is `+0cis(y)`
* If `z` is `+∞+yi` (for any finite nonzero y), the result is `+∞cis(y)`
* If `z` is `-∞+∞i`, the result is `±0±0i` (signs are unspecified)
* If `z` is `+∞+∞i`, the result is `±∞+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised (the sign of the real part is unspecified)
* If `z` is `-∞+NaNi`, the result is `±0±0i` (signs are unspecified)
* If `z` is `+∞+NaNi`, the result is `±∞+NaNi` (the sign of the real part is unspecified)
* If `z` is `NaN+0i`, the result is `NaN+0i`
* If `z` is `NaN+yi` (for any nonzero y), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `NaN+NaNi`, the result is `NaN+NaNi`
where cis(y) is cos(y) + i sin(y).
### Notes
The complex exponential function ez
for z = x+iy equals to ex
cis(y), or, ex
(cos(y) + i sin(y)).
The exponential function is an *entire function* in the complex plane and has no branch cuts.
### Example
```
#include <stdio.h>
#include <math.h>
#include <complex.h>
int main(void)
{
double PI = acos(-1);
double complex z = cexp(I * PI); // Euler's formula
printf("exp(i*pi) = %.1f%+.1fi\n", creal(z), cimag(z));
}
```
Output:
```
exp(i*pi) = -1.0+0.0i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.7.1 The cexp functions (p: 194)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.6.3.1 The cexp functions (p: 543)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.7.1 The cexp functions (p: 176)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.6.3.1 The cexp functions (p: 478)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [clogclogfclogl](clog "c/numeric/complex/clog")
(C99)(C99)(C99) | computes the complex natural logarithm (function) |
| [expexpfexpl](../math/exp "c/numeric/math/exp")
(C99)(C99) | computes *e* raised to the given power (\({\small e^x}\)ex) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/exp "cpp/numeric/complex/exp") for `exp` |
c cpowf, cpow, cpowl cpowf, cpow, cpowl
==================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex cpowf( float complex x, float complex y );
```
| (1) | (since C99) |
|
```
double complex cpow( double complex x, double complex y );
```
| (2) | (since C99) |
|
```
long double complex cpowl( long double complex x, long double complex y );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define pow( x, y )
```
| (4) | (since C99) |
1-3) Computes the complex power function xy
, with branch cut for the first parameter along the negative real axis.
4) Type-generic macro: If any argument has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `cpowl` is called. if any argument has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `cpow` is called, if any argument has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `cpowf` is called. If the arguments are real or integer, then the macro invokes the corresponding real function (`powf`, `[pow](http://en.cppreference.com/w/c/numeric/math/pow)`, `powl`). If any argument is imaginary, the corresponding complex number version is called. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | complex argument |
### Return value
If no errors occur, the complex power xy
, is returned.
Errors and special cases are handled as if the operation is implemented by `[cexp](http://en.cppreference.com/w/c/numeric/complex/cexp)(y\*[clog](http://en.cppreference.com/w/c/numeric/complex/clog)(x))`, except that the implementation is allowed to treat special cases more carefully.
### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
double complex z = cpow(1.0+2.0*I, 2);
printf("(1+2i)^2 = %.1f%+.1fi\n", creal(z), cimag(z));
double complex z2 = cpow(-1, 0.5);
printf("(-1+0i)^0.5 = %.1f%+.1fi\n", creal(z2), cimag(z2));
double complex z3 = cpow(conj(-1), 0.5); // other side of the cut
printf("(-1-0i)^0.5 = %.1f%+.1fi\n", creal(z3), cimag(z3));
double complex z4 = cpow(I, I); // i^i = exp(-pi/2)
printf("i^i = %f%+fi\n", creal(z4), cimag(z4));
}
```
Output:
```
(1+2i)^2 = -3.0+4.0i
(-1+0i)^0.5 = 0.0+1.0i
(-1-0i)^0.5 = 0.0-1.0i
i^i = 0.207880+0.000000i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.8.2 The cpow functions (p: 195-196)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.6.4.1 The cpow functions (p: 544)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.8.2 The cpow functions (p: 177)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.6.4.1 The cpow functions (p: 479)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [csqrtcsqrtfcsqrtl](csqrt "c/numeric/complex/csqrt")
(C99)(C99)(C99) | computes the complex square root (function) |
| [powpowfpowl](../math/pow "c/numeric/math/pow")
(C99)(C99) | computes a number raised to the given power (\(\small{x^y}\)xy) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/pow "cpp/numeric/complex/pow") for `pow` |
c complex complex
=======
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
#define complex _Complex
```
| | (since C99) |
This macro expands to a type specifier used to identify [complex types](../../language/arithmetic_types#Complex_floating_types "c/language/arithmetic types").
A program may undefine and perhaps then redefine the `complex` macro.
### Example
```
#include <stdio.h>
#include <complex.h>
#include <math.h>
void print_complex(const char* note, complex z)
{
printf("%s %f + %f*i\n", note, creal(z), cimag(z));
}
int main(void)
{
double complex z = -1.0 + 2.0*I;
print_complex("z =", z);
print_complex("z^2 =", z * z);
double complex z2 = ccos(2.0 * carg(z)) + csin(2.0 * carg(z))*I;
print_complex("z^2 =", cabs(z) * cabs(z) * z2);
}
```
Output:
```
z = -1.000000 + 2.000000*i
z^2 = -3.000000 + -4.000000*i
z^2 = -3.000000 + -4.000000*i
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.3.1/4 complex (p: 136)
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.1/4 complex (p: 188)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.1/2 complex (p: 170)
### See also
| | |
| --- | --- |
| [imaginary](imaginary "c/numeric/complex/imaginary")
(C99) | imaginary type macro (keyword macro) |
c cacosf, cacos, cacosl cacosf, cacos, cacosl
=====================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex cacosf( float complex z );
```
| (1) | (since C99) |
|
```
double complex cacos( double complex z );
```
| (2) | (since C99) |
|
```
long double complex cacosl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define acos( z )
```
| (4) | (since C99) |
1-3) Computes the complex arc cosine of `z` with branch cuts outside the interval [−1,+1] along the real axis.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `cacosl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `cacos` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `cacosf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`acosf`, `[acos](http://en.cppreference.com/w/c/numeric/math/acos)`, `acosl`). If `z` is imaginary, then the macro invokes the corresponding complex number version. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
If no errors occur, complex arc cosine of `z` is returned, in the range a strip unbounded along the imaginary axis and in the interval [0; π] along the real axis.
### Error handling and special values
Errors are reported consistent with [`math_errhandling`](../math/math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic,
* `cacos([conj](http://en.cppreference.com/w/c/numeric/complex/conj)(z)) == [conj](http://en.cppreference.com/w/c/numeric/complex/conj)(cacos(z))`
* If `z` is `±0+0i`, the result is `π/2-0i`
* If `z` is `±0+NaNi`, the result is `π/2+NaNi`
* If `z` is `x+∞i` (for any finite x), the result is `π/2-∞i`
* If `z` is `x+NaNi` (for any nonzero finite x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised.
* If `z` is `-∞+yi` (for any positive finite y), the result is `π-∞i`
* If `z` is `+∞+yi` (for any positive finite y), the result is `+0-∞i`
* If `z` is `-∞+∞i`, the result is `3π/4-∞i`
* If `z` is `+∞+∞i`, the result is `π/4-∞i`
* If `z` is `±∞+NaNi`, the result is `NaN±∞i` (the sign of the imaginary part is unspecified)
* If `z` is `NaN+yi` (for any finite y), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `z` is `NaN+∞i`, the result is `NaN-∞i`
* If `z` is `NaN+NaNi`, the result is `NaN+NaNi`
### Notes
Inverse cosine (or arc cosine) is a multivalued function and requires a branch cut on the complex plane. The branch cut is conventially placed at the line segments (-∞,-1) and (1,∞) of the real axis. The mathematical definition of the principal value of arc cosine is acos z =
1/2π + *i*ln(*i*z + √1-z2
) For any z, acos(z) = π - acos(-z).
### Example
```
#include <stdio.h>
#include <math.h>
#include <complex.h>
int main(void)
{
double complex z = cacos(-2);
printf("cacos(-2+0i) = %f%+fi\n", creal(z), cimag(z));
double complex z2 = cacos(conj(-2)); // or CMPLX(-2, -0.0)
printf("cacos(-2-0i) (the other side of the cut) = %f%+fi\n", creal(z2), cimag(z2));
// for any z, acos(z) = pi - acos(-z)
double pi = acos(-1);
double complex z3 = ccos(pi-z2);
printf("ccos(pi - cacos(-2-0i) = %f%+fi\n", creal(z3), cimag(z3));
}
```
Output:
```
cacos(-2+0i) = 3.141593-1.316958i
cacos(-2-0i) (the other side of the cut) = 3.141593+1.316958i
ccos(pi - cacos(-2-0i) = 2.000000+0.000000i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.5.1 The cacos functions (p: 190)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.6.1.1 The cacos functions (p: 539)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.5.1 The cacos functions (p: 172)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.6.1.1 The cacos functions (p: 474)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [casincasinfcasinl](casin "c/numeric/complex/casin")
(C99)(C99)(C99) | computes the complex arc sine (function) |
| [catancatanfcatanl](catan "c/numeric/complex/catan")
(C99)(C99)(C99) | computes the complex arc tangent (function) |
| [ccosccosfccosl](ccos "c/numeric/complex/ccos")
(C99)(C99)(C99) | computes the complex cosine (function) |
| [acosacosfacosl](../math/acos "c/numeric/math/acos")
(C99)(C99) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/acos "cpp/numeric/complex/acos") for `acos` |
| programming_docs |
c cacoshf, cacosh, cacoshl cacoshf, cacosh, cacoshl
========================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex cacoshf( float complex z );
```
| (1) | (since C99) |
|
```
double complex cacosh( double complex z );
```
| (2) | (since C99) |
|
```
long double complex cacoshl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define acosh( z )
```
| (4) | (since C99) |
1-3) Computes complex arc hyperbolic cosine of a complex value `z` with branch cut at values less than 1 along the real axis.
4) Type-generic macro: If `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `cacoshl` is called. if `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `cacosh` is called, if `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `cacoshf` is called. If `z` is real or integer, then the macro invokes the corresponding real function (`acoshf`, `[acosh](http://en.cppreference.com/w/c/numeric/math/acosh)`, `acoshl`). If `z` is imaginary, then the macro invokes the corresponding complex number version and the return type is complex. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
The complex arc hyperbolic cosine of `z` in the interval [0; ∞) along the real axis and in the interval [−iπ; +iπ] along the imaginary axis.
### Error handling and special values
Errors are reported consistent with [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic,
* `cacosh([conj](http://en.cppreference.com/w/c/numeric/complex/conj)(z)) == [conj](http://en.cppreference.com/w/c/numeric/complex/conj)(cacosh(z))`
* If `z` is `±0+0i`, the result is `+0+iπ/2`
* If `z` is `+x+∞i` (for any finite x), the result is `+∞+iπ/2`
* If `z` is `+x+NaNi` (for non-zero finite x), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised.
* If `z` is `0+NaNi`, the result is `NaN±iπ/2`, where the sign of the imaginary part is unspecified
* If `z` is `-∞+yi` (for any positive finite y), the result is `+∞+iπ`
* If `z` is `+∞+yi` (for any positive finite y), the result is `+∞+0i`
* If `z` is `-∞+∞i`, the result is `+∞+3iπ/4`
* If `z` is `+∞+∞i`, the result is `+∞+iπ/4`
* If `z` is `±∞+NaNi`, the result is `+∞+NaNi`
* If `z` is `NaN+yi` (for any finite y), the result is `NaN+NaNi` and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised.
* If `z` is `NaN+∞i`, the result is `+∞+NaNi`
* If `z` is `NaN+NaNi`, the result is `NaN+NaNi`
### Notes
Although the C standard names this function "complex arc hyperbolic cosine", the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct name is "complex inverse hyperbolic cosine", and, less common, "complex area hyperbolic cosine".
Inverse hyperbolic cosine is a multivalued function and requires a branch cut on the complex plane. The branch cut is conventionally placed at the line segment (-∞,+1) of the real axis.
The mathematical definition of the principal value of the inverse hyperbolic cosine is acosh z = ln(z + √z+1 √z-1) For any z, acosh(z) =
√z-1/√1-z acos(z), or simply i acos(z) in the upper half of the complex plane. ### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
double complex z = cacosh(0.5);
printf("cacosh(+0.5+0i) = %f%+fi\n", creal(z), cimag(z));
double complex z2 = conj(0.5); // or cacosh(CMPLX(0.5, -0.0)) in C11
printf("cacosh(+0.5-0i) (the other side of the cut) = %f%+fi\n", creal(z2), cimag(z2));
// in upper half-plane, acosh(z) = i*acos(z)
double complex z3 = casinh(1+I);
printf("casinh(1+1i) = %f%+fi\n", creal(z3), cimag(z3));
double complex z4 = I*casin(1+I);
printf("I*asin(1+1i) = %f%+fi\n", creal(z4), cimag(z4));
}
```
Output:
```
cacosh(+0.5+0i) = 0.000000-1.047198i
cacosh(+0.5-0i) (the other side of the cut) = 0.500000-0.000000i
casinh(1+1i) = 1.061275+0.666239i
I*asin(1+1i) = -1.061275+0.666239i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.6.1 The cacosh functions (p: 192)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.6.2.1 The cacosh functions (p: 539-540)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.6.1 The cacosh functions (p: 174)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.6.2.1 The cacosh functions (p: 474-475)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| | |
| --- | --- |
| [cacoscacosfcacosl](cacos "c/numeric/complex/cacos")
(C99)(C99)(C99) | computes the complex arc cosine (function) |
| [casinhcasinhfcasinhl](casinh "c/numeric/complex/casinh")
(C99)(C99)(C99) | computes the complex arc hyperbolic sine (function) |
| [catanhcatanhfcatanhl](catanh "c/numeric/complex/catanh")
(C99)(C99)(C99) | computes the complex arc hyperbolic tangent (function) |
| [ccoshccoshfccoshl](ccosh "c/numeric/complex/ccosh")
(C99)(C99)(C99) | computes the complex hyperbolic cosine (function) |
| [acoshacoshfacoshl](../math/acosh "c/numeric/math/acosh")
(C99)(C99)(C99) | computes inverse hyperbolic cosine (\({\small\operatorname{arcosh}{x} }\)arcosh(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/acosh "cpp/numeric/complex/acosh") for `acosh` |
c conjf, conj, conjl conjf, conj, conjl
==================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex conjf( float complex z );
```
| (1) | (since C99) |
|
```
double complex conj( double complex z );
```
| (2) | (since C99) |
|
```
long double complex conjl( long double complex z );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define conj( z )
```
| (4) | (since C99) |
1-3) Computes the [complex conjugate](https://en.wikipedia.org/wiki/Complex_conjugate "enwiki:Complex conjugate") of `z` by reversing the sign of the imaginary part.
4) Type-generic macro: if `z` has type `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `long double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, or `long double`, `conjl` is called. If `z` has type `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `float [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, or `float`, `conjf` is called. If `z` has type `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, `double`, or any integer type, `conj` is called. ### Parameters
| | | |
| --- | --- | --- |
| z | - | complex argument |
### Return value
The complex conjugate of `z`.
### Notes
On C99 implementations that do not implement `I` as `[\_Imaginary\_I](imaginary_i "c/numeric/complex/Imaginary I")`, `conj` may be used to obtain complex numbers with negative zero imaginary part. In C11, the macro `[CMPLX](cmplx "c/numeric/complex/CMPLX")` is used for that purpose.
### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
double complex z = 1.0 + 2.0*I;
double complex z2 = conj(z);
printf("The conjugate of %.1f%+.1fi is %.1f%+.1fi\n",
creal(z), cimag(z), creal(z2), cimag(z2));
printf("Their product is %.1f%+.1fi\n", creal(z*z2), cimag(z*z2));
}
```
Output:
```
The conjugate of 1.0+2.0i is 1.0-2.0i
Their product is 5.0+0.0i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.9.4 The conj functions (p: 198)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ G.7 Type-generic math <tgmath.h> (p: 545)
* C99 standard (ISO/IEC 9899:1999):
+ 7.3.9.3 The conj functions (p: 179)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ G.7 Type-generic math <tgmath.h> (p: 480)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/conj "cpp/numeric/complex/conj") for `conj` |
c CMPLXF, CMPLX, CMPLXL CMPLXF, CMPLX, CMPLXL
=====================
| Defined in header `<complex.h>` | | |
| --- | --- | --- |
|
```
float complex CMPLXF( float real, float imag );
```
| | (since C11) |
|
```
double complex CMPLX( double real, double imag );
```
| | (since C11) |
|
```
long double complex CMPLXL( long double real, long double imag );
```
| | (since C11) |
Each of these macros expands to an expression that evaluates to the value of the specified complex type, with the real part having the value of `real` (converted to the specified argument type) and the imaginary part having the value of `imag` (converted to the specified argument type).
The expressions are suitable for use as initializers for objects with static or thread storage duration, as long as the expressions `real` and `imag` are also suitable.
### Parameters
| | | |
| --- | --- | --- |
| real | - | the real part of the complex number to return |
| imag | - | the imaginary part of the complex number to return |
### Return value
A complex number composed of `real` and `imag` as the real and imaginary parts.
### Notes
These macros are implemented as if the imaginary types are supported (even if they are otherwise not supported and `[\_Imaginary\_I](imaginary_i "c/numeric/complex/Imaginary I")` is actually undefined) and as if defined as follows:
```
#define CMPLX(x, y) ((double complex)((double)(x) + _Imaginary_I * (double)(y)))
#define CMPLXF(x, y) ((float complex)((float)(x) + _Imaginary_I * (float)(y)))
#define CMPLXL(x, y) ((long double complex)((long double)(x) + \
_Imaginary_I * (long double)(y)))
```
### Example
```
#include <stdio.h>
#include <complex.h>
int main(void)
{
double complex z = CMPLX(0.0, -0.0);
printf("z = %.1f%+.1fi\n", creal(z), cimag(z));
}
```
Output:
```
z = 0.0-0.0i
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.3.9.3 The CMPLX macros (p: 197)
### See also
| | |
| --- | --- |
| [\_Imaginary\_I](imaginary_i "c/numeric/complex/Imaginary I")
(C99) | the imaginary unit constant i (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/complex/complex "cpp/numeric/complex/complex") for `complex` |
c fetestexcept fetestexcept
============
| Defined in header `<fenv.h>` | | |
| --- | --- | --- |
|
```
int fetestexcept( int excepts );
```
| | (since C99) |
Determines which of the specified subset of the floating-point exceptions are currently set. The argument `excepts` is a bitwise OR of the [floating-point exception macros](fe_exceptions "c/numeric/fenv/FE exceptions").
### Parameters
| | | |
| --- | --- | --- |
| excepts | - | bitmask listing the exception flags to test |
### Return value
Bitwise OR of the floating-point exception macros that are both included in `excepts` and correspond to floating-point exceptions currently set.
### Example
```
#include <stdio.h>
#include <math.h>
#include <fenv.h>
#include <float.h>
#pragma STDC FENV_ACCESS ON
void show_fe_exceptions(void)
{
printf("current exceptions raised: ");
if(fetestexcept(FE_DIVBYZERO)) printf(" FE_DIVBYZERO");
if(fetestexcept(FE_INEXACT)) printf(" FE_INEXACT");
if(fetestexcept(FE_INVALID)) printf(" FE_INVALID");
if(fetestexcept(FE_OVERFLOW)) printf(" FE_OVERFLOW");
if(fetestexcept(FE_UNDERFLOW)) printf(" FE_UNDERFLOW");
if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none");
printf("\n");
}
int main(void)
{
/* Show default set of exception flags. */
show_fe_exceptions();
/* Perform some computations which raise exceptions. */
printf("1.0/0.0 = %f\n", 1.0/0.0); /* FE_DIVBYZERO */
printf("1.0/10.0 = %f\n", 1.0/10.0); /* FE_INEXACT */
printf("sqrt(-1) = %f\n", sqrt(-1)); /* FE_INVALID */
printf("DBL_MAX*2.0 = %f\n", DBL_MAX*2.0); /* FE_INEXACT FE_OVERFLOW */
printf("nextafter(DBL_MIN/pow(2.0,52),0.0) = %.1f\n",
nextafter(DBL_MIN/pow(2.0,52),0.0)); /* FE_INEXACT FE_UNDERFLOW */
show_fe_exceptions();
return 0;
}
```
Output:
```
current exceptions raised: none
1.0/0.0 = inf
1.0/10.0 = 0.100000
sqrt(-1) = -nan
DBL_MAX*2.0 = inf
nextafter(DBL_MIN/pow(2.0,52),0.0) = 0.0
current exceptions raised: FE_DIVBYZERO FE_INEXACT FE_INVALID FE_OVERFLOW FE_UNDERFLOW
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.6.2.5 The fetestexcept function (p: 211-212)
* C99 standard (ISO/IEC 9899:1999):
+ 7.6.2.5 The fetestexcept function (p: 192-193)
### See also
| | |
| --- | --- |
| [feclearexcept](feclearexcept "c/numeric/fenv/feclearexcept")
(C99) | clears the specified floating-point status flags (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/fenv/fetestexcept "cpp/numeric/fenv/fetestexcept") for `fetestexcept` |
c fegetexceptflag, fesetexceptflag fegetexceptflag, fesetexceptflag
================================
| Defined in header `<fenv.h>` | | |
| --- | --- | --- |
|
```
int fegetexceptflag( fexcept_t* flagp, int excepts );
```
| (1) | (since C99) |
|
```
int fesetexceptflag( const fexcept_t* flagp, int excepts );
```
| (2) | (since C99) |
1) Attempts to obtain the full contents of the floating-point exception flags that are listed in the bitmask argument `excepts`, which is a bitwise OR of the [floating-point exception macros](fe_exceptions "c/numeric/fenv/FE exceptions").
2) Attempts to copy the full contents of the floating-point exception flags that are listed in `excepts` from `flagp` into the floating-point environment. Does not raise any exceptions, only modifies the flags.
The full contents of a floating-point exception flag is not necessarily a boolean value indicating whether the exception is raised or cleared. For example, it may be a struct which includes the boolean status and the address of the code that triggered the exception. These functions obtain all such content and obtain/store it in `flagp` in implementation-defined format.
### Parameters
| | | |
| --- | --- | --- |
| flagp | - | pointer to an `fexcept_t` object where the flags will be stored or read from |
| excepts | - | bitmask listing the exception flags to get/set |
### Return value
`0` on success, non-zero otherwise.
### Example
```
#include <stdio.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
void show_fe_exceptions(void)
{
printf("current exceptions raised: ");
if(fetestexcept(FE_DIVBYZERO)) printf(" FE_DIVBYZERO");
if(fetestexcept(FE_INEXACT)) printf(" FE_INEXACT");
if(fetestexcept(FE_INVALID)) printf(" FE_INVALID");
if(fetestexcept(FE_OVERFLOW)) printf(" FE_OVERFLOW");
if(fetestexcept(FE_UNDERFLOW)) printf(" FE_UNDERFLOW");
if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none");
printf("\n");
}
int main(void)
{
fexcept_t excepts;
/* Setup a "current" set of exception flags. */
feraiseexcept(FE_INVALID);
show_fe_exceptions();
/* Save current exception flags. */
fegetexceptflag(&excepts,FE_ALL_EXCEPT);
/* Temporarily raise two other exceptions. */
feclearexcept(FE_ALL_EXCEPT);
feraiseexcept(FE_OVERFLOW | FE_INEXACT);
show_fe_exceptions();
/* Restore previous exception flags. */
fesetexceptflag(&excepts,FE_ALL_EXCEPT);
show_fe_exceptions();
return 0;
}
```
Output:
```
current exceptions raised: FE_INVALID
current exceptions raised: FE_INEXACT FE_OVERFLOW
current exceptions raised: FE_INVALID
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.6.2.2 The fegetexceptflag function (p: 210)
+ 7.6.2.4 The fesetexceptflag function (p: 211)
* C99 standard (ISO/IEC 9899:1999):
+ 7.6.2.2 The fegetexceptflag function (p: 191)
+ 7.6.2.4 The fesetexceptflag function (p: 192)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/fenv/feexceptflag "cpp/numeric/fenv/feexceptflag") for `fegetexceptflag, fesetexceptflag` |
c feraiseexcept feraiseexcept
=============
| Defined in header `<fenv.h>` | | |
| --- | --- | --- |
|
```
int feraiseexcept( int excepts );
```
| | (since C99) |
Attempts to raise all floating-point exceptions listed in `excepts` (a bitwise OR of the [floating-point exception macros](fe_exceptions "c/numeric/fenv/FE exceptions")). If one of the exceptions is `[FE\_OVERFLOW](fe_exceptions "c/numeric/fenv/FE exceptions")` or `[FE\_UNDERFLOW](http://en.cppreference.com/w/c/numeric/fenv/FE_exceptions)`, this function may additionally raise `[FE\_INEXACT](fe_exceptions "c/numeric/fenv/FE exceptions")`. The order in which the exceptions are raised is unspecified, except that `[FE\_OVERFLOW](fe_exceptions "c/numeric/fenv/FE exceptions")` and `[FE\_UNDERFLOW](http://en.cppreference.com/w/c/numeric/fenv/FE_exceptions)` are always raised before `[FE\_INEXACT](fe_exceptions "c/numeric/fenv/FE exceptions")`.
### Parameters
| | | |
| --- | --- | --- |
| excepts | - | bitmask listing the exception flags to raise |
### Return value
`0` if all listed exceptions were raised, non-zero value otherwise.
### Example
```
#include <stdio.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
void show_fe_exceptions(void)
{
printf("current exceptions raised: ");
if(fetestexcept(FE_DIVBYZERO)) printf(" FE_DIVBYZERO");
if(fetestexcept(FE_INEXACT)) printf(" FE_INEXACT");
if(fetestexcept(FE_INVALID)) printf(" FE_INVALID");
if(fetestexcept(FE_OVERFLOW)) printf(" FE_OVERFLOW");
if(fetestexcept(FE_UNDERFLOW)) printf(" FE_UNDERFLOW");
if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none");
feclearexcept(FE_ALL_EXCEPT);
printf("\n");
}
double some_computation(void)
{
/* Computation reaches a state that causes overflow. */
int r = feraiseexcept(FE_OVERFLOW | FE_INEXACT);
printf("feraiseexcept() %s\n", (r?"fails":"succeeds"));
return 0.0;
}
int main(void)
{
some_computation();
show_fe_exceptions();
return 0;
}
```
Output:
```
feraiseexcept() succeeds
current exceptions raised: FE_INEXACT FE_OVERFLOW
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.6.2.3 The feraiseexcept function (p: 210)
* C99 standard (ISO/IEC 9899:1999):
+ 7.6.2.3 The feraiseexcept function (p: 191)
### See also
| | |
| --- | --- |
| [feclearexcept](feclearexcept "c/numeric/fenv/feclearexcept")
(C99) | clears the specified floating-point status flags (function) |
| [fetestexcept](fetestexcept "c/numeric/fenv/fetestexcept")
(C99) | determines which of the specified floating-point status flags are set (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/fenv/feraiseexcept "cpp/numeric/fenv/feraiseexcept") for `feraiseexcept` |
c fegetenv, fesetenv fegetenv, fesetenv
==================
| Defined in header `<fenv.h>` | | |
| --- | --- | --- |
|
```
int fegetenv( fenv_t* envp );
```
| (1) | (since C99) |
|
```
int fesetenv( const fenv_t* envp );
```
| (2) | (since C99) |
1) Attempts to store the status of the floating-point environment in the object pointed to by `envp`.
2) Attempts to establish the floating-point environment from the object pointed to by `envp`. The value of that object must be previously obtained by a call to `[feholdexcept](feholdexcept "c/numeric/fenv/feholdexcept")` or `fegetenv` or be a floating-point macro constant. If any of the floating-point status flags are set in `envp`, they become set in the environment (and are then testable with `[fetestexcept](fetestexcept "c/numeric/fenv/fetestexcept")`), but the corresponding floating-point exceptions are not raised (execution continues uninterrupted).
### Parameters
| | | |
| --- | --- | --- |
| envp | - | pointer to the object of type `fenv_t` which holds the status of the floating-point environment |
### Return value
`0` on success, non-zero otherwise.
### Example
```
#include <stdio.h>
#include <math.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
void show_fe_exceptions(void)
{
printf("current exceptions raised: ");
if(fetestexcept(FE_DIVBYZERO)) printf(" FE_DIVBYZERO");
if(fetestexcept(FE_INEXACT)) printf(" FE_INEXACT");
if(fetestexcept(FE_INVALID)) printf(" FE_INVALID");
if(fetestexcept(FE_OVERFLOW)) printf(" FE_OVERFLOW");
if(fetestexcept(FE_UNDERFLOW)) printf(" FE_UNDERFLOW");
if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none");
printf("\n");
}
void show_fe_rounding_method(void)
{
printf("current rounding method: ");
switch (fegetround()) {
case FE_TONEAREST: printf ("FE_TONEAREST"); break;
case FE_DOWNWARD: printf ("FE_DOWNWARD"); break;
case FE_UPWARD: printf ("FE_UPWARD"); break;
case FE_TOWARDZERO: printf ("FE_TOWARDZERO"); break;
default: printf ("unknown");
};
printf("\n");
}
void show_fe_environment(void)
{
show_fe_exceptions();
show_fe_rounding_method();
}
int main(void)
{
fenv_t curr_env;
int rtn;
/* Show default environment. */
show_fe_environment();
printf("\n");
/* Perform some computation under default environment. */
printf("+11.5 -> %+4.1f\n", rint(+11.5)); /* midway between two integers */
printf("+12.5 -> %+4.1f\n", rint(+12.5)); /* midway between two integers */
show_fe_environment();
printf("\n");
/* Save current environment. */
rtn = fegetenv(&curr_env);
/* Perform some computation with new rounding method. */
feclearexcept(FE_ALL_EXCEPT);
fesetround(FE_DOWNWARD);
printf("1.0/0.0 = %f\n", 1.0/0.0);
printf("+11.5 -> %+4.1f\n", rint(+11.5));
printf("+12.5 -> %+4.1f\n", rint(+12.5));
show_fe_environment();
printf("\n");
/* Restore previous environment. */
rtn = fesetenv(&curr_env);
show_fe_environment();
return 0;
}
```
Output:
```
current exceptions raised: none
current rounding method: FE_TONEAREST
+11.5 -> +12.0
+12.5 -> +12.0
current exceptions raised: FE_INEXACT
current rounding method: FE_TONEAREST
1.0/0.0 = inf
+11.5 -> +11.0
+12.5 -> +12.0
current exceptions raised: FE_DIVBYZERO FE_INEXACT
current rounding method: FE_DOWNWARD
current exceptions raised: FE_INEXACT
current rounding method: FE_TONEAREST
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.6.4.1 The fegetenv function (p: 213)
+ 7.6.4.3 The fesetenv function (p: 214)
* C99 standard (ISO/IEC 9899:1999):
+ 7.6.4.1 The fegetenv function (p: 194)
+ 7.6.4.3 The fesetenv function (p: 195)
### See also
| | |
| --- | --- |
| [feholdexcept](feholdexcept "c/numeric/fenv/feholdexcept")
(C99) | saves the environment, clears all status flags and ignores all future errors (function) |
| [feupdateenv](feupdateenv "c/numeric/fenv/feupdateenv")
(C99) | restores the floating-point environment and raises the previously raise exceptions (function) |
| [FE\_DFL\_ENV](fe_dfl_env "c/numeric/fenv/FE DFL ENV")
(C99) | default floating-point environment (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/fenv/feenv "cpp/numeric/fenv/feenv") for `fegetenv, fesetenv` |
| programming_docs |
c FE_DOWNWARD, FE_TONEAREST, FE_TOWARDZERO, FE_UPWARD FE\_DOWNWARD, FE\_TONEAREST, FE\_TOWARDZERO, FE\_UPWARD
=======================================================
| Defined in header `<fenv.h>` | | |
| --- | --- | --- |
|
```
#define FE_DOWNWARD /*implementation defined*/
```
| | (since C99) |
|
```
#define FE_TONEAREST /*implementation defined*/
```
| | (since C99) |
|
```
#define FE_TOWARDZERO /*implementation defined*/
```
| | (since C99) |
|
```
#define FE_UPWARD /*implementation defined*/
```
| | (since C99) |
Each of these macro constants expands to a nonnegative integer constant expression, which can be used with `[fesetround](feround "c/numeric/fenv/feround")` and `[fegetround](feround "c/numeric/fenv/feround")` to indicate one of the supported floating-point rounding modes. The implementation may define additional rounding mode constants in `<fenv.h>`, which should all begin with `FE_` followed by at least one uppercase letter. Each macro is only defined if it is supported.
| Constant | Explanation |
| --- | --- |
| `FE_DOWNWARD` | rounding towards negative infinity |
| `FE_TONEAREST` | rounding towards nearest representable value |
| `FE_TOWARDZERO` | rounding towards zero |
| `FE_UPWARD` | rounding towards positive infinity |
Additional rounding modes may be supported by an implementation.
The current rounding mode affects the following:
* results of floating-point arithmetic operators outside of constant expressions
```
double x = 1;
x/10; // 0.09999999999999999167332731531132594682276248931884765625
// or 0.1000000000000000055511151231257827021181583404541015625
```
* results of standard library [mathematical functions](../math "c/numeric/math")
```
sqrt(2); // 1.41421356237309492343001693370752036571502685546875
// or 1.4142135623730951454746218587388284504413604736328125
```
* floating-point to floating-point implicit conversion and casts
```
double d = 1 + DBL_EPSILON;
float f = d; // 1.00000000000000000000000
// or 1.00000011920928955078125
```
* string conversions such as `[strtod](../../string/byte/strtof "c/string/byte/strtof")` or `[printf](../../io/fprintf "c/io/fprintf")`
```
strtof("0.1", NULL); // 0.0999999940395355224609375
// or 0.100000001490116119384765625
```
* the library rounding functions `[nearbyint](../math/nearbyint "c/numeric/math/nearbyint")`, `[rint](../math/rint "c/numeric/math/rint")`, `[lrint](../math/rint "c/numeric/math/rint")`
```
lrint(2.1); // 2 or 3
```
The current rounding mode does NOT affect the following:
* floating-point to integer implicit conversion and casts (always towards zero)
* results of floating-point arithmetic operators in constant expressions executed at compile time (always to nearest)
* the library functions `[round](../math/round "c/numeric/math/round")`, `[lround](../math/round "c/numeric/math/round")`, `[llround](../math/round "c/numeric/math/round")`, `[ceil](../math/ceil "c/numeric/math/ceil")`, `[floor](../math/floor "c/numeric/math/floor")`, `[trunc](../math/trunc "c/numeric/math/trunc")`
As with any [floating-point environment](../fenv "c/numeric/fenv") functionality, rounding is only guaranteed if `#pragma STDC FENV_ACCESS ON` is set.
Compilers that do not support the pragma may offer their own ways to support current rounding mode. For example Clang and GCC have the option `-frounding-math` intended to disable optimizations that would change the meaning of rounding-sensitive code.
### Example
```
#include <stdio.h>
#include <stdlib.h>
#include <fenv.h>
#include <math.h>
int main()
{
#pragma STDC FENV_ACCESS ON
fesetround(FE_DOWNWARD);
puts("rounding down: ");
printf(" pi = %.22f\n", acosf(-1));
printf("strtof(\"1.1\") = %.22f\n", strtof("1.1", NULL));
printf(" rint(2.1) = %.22f\n\n", rintf(2.1));
fesetround(FE_UPWARD);
puts("rounding up: ");
printf(" pi = %.22f\n", acosf(-1));
printf("strtof(\"1.1\") = %.22f\n", strtof("1.1", NULL));
printf(" rint(2.1) = %.22f\n", rintf(2.1));
}
```
Output:
```
rounding down:
pi = 3.1415925025939941406250
strtof("1.1") = 1.0999999046325683593750
rint(2.1) = 2.0000000000000000000000
rounding up:
pi = 3.1415927410125732421875
strtof("1.1") = 1.1000000238418579101563
rint(2.1) = 3.0000000000000000000000
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.6/8 Floating-point environment <fenv.h> (p: 151)
* C11 standard (ISO/IEC 9899:2011):
+ 7.6/8 Floating-point environment <fenv.h> (p: 207)
* C99 standard (ISO/IEC 9899:1999):
+ 7.6/7 Floating-point environment <fenv.h> (p: 188)
### See also
| | |
| --- | --- |
| [fegetroundfesetround](feround "c/numeric/fenv/feround")
(C99)(C99) | gets or sets rounding direction (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/fenv/FE_round "cpp/numeric/fenv/FE round") for floating-point rounding macros |
c fegetround, fesetround fegetround, fesetround
======================
| Defined in header `<fenv.h>` | | |
| --- | --- | --- |
|
```
int fesetround( int round );
```
| (1) | (since C99) |
|
```
int fegetround();
```
| (2) | (since C99) |
1) Attempts to establish the floating-point rounding direction equal to the argument `round`, which is expected to be one of the [floating-point rounding macros](fe_round "c/numeric/fenv/FE round").
2) Returns the value of the [floating-point rounding macro](fe_round "c/numeric/fenv/FE round") that corresponds to the current rounding direction.
### Parameters
| | | |
| --- | --- | --- |
| round | - | rounding direction, one of [floating-point rounding macros](fe_round "c/numeric/fenv/FE round") |
### Return value
1) `0` on success, non-zero otherwise.
2) the [floating-point rounding macro](fe_round "c/numeric/fenv/FE round") describing the current rounding direction or a negative value if the direction cannot be determined.
### Notes
The current rounding mode, reflecting the effects of the most recent `fesetround`, can also be queried with `[FLT\_ROUNDS](../../types/limits/flt_rounds "c/types/limits/FLT ROUNDS")`.
### Example
```
#include <stdio.h>
#include <math.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
void show_fe_current_rounding_direction(void)
{
printf("current rounding direction: ");
switch (fegetround()) {
case FE_TONEAREST: printf ("FE_TONEAREST"); break;
case FE_DOWNWARD: printf ("FE_DOWNWARD"); break;
case FE_UPWARD: printf ("FE_UPWARD"); break;
case FE_TOWARDZERO: printf ("FE_TOWARDZERO"); break;
default: printf ("unknown");
};
printf("\n");
}
int main(void)
{
/* Default rounding direction */
show_fe_current_rounding_direction();
printf("+11.5 -> %+4.1f\n", rint(+11.5)); /* midway between two integers */
printf("+12.5 -> %+4.1f\n", rint(+12.5)); /* midway between two integers */
/* Save current rounding direction. */
int curr_direction = fegetround();
/* Temporarily change current rounding direction. */
fesetround(FE_DOWNWARD);
show_fe_current_rounding_direction();
printf("+11.5 -> %+4.1f\n", rint(+11.5));
printf("+12.5 -> %+4.1f\n", rint(+12.5));
/* Restore default rounding direction. */
fesetround(curr_direction);
show_fe_current_rounding_direction();
return 0;
}
```
Possible output:
```
current rounding direction: FE_TONEAREST
+11.5 -> +12.0
+12.5 -> +12.0
current rounding direction: FE_DOWNWARD
+11.5 -> +11.0
+12.5 -> +12.0
current rounding direction: FE_TONEAREST
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.6.3.1 The fegetround function (p: 212)
+ 7.6.3.2 The fesetround function (p: 212-213)
* C99 standard (ISO/IEC 9899:1999):
+ 7.6.3.1 The fegetround function (p: 193)
+ 7.6.3.2 The fesetround function (p: 193-194)
### See also
| | |
| --- | --- |
| [nearbyintnearbyintfnearbyintl](../math/nearbyint "c/numeric/math/nearbyint")
(C99)(C99)(C99) | rounds to an integer using current rounding mode (function) |
| [rintrintfrintllrintlrintflrintlllrintllrintfllrintl](../math/rint "c/numeric/math/rint")
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) | rounds to an integer using current rounding mode with exception if the result differs (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/fenv/feround "cpp/numeric/fenv/feround") for `fegetround, fesetround` |
c feupdateenv feupdateenv
===========
| Defined in header `<fenv.h>` | | |
| --- | --- | --- |
|
```
int feupdateenv( const fenv_t* envp );
```
| | (since C99) |
First, remembers the currently raised floating-point exceptions, then restores the floating-point environment from the object pointed to by `envp` (similar to `[fesetenv](feenv "c/numeric/fenv/feenv")`), then raises the floating-point exceptions that were saved.
This function may be used to end the non-stop mode established by an earlier call to `[feholdexcept](feholdexcept "c/numeric/fenv/feholdexcept")`.
### Parameters
| | | |
| --- | --- | --- |
| envp | - | pointer to the object of type `fenv_t` set by an earlier call to `[feholdexcept](feholdexcept "c/numeric/fenv/feholdexcept")` or `fegetenv` or equal to `[FE\_DFL\_ENV](fe_dfl_env "c/numeric/fenv/FE DFL ENV")` |
### Return value
`0` on success, non-zero otherwise.
### Example
```
#include <stdio.h>
#include <fenv.h>
#include <float.h>
#pragma STDC FENV_ACCESS ON
void show_fe_exceptions(void)
{
printf("current exceptions raised: ");
if(fetestexcept(FE_DIVBYZERO)) printf(" FE_DIVBYZERO");
if(fetestexcept(FE_INEXACT)) printf(" FE_INEXACT");
if(fetestexcept(FE_INVALID)) printf(" FE_INVALID");
if(fetestexcept(FE_OVERFLOW)) printf(" FE_OVERFLOW");
if(fetestexcept(FE_UNDERFLOW)) printf(" FE_UNDERFLOW");
if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none");
printf("\n");
}
double x2 (double x) /* times two */
{
fenv_t curr_excepts;
/* Save and clear current f-p environment. */
feholdexcept(&curr_excepts);
/* Raise inexact and overflow exceptions. */
printf("In x2(): x = %f\n", x=x*2.0);
show_fe_exceptions();
feclearexcept(FE_INEXACT); /* hide inexact exception from caller */
/* Merge caller's exceptions (FE_INVALID) */
/* with remaining x2's exceptions (FE_OVERFLOW). */
feupdateenv(&curr_excepts);
return x;
}
int main(void)
{
feclearexcept(FE_ALL_EXCEPT);
feraiseexcept(FE_INVALID); /* some computation with invalid argument */
show_fe_exceptions();
printf("x2(DBL_MAX) = %f\n", x2(DBL_MAX));
show_fe_exceptions();
return 0;
}
```
Output:
```
current exceptions raised: FE_INVALID
In x2(): x = inf
current exceptions raised: FE_INEXACT FE_OVERFLOW
x2(DBL_MAX) = inf
current exceptions raised: FE_INVALID FE_OVERFLOW
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.6.4.4 The feupdateenv function (p: 214-215)
* C99 standard (ISO/IEC 9899:1999):
+ 7.6.4.4 The feupdateenv function (p: 195-196)
### See also
| | |
| --- | --- |
| [feholdexcept](feholdexcept "c/numeric/fenv/feholdexcept")
(C99) | saves the environment, clears all status flags and ignores all future errors (function) |
| [fegetenvfesetenv](feenv "c/numeric/fenv/feenv")
(C99) | saves or restores the current floating-point environment (function) |
| [FE\_DFL\_ENV](fe_dfl_env "c/numeric/fenv/FE DFL ENV")
(C99) | default floating-point environment (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/fenv/feupdateenv "cpp/numeric/fenv/feupdateenv") for `feupdateenv` |
c feholdexcept feholdexcept
============
| Defined in header `<fenv.h>` | | |
| --- | --- | --- |
|
```
int feholdexcept( fenv_t* envp );
```
| | (since C99) |
First, saves the current floating-point environment to the object pointed to by `envp` (similar to `[fegetenv](feenv "c/numeric/fenv/feenv")`), then clears all floating-point status flags, and then installs the non-stop mode: future floating-point exceptions will not interrupt execution (will not trap), until the floating-point environment is restored by `[feupdateenv](feupdateenv "c/numeric/fenv/feupdateenv")` or `[fesetenv](feenv "c/numeric/fenv/feenv")`.
This function may be used in the beginning of a subroutine that must hide the floating-point exceptions it may raise from the caller. If only some exceptions must be suppressed, while others must be reported, the non-stop mode is usually ended with a call to `[feupdateenv](feupdateenv "c/numeric/fenv/feupdateenv")` after clearing the unwanted exceptions.
### Parameters
| | | |
| --- | --- | --- |
| envp | - | pointer to the object of type `fenv_t` where the floating-point environment will be stored |
### Return value
`0` on success, non-zero otherwise.
### Example
```
#include <stdio.h>
#include <fenv.h>
#include <float.h>
#pragma STDC FENV_ACCESS ON
void show_fe_exceptions(void)
{
printf("current exceptions raised: ");
if(fetestexcept(FE_DIVBYZERO)) printf(" FE_DIVBYZERO");
if(fetestexcept(FE_INEXACT)) printf(" FE_INEXACT");
if(fetestexcept(FE_INVALID)) printf(" FE_INVALID");
if(fetestexcept(FE_OVERFLOW)) printf(" FE_OVERFLOW");
if(fetestexcept(FE_UNDERFLOW)) printf(" FE_UNDERFLOW");
if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none");
printf("\n");
}
double x2 (double x) /* times two */
{
fenv_t curr_excepts;
/* Save and clear current f-p environment. */
feholdexcept(&curr_excepts);
/* Raise inexact and overflow exceptions. */
printf("In x2(): x = %f\n", x=x*2.0);
show_fe_exceptions();
feclearexcept(FE_INEXACT); /* hide inexact exception from caller */
/* Merge caller's exceptions (FE_INVALID) */
/* with remaining x2's exceptions (FE_OVERFLOW). */
feupdateenv(&curr_excepts);
return x;
}
int main(void)
{
feclearexcept(FE_ALL_EXCEPT);
feraiseexcept(FE_INVALID); /* some computation with invalid argument */
show_fe_exceptions();
printf("x2(DBL_MAX) = %f\n", x2(DBL_MAX));
show_fe_exceptions();
return 0;
}
```
Output:
```
current exceptions raised: FE_INVALID
In x2(): x = inf
current exceptions raised: FE_INEXACT FE_OVERFLOW
x2(DBL_MAX) = inf
current exceptions raised: FE_INVALID FE_OVERFLOW
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.6.4.2 The feholdexcept function (p: 213-214)
* C99 standard (ISO/IEC 9899:1999):
+ 7.6.4.2 The feholdexcept function (p: 194-195)
### See also
| | |
| --- | --- |
| [feupdateenv](feupdateenv "c/numeric/fenv/feupdateenv")
(C99) | restores the floating-point environment and raises the previously raise exceptions (function) |
| [fegetenvfesetenv](feenv "c/numeric/fenv/feenv")
(C99) | saves or restores the current floating-point environment (function) |
| [FE\_DFL\_ENV](fe_dfl_env "c/numeric/fenv/FE DFL ENV")
(C99) | default floating-point environment (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/fenv/feholdexcept "cpp/numeric/fenv/feholdexcept") for `feholdexcept` |
c feclearexcept feclearexcept
=============
| Defined in header `<fenv.h>` | | |
| --- | --- | --- |
|
```
int feclearexcept( int excepts );
```
| | (since C99) |
Attempts to clear the floating-point exceptions that are listed in the bitmask argument `excepts`, which is a bitwise OR of the [floating-point exception macros](fe_exceptions "c/numeric/fenv/FE exceptions").
### Parameters
| | | |
| --- | --- | --- |
| excepts | - | bitmask listing the exception flags to clear |
### Return value
`0` if all indicated exceptions were successfully cleared or if `excepts` is zero. Returns a non-zero value on error.
### Example
```
#include <fenv.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
/*
* A possible implementation of hypot which makes use of many advanced
* floating-point features.
*/
double hypot_demo(double a, double b) {
const int range_problem = FE_OVERFLOW | FE_UNDERFLOW;
feclearexcept(range_problem);
// try a fast algorithm
double result = sqrt(a * a + b * b);
if (!fetestexcept(range_problem)) // no overflow or underflow
return result; // return the fast result
// do a more complicated calculation to avoid overflow or underflow
int a_exponent,b_exponent;
frexp(a, &a_exponent);
frexp(b, &b_exponent);
if (a_exponent - b_exponent > DBL_MAX_EXP)
return fabs(a) + fabs(b); // we can ignore the smaller value
// scale so that fabs(a) is near 1
double a_scaled = scalbn(a, -a_exponent);
double b_scaled = scalbn(b, -a_exponent);
// overflow and underflow is now impossible
result = sqrt(a_scaled * a_scaled + b_scaled * b_scaled);
// undo scaling
return scalbn(result, a_exponent);
}
int main(void)
{
// Normal case takes the fast route
printf("hypot(%f, %f) = %f\n", 3.0, 4.0, hypot_demo(3.0, 4.0));
// Extreme case takes the slow but more accurate route
printf("hypot(%e, %e) = %e\n", DBL_MAX / 2.0,
DBL_MAX / 2.0,
hypot_demo(DBL_MAX / 2.0, DBL_MAX / 2.0));
return 0;
}
```
Output:
```
hypot(3.000000, 4.000000) = 5.000000
hypot(8.988466e+307, 8.988466e+307) = 1.271161e+308
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.6.2.1 The feclearexcept function (p: 209)
* C99 standard (ISO/IEC 9899:1999):
+ 7.6.2.1 The feclearexcept function (p: 190)
### See also
| | |
| --- | --- |
| [fetestexcept](fetestexcept "c/numeric/fenv/fetestexcept")
(C99) | determines which of the specified floating-point status flags are set (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/fenv/feclearexcept "cpp/numeric/fenv/feclearexcept") for `feclearexcept` |
c FE_DIVBYZERO, FE_INEXACT, FE_INVALID, FE_OVERFLOW, FE_UNDERFLOW, FE_ALL_EXCEPT FE\_DIVBYZERO, FE\_INEXACT, FE\_INVALID, FE\_OVERFLOW, FE\_UNDERFLOW, FE\_ALL\_EXCEPT
=====================================================================================
| Defined in header `<fenv.h>` | | |
| --- | --- | --- |
|
```
#define FE_DIVBYZERO /*implementation defined power of 2*/
```
| | (since C99) |
|
```
#define FE_INEXACT /*implementation defined power of 2*/
```
| | (since C99) |
|
```
#define FE_INVALID /*implementation defined power of 2*/
```
| | (since C99) |
|
```
#define FE_OVERFLOW /*implementation defined power of 2*/
```
| | (since C99) |
|
```
#define FE_UNDERFLOW /*implementation defined power of 2*/
```
| | (since C99) |
|
```
#define FE_ALL_EXCEPT FE_DIVBYZERO | FE_INEXACT | \
FE_INVALID | FE_OVERFLOW | \
FE_UNDERFLOW
```
| | (since C99) |
All these macro constants (except `FE_ALL_EXCEPT`) expand to integer constant expressions that are distinct powers of 2, which uniquely identify all supported floating-point exceptions. Each macro is only defined if it is supported.
The macro constant `FE_ALL_EXCEPT`, which expands to the bitwise OR of all other `FE_*`, is always defined and is zero if floating-point exceptions are not supported by the implementation.
| Constant | Explanation |
| --- | --- |
| `FE_DIVBYZERO` | pole error occurred in an earlier floating-point operation |
| `FE_INEXACT` | inexact result: rounding was necessary to store the result of an earlier floating-point operation |
| `FE_INVALID` | domain error occurred in an earlier floating-point operation |
| `FE_OVERFLOW` | the result of an earlier floating-point operation was too large to be representable |
| `FE_UNDERFLOW` | the result of an earlier floating-point operation was subnormal with a loss of precision |
| `FE_ALL_EXCEPT` | bitwise OR of all supported floating-point exceptions |
The implementation may define additional macro constants in `<fenv.h>` to identify additional floating-point exceptions. All such constants begin with `FE_` followed by at least one uppercase letter.
See [math\_errhandling](../math/math_errhandling "c/numeric/math/math errhandling") for further details.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
void show_fe_exceptions(void)
{
printf("exceptions raised:");
if(fetestexcept(FE_DIVBYZERO)) printf(" FE_DIVBYZERO");
if(fetestexcept(FE_INEXACT)) printf(" FE_INEXACT");
if(fetestexcept(FE_INVALID)) printf(" FE_INVALID");
if(fetestexcept(FE_OVERFLOW)) printf(" FE_OVERFLOW");
if(fetestexcept(FE_UNDERFLOW)) printf(" FE_UNDERFLOW");
feclearexcept(FE_ALL_EXCEPT);
printf("\n");
}
int main(void)
{
printf("MATH_ERREXCEPT is %s\n",
math_errhandling & MATH_ERREXCEPT ? "set" : "not set");
printf("0.0/0.0 = %f\n", 0.0/0.0);
show_fe_exceptions();
printf("1.0/0.0 = %f\n", 1.0/0.0);
show_fe_exceptions();
printf("1.0/10.0 = %f\n", 1.0/10.0);
show_fe_exceptions();
printf("sqrt(-1) = %f\n", sqrt(-1));
show_fe_exceptions();
printf("DBL_MAX*2.0 = %f\n", DBL_MAX*2.0);
show_fe_exceptions();
printf("nextafter(DBL_MIN/pow(2.0,52),0.0) = %.1f\n",
nextafter(DBL_MIN/pow(2.0,52),0.0));
show_fe_exceptions();
}
```
Possible output:
```
MATH_ERREXCEPT is set
0.0/0.0 = nan
exceptions raised: FE_INVALID
1.0/0.0 = inf
exceptions raised: FE_DIVBYZERO
1.0/10.0 = 0.100000
exceptions raised: FE_INEXACT
sqrt(-1) = -nan
exceptions raised: FE_INVALID
DBL_MAX*2.0 = inf
exceptions raised: FE_INEXACT FE_OVERFLOW
nextafter(DBL_MIN/pow(2.0,52),0.0) = 0.0
exceptions raised: FE_INEXACT FE_UNDERFLOW
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.6/6 Floating-point environment <fenv.h> (p: 207)
* C99 standard (ISO/IEC 9899:1999):
+ 7.6/5 Floating-point environment <fenv.h> (p: 188)
### See also
| | |
| --- | --- |
| [math\_errhandlingMATH\_ERRNOMATH\_ERREXCEPT](../math/math_errhandling "c/numeric/math/math errhandling")
(C99)(C99)(C99) | defines the error handling mechanism used by the common mathematical functions (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/fenv/FE_exceptions "cpp/numeric/fenv/FE exceptions") for floating-point exception macros |
| programming_docs |
c FE_DFL_ENV FE\_DFL\_ENV
============
| Defined in header `<fenv.h>` | | |
| --- | --- | --- |
|
```
#define FE_DFL_ENV /*implementation defined*/
```
| | (since C99) |
The macro constant `FE_DFL_ENV` expands to an expression of type `const fenv_t*`, which points to a full copy of the default floating-point environment, that is, the environment as loaded at program startup.
Additional macros that begin with `FE_` followed by uppercase letters, and have the type `const fenv_t*`, may be supported by an implementation.
### Example
```
#include <stdio.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
void show_fe_exceptions(void)
{
printf("current exceptions raised: ");
if(fetestexcept(FE_DIVBYZERO)) printf(" FE_DIVBYZERO");
if(fetestexcept(FE_INEXACT)) printf(" FE_INEXACT");
if(fetestexcept(FE_INVALID)) printf(" FE_INVALID");
if(fetestexcept(FE_OVERFLOW)) printf(" FE_OVERFLOW");
if(fetestexcept(FE_UNDERFLOW)) printf(" FE_UNDERFLOW");
if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none");
printf("\n");
}
void show_fe_rounding_method(void)
{
printf("current rounding method: ");
switch (fegetround()) {
case FE_TONEAREST: printf ("FE_TONEAREST"); break;
case FE_DOWNWARD: printf ("FE_DOWNWARD"); break;
case FE_UPWARD: printf ("FE_UPWARD"); break;
case FE_TOWARDZERO: printf ("FE_TOWARDZERO"); break;
default: printf ("unknown");
};
printf("\n");
}
void show_fe_environment(void)
{
show_fe_exceptions();
show_fe_rounding_method();
}
int main()
{
printf("On startup:\n");
show_fe_environment();
// Change environment
fesetround(FE_DOWNWARD); // change rounding mode
feraiseexcept(FE_INVALID); // raise exception
printf("\nBefore restoration:\n");
show_fe_environment();
fesetenv(FE_DFL_ENV); // restore
printf("\nAfter restoring default environment:\n");
show_fe_environment();
}
```
Output:
```
On startup:
current exceptions raised: none
current rounding method: FE_TONEAREST
Before restoration:
current exceptions raised: FE_INVALID
current rounding method: FE_DOWNWARD
After restoring default environment:
current exceptions raised: none
current rounding method: FE_TONEAREST
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.6/9 Floating-point environment <fenv.h> (p: 208)
* C99 standard (ISO/IEC 9899:1999):
+ 7.6/8 Floating-point environment <fenv.h> (p: 188-189)
### See also
| | |
| --- | --- |
| [fegetenvfesetenv](feenv "c/numeric/fenv/feenv")
(C99) | saves or restores the current floating-point environment (function) |
| [feupdateenv](feupdateenv "c/numeric/fenv/feupdateenv")
(C99) | restores the floating-point environment and raises the previously raise exceptions (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/fenv/FE_DFL_ENV "cpp/numeric/fenv/FE DFL ENV") for `FE_DFL_ENV` |
c fpclassify fpclassify
==========
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define fpclassify(arg) /* implementation defined */
```
| | (since C99) |
Categorizes floating point value `arg` into the following categories: zero, subnormal, normal, infinite, NAN, or implementation-defined category. The macro returns an integral value.
`[FLT\_EVAL\_METHOD](../../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")` is ignored: even if the argument is evaluated with more range and precision than its type, it is first converted to its semantic type, and the classification is based on that: a normal long double value might become subnormal when converted to double and zero when converted to float.
### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
One of `[FP\_INFINITE](fp_categories "c/numeric/math/FP categories")`, `[FP\_NAN](fp_categories "c/numeric/math/FP categories")`, `[FP\_NORMAL](fp_categories "c/numeric/math/FP categories")`, `[FP\_SUBNORMAL](fp_categories "c/numeric/math/FP categories")`, `[FP\_ZERO](fp_categories "c/numeric/math/FP categories")` or implementation-defined type, specifying the category of `arg`.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
const char *show_classification(double x) {
switch(fpclassify(x)) {
case FP_INFINITE: return "Inf";
case FP_NAN: return "NaN";
case FP_NORMAL: return "normal";
case FP_SUBNORMAL: return "subnormal";
case FP_ZERO: return "zero";
default: return "unknown";
}
}
int main(void)
{
printf("1.0/0.0 is %s\n", show_classification(1/0.0));
printf("0.0/0.0 is %s\n", show_classification(0.0/0.0));
printf("DBL_MIN/2 is %s\n", show_classification(DBL_MIN/2));
printf("-0.0 is %s\n", show_classification(-0.0));
printf("1.0 is %s\n", show_classification(1.0));
}
```
Output:
```
1.0/0.0 is Inf
0.0/0.0 is NaN
DBL_MIN/2 is subnormal
-0.0 is zero
1.0 is normal
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.3.1 The fpclassify macro (p: 235)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.3.1 The fpclassify macro (p: 216)
### See also
| | |
| --- | --- |
| [isfinite](isfinite "c/numeric/math/isfinite")
(C99) | checks if the given number has finite value (function macro) |
| [isinf](isinf "c/numeric/math/isinf")
(C99) | checks if the given number is infinite (function macro) |
| [isnan](isnan "c/numeric/math/isnan")
(C99) | checks if the given number is NaN (function macro) |
| [isnormal](isnormal "c/numeric/math/isnormal")
(C99) | checks if the given number is normal (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/fpclassify "cpp/numeric/math/fpclassify") for `fpclassify` |
c remquo, remquof, remquol remquo, remquof, remquol
========================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float remquof( float x, float y, int *quo );
```
| (1) | (since C99) |
|
```
double remquo( double x, double y, int *quo );
```
| (2) | (since C99) |
|
```
long double remquol( long double x, long double y, int *quo );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define remquo( x, y, quo )
```
| (4) | (since C99) |
1-3) Computes the floating-point remainder of the division operation `x/y` as the `[remainder()](remainder "c/numeric/math/remainder")` function does. Additionally, the sign and at least the three of the last bits of `x/y` will be stored in `quo`, sufficient to determine the octant of the result within a period.
4) Type-generic macro: If any non-pointer argument has type `long double`, `remquol` is called. Otherwise, if any non-pointer argument has integer type or has type `double`, `remquo` is called. Otherwise, `remquof` is called. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | floating point values |
| quo | - | pointer to an integer value to store the sign and some bits of `x/y` |
### Return value
If successful, returns the floating-point remainder of the division `x/y` as defined in `[remainder](remainder "c/numeric/math/remainder")`, and stores, in `*quo`, the sign and at least three of the least significant bits of `x/y` (formally, stores a value whose sign is the sign of `x/y` and whose magnitude is congruent modulo 2n
to the magnitude of the integral quotient of `x/y`, where n is an implementation-defined integer greater than or equal to 3).
If `y` is zero, the value stored in `*quo` is unspecified.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result is returned if subnormals are supported.
If `y` is zero, but the domain error does not occur, zero is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
Domain error may occur if `y` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* The current [rounding mode](../fenv/fe_round "c/numeric/fenv/FE round") has no effect.
* `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is never raised
* If `x` is ±∞ and `y` is not NaN, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `y` is ±0 and `x` is not NaN, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If either `x` or `y` is NaN, NaN is returned
### Notes
[POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/remquo.html) that a domain error occurs if `x` is infinite or `y` is zero.
This function is useful when implementing periodic functions with the period exactly representable as a floating-point value: when calculating sin(πx) for a very large `x`, calling `[sin](sin "c/numeric/math/sin")` directly may result in a large error, but if the function argument is first reduced with `remquo`, the low-order bits of the quotient may be used to determine the sign and the octant of the result within the period, while the remainder may be used to calculate the value with high precision.
On some platforms this operation is supported by hardware (and, for example, on Intel CPU, `FPREM1` leaves exactly 3 bits of precision in the quotient).
### Example
```
#include <stdio.h>
#include <math.h>
#include <fenv.h>
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
double cos_pi_x_naive(double x)
{
const double pi = acos(-1);
return cos(pi * x);
}
// the period is 2, values are (0;0.5) positive, (0.5;1.5) negative, (1.5,2) positive
double cos_pi_x_smart(double x)
{
const double pi = acos(-1);
int extremum;
double rem = remquo(x, 1, &extremum);
extremum = (unsigned)extremum % 2; // keep 1 bit to determine nearest extremum
return extremum ? -cos(pi * rem) : cos(pi * rem);
}
int main(void)
{
printf("cos(pi * 0.25) = %f\n", cos_pi_x_naive(0.25));
printf("cos(pi * 1.25) = %f\n", cos_pi_x_naive(1.25));
printf("cos(pi * 1000000000000.25) = %f\n", cos_pi_x_naive(1000000000000.25));
printf("cos(pi * 1000000000001.25) = %f\n", cos_pi_x_naive(1000000000001.25));
printf("cos(pi * 1000000000000.25) = %f\n", cos_pi_x_smart(1000000000000.25));
printf("cos(pi * 1000000000001.25) = %f\n", cos_pi_x_smart(1000000000001.25));
// error handling
feclearexcept(FE_ALL_EXCEPT);
int quo;
printf("remquo(+Inf, 1) = %.1f\n", remquo(INFINITY, 1, &quo));
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
}
```
Possible output:
```
cos(pi * 0.25) = 0.707107
cos(pi * 1.25) = -0.707107
cos(pi * 1000000000000.25) = 0.707123
cos(pi * 1000000000001.25) = -0.707117
cos(pi * 1000000000000.25) = 0.707107
cos(pi * 1000000000001.25) = -0.707107
remquo(+Inf, 1) = -nan
FE_INVALID raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.10.3 The remquo functions (p: 186)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.7.3 The remquo functions (p: 385)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.10.3 The remquo functions (p: 255)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.7.3 The remquo functions (p: 529)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.10.3 The remquo functions (p: 236)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.7.3 The remquo functions (p: 465)
### See also
| | |
| --- | --- |
| [divldivlldiv](div "c/numeric/math/div")
(C99) | computes quotient and remainder of integer division (function) |
| [fmodfmodffmodl](fmod "c/numeric/math/fmod")
(C99)(C99) | computes remainder of the floating-point division operation (function) |
| [remainderremainderfremainderl](remainder "c/numeric/math/remainder")
(C99)(C99)(C99) | computes signed remainder of the floating-point division operation (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/remquo "cpp/numeric/math/remquo") for `remquo` |
c INFINITY INFINITY
========
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define INFINITY /*implementation defined*/
```
| | (since C99) |
If the implementation supports floating-point infinities, the macro `INFINITY` expands to constant expression of type `float` which evaluates to positive or unsigned infinity.
If the implementation does not support floating-point infinities, the macro `INFINITY` expands to a positive value that is guaranteed to overflow a `float` at compile time, and the use of this macro generates a compiler warning.
The style used to print an infinity is implementation defined.
### Example
Show style used to print an infinity and IEEE format.
```
#include <stdio.h>
#include <math.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
int main(void)
{
double f = INFINITY;
uint64_t fn; memcpy(&fn, &f, sizeof f);
printf("INFINITY: %f %" PRIx64 "\n", f, fn);
}
```
Possible output:
```
INFINITY: inf 7ff0000000000000
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12/4 INFINITY (p: 231-232)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12/4 INFINITY (p: 212-213)
### See also
| | |
| --- | --- |
| [isinf](isinf "c/numeric/math/isinf")
(C99) | checks if the given number is infinite (function macro) |
| [HUGE\_VALFHUGE\_VALHUGE\_VALL](huge_val "c/numeric/math/HUGE VAL")
(C99)(C99) | indicates value too big to be representable (infinity) by `float`, `double` and `long double` respectively (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/INFINITY "cpp/numeric/math/INFINITY") for `INFINITY` |
c atan, atanf, atanl atan, atanf, atanl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float atanf( float arg );
```
| (1) | (since C99) |
|
```
double atan( double arg );
```
| (2) | |
|
```
long double atanl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define atan( arg )
```
| (4) | (since C99) |
1-3) Computes the principal value of the arc tangent of `arg`.
4) Type-generic macro: If the argument has type `long double`, `atanl` is called. Otherwise, if the argument has integer type or the type `double`, `atan` is called. Otherwise, `atanf` is called. If the argument is complex, then the macro invokes the corresponding complex function (`[catanf](http://en.cppreference.com/w/c/numeric/complex/catan)`, `[catan](http://en.cppreference.com/w/c/numeric/complex/catan)`, `[catanl](http://en.cppreference.com/w/c/numeric/complex/catan)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the arc tangent of `arg` (arctan(arg)) in the range [- π/2 ; +π/2] radians, is returned. If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ±0, it is returned unmodified
* If the argument is +∞, +π/2 is returned
* If the argument is -∞, -π/2 is returned
* if the argument is NaN, NaN is returned
### Notes
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/atan.html) that in case of underflow, `arg` is returned unmodified, and if that is not supported, an implementation-defined value no greater than DBL\_MIN, FLT\_MIN, and LDBL\_MIN is returned.
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("atan(1) = %f, 4*atan(1)=%f\n", atan(1), 4*atan(1));
// special values
printf("atan(Inf) = %f, 2*atan(Inf) = %f\n", atan(INFINITY), 2*atan(INFINITY));
printf("atan(-0.0) = %+f, atan(+0.0) = %+f\n", atan(-0.0), atan(0));
}
```
Output:
```
atan(1) = 0.785398, 4*atan(1)=3.141593
atan(Inf) = 1.570796, 2*atan(Inf) = 3.141593
atan(-0.0) = -0.000000, atan(+0.0) = +0.000000
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.4.3 The atan functions (p: 238-239)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.1.3 The atan functions (p: 519)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.4.3 The atan functions (p: 219)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.1.3 The atan functions (p: 456)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.2.3 The atan function
### See also
| | |
| --- | --- |
| [atan2atan2fatan2l](atan2 "c/numeric/math/atan2")
(C99)(C99) | computes arc tangent, using signs to determine quadrants (function) |
| [asinasinfasinl](asin "c/numeric/math/asin")
(C99)(C99) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) |
| [acosacosfacosl](acos "c/numeric/math/acos")
(C99)(C99) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [tantanftanl](tan "c/numeric/math/tan")
(C99)(C99) | computes tangent (\({\small\tan{x} }\)tan(x)) (function) |
| [catancatanfcatanl](../complex/catan "c/numeric/complex/catan")
(C99)(C99)(C99) | computes the complex arc tangent (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/atan "cpp/numeric/math/atan") for `atan` |
c asin, asinf, asinl asin, asinf, asinl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float asinf( float arg );
```
| (1) | (since C99) |
|
```
double asin( double arg );
```
| (2) | |
|
```
long double asinl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define asin( arg )
```
| (4) | (since C99) |
1-3) Computes the principal values of the arc sine of `arg`.
4) Type-generic macro: If the argument has type `long double`, `asinl` is called. Otherwise, if the argument has integer type or the type `double`, `asin` is called. Otherwise, `asinf` is called. If the argument is complex, then the macro invokes the corresponding complex function (`[casinf](http://en.cppreference.com/w/c/numeric/complex/casin)`, `[casin](http://en.cppreference.com/w/c/numeric/complex/casin)`, `[casinl](http://en.cppreference.com/w/c/numeric/complex/casin)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the arc sine of `arg` (arcsin(arg)) in the range [-π/2 ; +π/2], is returned. If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
Domain error occurs if `arg` is outside the range `[-1.0; 1.0]`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ±0, it is returned unmodified
* If |arg| > 1, a domain error occurs and NaN is returned.
* if the argument is NaN, NaN is returned
### Example
```
#include <math.h>
#include <stdio.h>
#include <errno.h>
#include <fenv.h>
#include <string.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
printf("asin( 1.0) = %+f, 2*asin( 1.0)=%+f\n", asin(1), 2*asin(1));
printf("asin(-0.5) = %+f, 6*asin(-0.5)=%+f\n", asin(-0.5), 6*asin(-0.5));
// special values
printf("asin(0.0) = %1f, asin(-0.0)=%f\n", asin(+0.0), asin(-0.0));
// error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("asin(1.1) = %f\n", asin(1.1));
if(errno == EDOM) perror(" errno == EDOM");
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
}
```
Possible output:
```
asin( 1.0) = +1.570796, 2*asin( 1.0)=+3.141593
asin(-0.5) = -0.523599, 6*asin(-0.5)=-3.141593
asin(0.0) = 0.000000, asin(-0.0)=-0.000000
asin(1.1) = nan
errno == EDOM: Numerical argument out of domain
FE_INVALID raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.4.2 The asin functions (p: 238)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.1.2 The asin functions (p: 518)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.4.2 The asin functions (p: 219)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.1.2 The asin functions (p: 456)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.2.2 The asin function
### See also
| | |
| --- | --- |
| [acosacosfacosl](acos "c/numeric/math/acos")
(C99)(C99) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [atanatanfatanl](atan "c/numeric/math/atan")
(C99)(C99) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [atan2atan2fatan2l](atan2 "c/numeric/math/atan2")
(C99)(C99) | computes arc tangent, using signs to determine quadrants (function) |
| [sinsinfsinl](sin "c/numeric/math/sin")
(C99)(C99) | computes sine (\({\small\sin{x} }\)sin(x)) (function) |
| [casincasinfcasinl](../complex/casin "c/numeric/complex/casin")
(C99)(C99)(C99) | computes the complex arc sine (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/asin "cpp/numeric/math/asin") for `asin` |
| programming_docs |
c cosh, coshf, coshl cosh, coshf, coshl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float coshf( float arg );
```
| (1) | (since C99) |
|
```
double cosh( double arg );
```
| (2) | |
|
```
long double coshl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define cosh( arg )
```
| (4) | (since C99) |
1-3) Computes the hyperbolic cosine of `arg`.
4) Type-generic macro: If the argument has type `long double`, `coshl` is called. Otherwise, if the argument has integer type or the type `double`, `cosh` is called. Otherwise, `coshf` is called. If the argument is complex, then the macro invokes the corresponding complex function (`[ccoshf](http://en.cppreference.com/w/c/numeric/complex/ccosh)`, `[ccosh](http://en.cppreference.com/w/c/numeric/complex/ccosh)`, `[ccoshl](http://en.cppreference.com/w/c/numeric/complex/ccosh)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value representing a hyperbolic angle |
### Return value
If no errors occur, the hyperbolic cosine of `arg` (cosh(arg), or earg+e-arg/2) is returned. If a range error due to overflow occurs, `[+HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ±0, 1 is returned
* If the argument is ±∞, +∞ is returned
* if the argument is NaN, NaN is returned
### Notes
For the IEEE-compatible type `double`, if |arg| > 710.5, then `cosh(arg)` overflows.
### Example
```
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
printf("cosh(1) = %f\ncosh(-1)= %f\n", cosh(1), cosh(-1));
printf("log(sinh(1) + cosh(1))=%f\n", log(sinh(1)+cosh(1)));
// special values
printf("cosh(+0) = %f\ncosh(-0) = %f\n", cosh(0.0), cosh(-0.0));
// error handling
errno=0; feclearexcept(FE_ALL_EXCEPT);
printf("cosh(710.5) = %f\n", cosh(710.5));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_OVERFLOW)) puts(" FE_OVERFLOW raised");
}
```
Possible output:
```
cosh(1) = 1.543081
cosh(-1)= 1.543081
log(sinh(1) + cosh(1))=1.000000
cosh(+0) = 1.000000
cosh(-0) = 1.000000
cosh(710.5) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.5.4 The cosh functions (p: 176)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.2.4 The cosh functions (p: 379)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.5.4 The cosh functions (p: 241)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.2.4 The cosh functions (p: 520)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.5.4 The cosh functions (p: 222)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.2.4 The cosh functions (p: 457)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.3.1 The cosh function
### See also
| | |
| --- | --- |
| [sinhsinhfsinhl](sinh "c/numeric/math/sinh")
(C99)(C99) | computes hyperbolic sine (\({\small\sinh{x} }\)sinh(x)) (function) |
| [tanhtanhftanhl](tanh "c/numeric/math/tanh")
(C99)(C99) | computes hyperbolic tangent (\({\small\tanh{x} }\)tanh(x)) (function) |
| [acoshacoshfacoshl](acosh "c/numeric/math/acosh")
(C99)(C99)(C99) | computes inverse hyperbolic cosine (\({\small\operatorname{arcosh}{x} }\)arcosh(x)) (function) |
| [ccoshccoshfccoshl](../complex/ccosh "c/numeric/complex/ccosh")
(C99)(C99)(C99) | computes the complex hyperbolic cosine (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/cosh "cpp/numeric/math/cosh") for `cosh` |
c isgreater isgreater
=========
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define isgreater(x, y) /* implementation defined */
```
| | (since C99) |
Determines if the floating point number `x` is greater than the floating-point number (`y`), without setting floating-point exceptions.
### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
Nonzero integral value if `x > y`, `0` otherwise.
### Notes
The built-in `operator>` for floating-point numbers may set `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` if one or both of the arguments is NaN. This function is a "quiet" version of `operator>`.
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("isgreater(2.0,1.0) = %d\n", isgreater(2.0,1.0));
printf("isgreater(1.0,2.0) = %d\n", isgreater(1.0,2.0));
printf("isgreater(INFINITY,1.0) = %d\n", isgreater(INFINITY,1.0));
printf("isgreater(1.0,NAN) = %d\n", isgreater(1.0,NAN));
return 0;
}
```
Possible output:
```
isgreater(2.0,1.0) = 1
isgreater(1.0,2.0) = 0
isgreater(INFINITY,1.0) = 1
isgreater(1.0,NAN) = 0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.14.1 The isgreater macro (p: 259)
+ F.10.11 Comparison macros (p: 531)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.14.1 The isgreater macro (p: 240)
### See also
| | |
| --- | --- |
| [isless](isless "c/numeric/math/isless")
(C99) | checks if the first floating-point argument is less than the second (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/isgreater "cpp/numeric/math/isgreater") for `isgreater` |
c rint, rintf, rintl, lrint, lrintf, lrintl, llrint, llrintf, llrintl rint, rintf, rintl, lrint, lrintf, lrintl, llrint, llrintf, llrintl
===================================================================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float rintf( float arg );
```
| (1) | (since C99) |
|
```
double rint( double arg );
```
| (2) | (since C99) |
|
```
long double rintl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define rint( arg )
```
| (4) | (since C99) |
| Defined in header `<math.h>` | | |
|
```
long lrintf( float arg );
```
| (5) | (since C99) |
|
```
long lrint( double arg );
```
| (6) | (since C99) |
|
```
long lrintl( long double arg );
```
| (7) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define lrint( arg )
```
| (8) | (since C99) |
| Defined in header `<math.h>` | | |
|
```
long long llrintf( float arg );
```
| (9) | (since C99) |
|
```
long long llrint( double arg );
```
| (10) | (since C99) |
|
```
long long llrintl( long double arg );
```
| (11) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define llrint( arg )
```
| (12) | (since C99) |
1-3) Rounds the floating-point argument `arg` to an integer value in floating-point format, using the current rounding mode.
5-7, 9-11) Rounds the floating-point argument `arg` to an integer value in integer format, using the current rounding mode.
4,8,12) Type-generic macros: If `arg` has type `long double`, `rintl`, `lrintl`, `llrintl` is called. Otherwise, if `arg` has integer type or the type `double`, `rint`, `lrint`, `llrint` is called. Otherwise, `rintf`, `lrintf`, `llrintf` is called, respectively. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the nearest integer value to `arg`, according to the [current rounding mode](../fenv/fe_round "c/numeric/fenv/FE round"), is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the result of `lrint` or `llrint` is outside the range representable by the return type, a domain error or a range error may occur.
If the implementation supports IEEE floating-point arithmetic (IEC 60559), For the `rint` function:
* If `arg` is ±∞, it is returned, unmodified
* If `arg` is ±0, it is returned, unmodified
* If `arg` is NaN, NaN is returned
For `lrint` and `llrint` functions: * If `arg` is ±∞, `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised and an implementation-defined value is returned
* If the result of the rounding is outside the range of the return type, `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised and an implementation-defined value is returned
* If `arg` is NaN, `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised and an implementation-defined value is returned
### Notes
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/lrint.html) that all cases where `lrint` or `llrint` raise `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` are domain errors.
As specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling"), `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be (but isn't required to be on non-IEEE floating-point platforms) raised by `rint` when rounding a non-integer finite value.
The only difference between `rint` and `[nearbyint](nearbyint "c/numeric/math/nearbyint")` is that `[nearbyint](nearbyint "c/numeric/math/nearbyint")` never raises `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")`.
The largest representable floating-point values are exact integers in all standard floating-point formats, so `rint` never overflows on its own; however the result may overflow any integer type (including `[intmax\_t](../../types/integer "c/types/integer")`), when stored in an integer variable.
If the current rounding mode is...
* `[FE\_DOWNWARD](../fenv/fe_round "c/numeric/fenv/FE round")`, then `rint` is equivalent to `[floor](floor "c/numeric/math/floor")`.
* `[FE\_UPWARD](../fenv/fe_round "c/numeric/fenv/FE round")`, then `rint` is equivalent to `[ceil](ceil "c/numeric/math/ceil")`.
* `[FE\_TOWARDZERO](../fenv/fe_round "c/numeric/fenv/FE round")`, then `rint` is equivalent to `[trunc](trunc "c/numeric/math/trunc")`
* `[FE\_TONEAREST](../fenv/fe_round "c/numeric/fenv/FE round")`, then `rint` differs from `[round](round "c/numeric/math/round")` in that halfway cases are rounded to even rather than away from zero.
### Example
```
#include <stdio.h>
#include <math.h>
#include <fenv.h>
#include <limits.h>
int main(void)
{
#pragma STDC FENV_ACCESS ON
fesetround(FE_TONEAREST);
printf("rounding to nearest (halfway cases to even):\n"
"rint(+2.3) = %+.1f ", rint(2.3));
printf("rint(+2.5) = %+.1f ", rint(2.5));
printf("rint(+3.5) = %+.1f\n", rint(3.5));
printf("rint(-2.3) = %+.1f ", rint(-2.3));
printf("rint(-2.5) = %+.1f ", rint(-2.5));
printf("rint(-3.5) = %+.1f\n", rint(-3.5));
fesetround(FE_DOWNWARD);
printf("rounding down: \nrint(+2.3) = %+.1f ", rint(2.3));
printf("rint(+2.5) = %+.1f ", rint(2.5));
printf("rint(+3.5) = %+.1f\n", rint(3.5));
printf("rint(-2.3) = %+.1f ", rint(-2.3));
printf("rint(-2.5) = %+.1f ", rint(-2.5));
printf("rint(-3.5) = %+.1f\n", rint(-3.5));
printf("rounding down with lrint: \nlrint(+2.3) = %ld ", lrint(2.3));
printf("lrint(+2.5) = %ld ", lrint(2.5));
printf("lrint(+3.5) = %ld\n", lrint(3.5));
printf("lrint(-2.3) = %ld ", lrint(-2.3));
printf("lrint(-2.5) = %ld ", lrint(-2.5));
printf("lrint(-3.5) = %ld\n", lrint(-3.5));
printf("lrint(-0.0) = %ld\n", lrint(-0.0));
printf("lrint(-Inf) = %ld\n", lrint(-INFINITY)); // FE_INVALID raised
// error handling
feclearexcept(FE_ALL_EXCEPT);
printf("rint(1.1) = %.1f\n", rint(1.1));
if(fetestexcept(FE_INEXACT)) puts(" FE_INEXACT was raised");
feclearexcept(FE_ALL_EXCEPT);
printf("lrint(LONG_MIN-2048.0) = %ld\n", lrint(LONG_MIN-2048.0));
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID was raised");
}
```
Possible output:
```
rounding to nearest (halfway cases to even):
rint(+2.3) = +2.0 rint(+2.5) = +2.0 rint(+3.5) = +4.0
rint(-2.3) = -2.0 rint(-2.5) = -2.0 rint(-3.5) = -4.0
rounding down:
rint(+2.3) = +2.0 rint(+2.5) = +2.0 rint(+3.5) = +3.0
rint(-2.3) = -3.0 rint(-2.5) = -3.0 rint(-3.5) = -4.0
rounding down with lrint:
lrint(+2.3) = 2 lrint(+2.5) = 2 lrint(+3.5) = 3
lrint(-2.3) = -3 lrint(-2.5) = -3 lrint(-3.5) = -4
lrint(-0.0) = 0
lrint(-Inf) = -9223372036854775808
rint(1.1) = 1.0
FE_INEXACT was raised
lrint(LONG_MIN-2048.0) = -9223372036854775808
FE_INVALID was raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.9.4 The rint functions (p: 184)
+ 7.12.9.5 The lrint and llrint functions (p: 184)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.6.4 The rint functions (p: 384)
+ F.10.6.5 The lrint and llrint functions (p: 384)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.9.4 The rint functions (p: 252)
+ 7.12.9.5 The lrint and llrint functions (p: 252)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.6.4 The rint functions (p: 527)
+ F.10.6.5 The lrint and llrint functions (p: 527)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.9.4 The rint functions (p: 232-233)
+ 7.12.9.5 The lrint and llrint functions (p: 233)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.6.4 The rint functions (p: 463)
+ F.9.6.5 The lrint and llrint functions (p: 463)
### See also
| | |
| --- | --- |
| [trunctruncftruncl](trunc "c/numeric/math/trunc")
(C99)(C99)(C99) | rounds to nearest integer not greater in magnitude than the given value (function) |
| [nearbyintnearbyintfnearbyintl](nearbyint "c/numeric/math/nearbyint")
(C99)(C99)(C99) | rounds to an integer using current rounding mode (function) |
| [fegetroundfesetround](../fenv/feround "c/numeric/fenv/feround")
(C99)(C99) | gets or sets rounding direction (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/rint "cpp/numeric/math/rint") for `rint` |
c asinh, asinhf, asinhl asinh, asinhf, asinhl
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float asinhf( float arg );
```
| (1) | (since C99) |
|
```
double asinh( double arg );
```
| (2) | (since C99) |
|
```
long double asinhl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define asinh( arg )
```
| (4) | (since C99) |
1-3) Computes the inverse hyperbolic sine of `arg`.
4) Type-generic macro: If the argument has type `long double`, `asinhl` is called. Otherwise, if the argument has integer type or the type `double`, `asinh` is called. Otherwise, `asinhf` is called. If the argument is complex, then the macro invokes the corresponding complex function (`[casinhf](http://en.cppreference.com/w/c/numeric/complex/casinh)`, `[casinh](http://en.cppreference.com/w/c/numeric/complex/casinh)`, `[casinhl](http://en.cppreference.com/w/c/numeric/complex/casinh)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value representing the area of a hyperbolic sector |
### Return value
If no errors occur, the inverse hyperbolic sine of `arg` (sinh-1
(arg), or arsinh(arg)), is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ±0 or ±∞, it is returned unmodified
* if the argument is NaN, NaN is returned
### Notes
Although the C standard names this function "arc hyperbolic sine", the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct name is "inverse hyperbolic sine" (used by POSIX) or "area hyperbolic sine".
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("asinh(1) = %f\nasinh(-1) = %f\n", asinh(1), asinh(-1));
// special values
printf("asinh(+0) = %f\nasinh(-0) = %f\n", asinh(0.0), asinh(-0.0));
}
```
Output:
```
asinh(1) = 0.881374
asinh(-1) = -0.881374
asinh(+0) = 0.000000
asinh(-0) = -0.000000
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.5.2 The asinh functions (p: 240-241)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.2.2 The asinh functions (p: 520)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.5.2 The asinh functions (p: 221)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.2.2 The asinh functions (p: 457)
### See also
| | |
| --- | --- |
| [acoshacoshfacoshl](acosh "c/numeric/math/acosh")
(C99)(C99)(C99) | computes inverse hyperbolic cosine (\({\small\operatorname{arcosh}{x} }\)arcosh(x)) (function) |
| [atanhatanhfatanhl](atanh "c/numeric/math/atanh")
(C99)(C99)(C99) | computes inverse hyperbolic tangent (\({\small\operatorname{artanh}{x} }\)artanh(x)) (function) |
| [sinhsinhfsinhl](sinh "c/numeric/math/sinh")
(C99)(C99) | computes hyperbolic sine (\({\small\sinh{x} }\)sinh(x)) (function) |
| [casinhcasinhfcasinhl](../complex/casinh "c/numeric/complex/casinh")
(C99)(C99)(C99) | computes the complex arc hyperbolic sine (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/asinh "cpp/numeric/math/asinh") for `asinh` |
### External links
[Weisstein, Eric W. "Inverse Hyperbolic Sine."](http://mathworld.wolfram.com/InverseHyperbolicSine.html) From MathWorld--A Wolfram Web Resource.
c trunc, truncf, truncl trunc, truncf, truncl
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float truncf( float arg );
```
| (1) | (since C99) |
|
```
double trunc( double arg );
```
| (2) | (since C99) |
|
```
long double truncl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define trunc( arg )
```
| (4) | (since C99) |
1-3) Computes the nearest integer not greater in magnitude than `arg`.
4) Type-generic macro: If `arg` has type `long double`, `truncl` is called. Otherwise, if `arg` has integer type or the type `double`, `trunc` is called. Otherwise, `truncf` is called. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the nearest integer value not greater in magnitude than `arg` (in other words, `arg` rounded towards zero), is returned.
Return value ![math-trunc.svg]() Argument ### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* The current [rounding mode](../fenv/fe_round "c/numeric/fenv/FE round") has no effect.
* If `arg` is ±∞, it is returned, unmodified
* If `arg` is ±0, it is returned, unmodified
* If arg is NaN, NaN is returned
### Notes
`[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be (but isn't required to be) raised when truncating a non-integer finite value.
The largest representable floating-point values are exact integers in all standard floating-point formats, so this function never overflows on its own; however the result may overflow any integer type (including `[intmax\_t](../../types/integer "c/types/integer")`), when stored in an integer variable.
The implicit conversion from floating-point to integral types also rounds towards zero, but is limited to the values that can be represented by the target type.
### Example
```
#include <math.h>
#include <stdio.h>
int main(void)
{
printf("trunc(+2.7) = %+.1f\n", trunc(2.7));
printf("trunc(-2.7) = %+.1f\n", trunc(-2.7));
printf("trunc(-0.0) = %+.1f\n", trunc(-0.0));
printf("trunc(-Inf) = %+f\n", trunc(-INFINITY));
}
```
Possible output:
```
trunc(+2.7) = +2.0
trunc(-2.7) = -2.0
trunc(-0.0) = -0.0
trunc(-Inf) = -inf
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.9.8 The trunc functions (p: 253-254)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.6.8 The trunc functions (p: 528)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.9.8 The trunc functions (p: 234)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.6.8 The trunc functions (p: 464)
### See also
| | |
| --- | --- |
| [floorfloorffloorl](floor "c/numeric/math/floor")
(C99)(C99) | computes largest integer not greater than the given value (function) |
| [ceilceilfceill](ceil "c/numeric/math/ceil")
(C99)(C99) | computes smallest integer not less than the given value (function) |
| [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](round "c/numeric/math/round")
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) | rounds to nearest integer, rounding away from zero in halfway cases (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/trunc "cpp/numeric/math/trunc") for `trunc` |
| programming_docs |
c log2, log2f, log2l log2, log2f, log2l
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float log2f( float arg );
```
| (1) | (since C99) |
|
```
double log2( double arg );
```
| (2) | (since C99) |
|
```
long double log2l( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define log2( arg )
```
| (4) | (since C99) |
1-3) Computes the base `2` logarithm of `arg`.
4) Type-generic macro: If `arg` has type `long double`, `log2l` is called. Otherwise, if `arg` has integer type or the type `double`, `log2` is called. Otherwise, `log2f` is called. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the base-*2* logarithm of `arg` (log
2(arg) or lb(arg)) is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a pole error occurs, `[-HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `-HUGE_VALF`, or `-HUGE_VALL` is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
Domain error occurs if `arg` is less than zero.
Pole error may occur if `arg` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ±0, -∞ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* If the argument is 1, +0 is returned
* If the argument is negative, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* If the argument is +∞, +∞ is returned
* If the argument is NaN, NaN is returned
### Notes
For integer `arg`, the binary logarithm can be interpreted as the zero-based index of the most significant 1 bit in the input.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
printf("log2(65536) = %f\n", log2(65536));
printf("log2(0.125) = %f\n", log2(0.125));
printf("log2(0x020f) = %f (highest set bit is in position 9)\n", log2(0x020f));
printf("base-5 logarithm of 125 = %f\n", log2(125)/log2(5));
// special values
printf("log2(1) = %f\n", log2(1));
printf("log2(+Inf) = %f\n", log2(INFINITY));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("log2(0) = %f\n", log2(0));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_DIVBYZERO)) puts(" FE_DIVBYZERO raised");
}
```
Possible output:
```
log2(65536) = 16.000000
log2(0.125) = -3.000000
log2(0x020f) = 9.041659 (highest set bit is in position 9)
base-5 logarithm of 125 = 3.000000
log2(1) = 0.000000
log2(+Inf) = inf
log2(0) = -inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.6.10 The log2 functions (p: 179)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.3.10 The log2 functions (p: 381)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.6.10 The log2 functions (p: 246)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.10 The log2 functions (p: 522)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.6.10 The log2 functions (p: 226)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.3.10 The log2 functions (p: 459)
### See also
| | |
| --- | --- |
| [loglogflogl](log "c/numeric/math/log")
(C99)(C99) | computes natural (base-*e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [log10log10flog10l](log10 "c/numeric/math/log10")
(C99)(C99) | computes common (base-*10*) logarithm (\({\small \log\_{10}{x} }\)log10(x)) (function) |
| [log1plog1pflog1pl](log1p "c/numeric/math/log1p")
(C99)(C99)(C99) | computes natural (base-*e*) logarithm of 1 plus the given number (\({\small \ln{(1+x)} }\)ln(1+x)) (function) |
| [exp2exp2fexp2l](exp2 "c/numeric/math/exp2")
(C99)(C99)(C99) | computes *2* raised to the given power (\({\small 2^x}\)2x) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/log2 "cpp/numeric/math/log2") for `log2` |
c round, roundf, roundl, lround, lroundf, lroundl, llround, llroundf, llroundl round, roundf, roundl, lround, lroundf, lroundl, llround, llroundf, llroundl
============================================================================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float roundf( float arg );
```
| (1) | (since C99) |
|
```
double round( double arg );
```
| (2) | (since C99) |
|
```
long double roundl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define round( arg )
```
| (4) | (since C99) |
| Defined in header `<math.h>` | | |
|
```
long lroundf( float arg );
```
| (5) | (since C99) |
|
```
long lround( double arg );
```
| (6) | (since C99) |
|
```
long lroundl( long double arg );
```
| (7) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define lround( arg )
```
| (8) | (since C99) |
| Defined in header `<math.h>` | | |
|
```
long long llroundf( float arg );
```
| (9) | (since C99) |
|
```
long long llround( double arg );
```
| (10) | (since C99) |
|
```
long long llroundl( long double arg );
```
| (11) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define llround( arg )
```
| (12) | (since C99) |
1-3) Computes the nearest integer value to `arg` (in floating-point format), rounding halfway cases away from zero, regardless of the current rounding mode.
5-7, 9-11) Computes the nearest integer value to `arg` (in integer format), rounding halfway cases away from zero, regardless of the current rounding mode.
4,8,12) Type-generic macros: If `arg` has type `long double`, `roundl`, `lroundl`, `llroundl` is called. Otherwise, if `arg` has integer type or the type `double`, `round`, `lround`, `llround` is called. Otherwise, `roundf`, `lroundf`, `llroundf` is called, respectively. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the nearest integer value to `arg`, rounding halfway cases away from zero, is returned.
Return value ![math-round away zero.svg]() Argument If a domain error occurs, an implementation-defined value is returned.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the result of `lround` or `llround` is outside the range representable by the return type, a domain error or a range error may occur.
If the implementation supports IEEE floating-point arithmetic (IEC 60559), For the `round`, `roundf`, and `roundl` function:
* The current [rounding mode](../fenv/fe_round "c/numeric/fenv/FE round") has no effect.
* If `arg` is ±∞, it is returned, unmodified
* If `arg` is ±0, it is returned, unmodified
* If `arg` is NaN, NaN is returned
For `lround` and `llround` families of functions: * `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is never raised
* The current [rounding mode](../fenv/fe_round "c/numeric/fenv/FE round") has no effect.
* If `arg` is ±∞, `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised and an implementation-defined value is returned
* If the result of the rounding is outside the range of the return type, `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised and an implementation-defined value is returned
* If `arg` is NaN, `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised and an implementation-defined value is returned
### Notes
`[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be (but isn't required to be) raised by `round` when rounding a non-integer finite value.
The largest representable floating-point values are exact integers in all standard floating-point formats, so `round` never overflows on its own; however the result may overflow any integer type (including `[intmax\_t](../../types/integer "c/types/integer")`), when stored in an integer variable.
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/lround.html) that all cases where `lround` or `llround` raise `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` are domain errors.
The `double` version of `round` behaves as if implemented as follows:
```
#include <math.h>
double round(double x)
{
return signbit(x) ? ceil(x - 0.5) : floor(x + 0.5);
}
```
### Example
```
#include <stdio.h>
#include <math.h>
#include <fenv.h>
#include <limits.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
// round
printf("round(+2.3) = %+.1f ", round(2.3));
printf("round(+2.5) = %+.1f ", round(2.5));
printf("round(+2.7) = %+.1f\n", round(2.7));
printf("round(-2.3) = %+.1f ", round(-2.3));
printf("round(-2.5) = %+.1f ", round(-2.5));
printf("round(-2.7) = %+.1f\n", round(-2.7));
printf("round(-0.0) = %+.1f\n", round(-0.0));
printf("round(-Inf) = %+f\n", round(-INFINITY));
// lround
printf("lround(+2.3) = %ld ", lround(2.3));
printf("lround(+2.5) = %ld ", lround(2.5));
printf("lround(+2.7) = %ld\n", lround(2.7));
printf("lround(-2.3) = %ld ", lround(-2.3));
printf("lround(-2.5) = %ld ", lround(-2.5));
printf("lround(-2.7) = %ld\n", lround(-2.7));
printf("lround(-0.0) = %ld\n", lround(-0.0));
printf("lround(-Inf) = %ld\n", lround(-INFINITY)); // FE_INVALID raised
// error handling
feclearexcept(FE_ALL_EXCEPT);
printf("lround(LONG_MAX+1.5) = %ld\n", lround(LONG_MAX+1.5));
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID was raised");
}
```
Possible output:
```
round(+2.3) = +2.0 round(+2.5) = +3.0 round(+2.7) = +3.0
round(-2.3) = -2.0 round(-2.5) = -3.0 round(-2.7) = -3.0
round(-0.0) = -0.0
round(-Inf) = -inf
lround(+2.3) = 2 lround(+2.5) = 3 lround(+2.7) = 3
lround(-2.3) = -2 lround(-2.5) = -3 lround(-2.7) = -3
lround(-0.0) = 0
lround(-Inf) = -9223372036854775808
lround(LONG_MAX+1.5) = -9223372036854775808
FE_INVALID was raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.9.6 The round functions (p: 184)
+ 7.12.9.7 The lround and llround functions (p: 184-185)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.6.6 The round functions (p: 384)
+ F.10.6.7 The lround and llround functions (p: 385)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.9.6 The round functions (p: 253)
+ 7.12.9.7 The lround and llround functions (p: 253)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.6.6 The round functions (p: 527)
+ F.10.6.7 The lround and llround functions (p: 528)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.9.6 The round functions (p: 233)
+ 7.12.9.7 The lround and llround functions (p: 234)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.6.6 The round functions (p: 464)
+ F.9.6.7 The lround and llround functions (p: 464)
### See also
| | |
| --- | --- |
| [floorfloorffloorl](floor "c/numeric/math/floor")
(C99)(C99) | computes largest integer not greater than the given value (function) |
| [ceilceilfceill](ceil "c/numeric/math/ceil")
(C99)(C99) | computes smallest integer not less than the given value (function) |
| [trunctruncftruncl](trunc "c/numeric/math/trunc")
(C99)(C99)(C99) | rounds to nearest integer not greater in magnitude than the given value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/round "cpp/numeric/math/round") for `round` |
c cos, cosf, cosl cos, cosf, cosl
===============
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float cosf( float arg );
```
| (1) | (since C99) |
|
```
double cos( double arg );
```
| (2) | |
|
```
long double cosl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define cos( arg )
```
| (4) | (since C99) |
1-3) Computes the cosine of `arg` (measured in radians).
4) Type-generic macro: If the argument has type `long double`, `cosl` is called. Otherwise, if the argument has integer type or the type `double`, `cos` is called. Otherwise, `cosf` is called. If the argument is complex, then the macro invokes the corresponding complex function (`[ccosf](http://en.cppreference.com/w/c/numeric/complex/ccos)`, `[ccos](http://en.cppreference.com/w/c/numeric/complex/ccos)`, `[ccosl](http://en.cppreference.com/w/c/numeric/complex/ccos)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value representing angle in radians |
### Return value
If no errors occur, the cosine of `arg` (cos(arg)) in the range [-1 ; +1], is returned.
| | |
| --- | --- |
| The result may have little or no significance if the magnitude of `arg` is large. | (until C++11) |
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ±0, the result is 1.0
* if the argument is ±∞, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* if the argument is NaN, NaN is returned
### Notes
The case where the argument is infinite is not specified to be a domain error in C, but it is defined as a [domain error in POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/cos.html).
### Example
```
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
double pi = acos(-1);
// typical usage
printf("cos(pi/3) = %f\n", cos(pi/3));
printf("cos(pi/2) = %f\n", cos(pi/2));
printf("cos(-3*pi/4) = %f\n", cos(-3*pi/4));
// special values
printf("cos(+0) = %f\n", cos(0.0));
printf("cos(-0) = %f\n", cos(-0.0));
// error handling
feclearexcept(FE_ALL_EXCEPT);
printf("cos(INFINITY) = %f\n", cos(INFINITY));
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
}
```
Possible output:
```
cos(pi/3) = 0.500000
cos(pi/2) = 0.000000
cos(-3*pi/4) = -0.707107
cos(+0) = 1.000000
cos(-0) = 1.000000
cos(INFINITY) = -nan
FE_INVALID raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.4.5 The cos functions (p: 239)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.1.5 The cos functions (p: 519)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.4.5 The cos functions (p: 220)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.1.5 The cos functions (p: 456)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.2.5 The cos function
### See also
| | |
| --- | --- |
| [sinsinfsinl](sin "c/numeric/math/sin")
(C99)(C99) | computes sine (\({\small\sin{x} }\)sin(x)) (function) |
| [tantanftanl](tan "c/numeric/math/tan")
(C99)(C99) | computes tangent (\({\small\tan{x} }\)tan(x)) (function) |
| [acosacosfacosl](acos "c/numeric/math/acos")
(C99)(C99) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [ccosccosfccosl](../complex/ccos "c/numeric/complex/ccos")
(C99)(C99)(C99) | computes the complex cosine (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/cos "cpp/numeric/math/cos") for `cos` |
c remainder, remainderf, remainderl remainder, remainderf, remainderl
=================================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float remainderf( float x, float y );
```
| (1) | (since C99) |
|
```
double remainder( double x, double y );
```
| (2) | (since C99) |
|
```
long double remainderl( long double x, long double y );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define remainder( x, y )
```
| (4) | (since C99) |
1-3) Computes the IEEE remainder of the floating point division operation `x/y`.
4) Type-generic macro: If any argument has type `long double`, `remainderl` is called. Otherwise, if any argument has integer type or has type `double`, `remainder` is called. Otherwise, `remainderf` is called. The IEEE floating-point remainder of the division operation `x/y` calculated by this function is exactly the value `x - n*y`, where the value `n` is the integral value nearest the exact value `x/y`. When |n-x/y| = ½, the value `n` is chosen to be even.
In contrast to `[fmod()](fmod "c/numeric/math/fmod")`, the returned value is not guaranteed to have the same sign as `x`.
If the returned value is `0`, it will have the same sign as `x`.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | floating point values |
### Return value
If successful, returns the IEEE floating-point remainder of the division `x/y` as defined above.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result is returned.
If `y` is zero, but the domain error does not occur, zero is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
Domain error may occur if `y` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* The current [rounding mode](https://en.cppreference.com/w/cpp/numeric/fenv/FE_round "cpp/numeric/fenv/FE round") has no effect.
* `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is never raised, the result is always exact.
* If `x` is ±∞ and `y` is not NaN, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `y` is ±0 and `x` is not NaN, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If either argument is NaN, NaN is returned
### Notes
[POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/remainder.html) that a domain error occurs if `x` is infinite or `y` is zero.
`[fmod](fmod "c/numeric/math/fmod")`, but not `remainder` is useful for doing silent wrapping of floating-point types to unsigned integer types: `(0.0 <= (y = [fmod](http://en.cppreference.com/w/c/numeric/math/fmod)([rint](http://en.cppreference.com/w/c/numeric/math/rint)(x), 65536.0)) ? y : 65536.0 + y)` is in the range `[-0.0 .. 65535.0]`, which corresponds to `unsigned short`, but `remainder([rint](http://en.cppreference.com/w/c/numeric/math/rint)(x), 65536.0)` is in the range `[-32767.0, +32768.0]`, which is outside of the range of `signed short`.
### Example
```
#include <stdio.h>
#include <math.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
printf("remainder(+5.1, +3.0) = %.1f\n", remainder(5.1,3));
printf("remainder(-5.1, +3.0) = %.1f\n", remainder(-5.1,3));
printf("remainder(+5.1, -3.0) = %.1f\n", remainder(5.1,-3));
printf("remainder(-5.1, -3.0) = %.1f\n", remainder(-5.1,-3));
// special values
printf("remainder(-0.0, 1.0) = %.1f\n", remainder(-0.0, 1));
printf("remainder(+5.1, Inf) = %.1f\n", remainder(5.1, INFINITY));
// error handling
feclearexcept(FE_ALL_EXCEPT);
printf("remainder(+5.1, 0) = %.1f\n", remainder(5.1, 0));
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
}
```
Output:
```
remainder(+5.1, +3.0) = -0.9
remainder(-5.1, +3.0) = 0.9
remainder(+5.1, -3.0) = -0.9
remainder(-5.1, -3.0) = 0.9
remainder(+0.0, 1.0) = 0.0
remainder(-0.0, 1.0) = -0.0
remainder(+5.1, Inf) = 5.1
remainder(+5.1, 0) = -nan
FE_INVALID raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.10.2 The remainder functions (p: 185-186)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.7.2 The remainder functions (p: 385)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.10.2 The remainder functions (p: 254-255)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.7.2 The remainder functions (p: 529)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.10.2 The remainder functions (p: 235)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.7.2 The remainder functions (p: 465)
### See also
| | |
| --- | --- |
| [divldivlldiv](div "c/numeric/math/div")
(C99) | computes quotient and remainder of integer division (function) |
| [fmodfmodffmodl](fmod "c/numeric/math/fmod")
(C99)(C99) | computes remainder of the floating-point division operation (function) |
| [remquoremquofremquol](remquo "c/numeric/math/remquo")
(C99)(C99)(C99) | computes signed remainder as well as the three last bits of the division operation (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/remainder "cpp/numeric/math/remainder") for `remainder` |
| programming_docs |
c float_t, double_t float\_t, double\_t
===================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
typedef /*implementation defined*/ float_t
```
| | (since C99) |
|
```
typedef /*implementation defined*/ double_t
```
| | (since C99) |
The types `float_t` and `double_t` are floating types at least as wide as `float` and `double`, respectively, and such that `double_t` is at least as wide as `float_t`. The value of `[FLT\_EVAL\_METHOD](../../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")` determines the types of `float_t` and `double_t`.
| FLT\_EVAL\_METHOD | Explanation |
| --- | --- |
| `0` | `float_t` and `double_t` are equivalent to `float` and `double`, respectively |
| `1` | both `float_t` and `double_t` are equivalent to `double` |
| `2` | both `float_t` and `double_t` are equivalent to `long double` |
| `other` | both `float_t` and `double_t` are implementation defined |
### Example
```
#include <float.h>
#include <math.h>
#include <stdio.h>
int main(void)
{
printf("%d\n", FLT_EVAL_METHOD);
printf("%zu %zu\n", sizeof(float),sizeof(float_t));
printf("%zu %zu\n", sizeof(double),sizeof(double_t));
return 0;
}
```
Possible output:
```
0
4 4
8 8
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12 Mathematics <math.h> (p: 231)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12 Mathematics <math.h> (p: 212)
### See also
| | |
| --- | --- |
| [FLT\_EVAL\_METHOD](../../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")
(C99) | use of extended precision for intermediate results: 0 not used, 1 `double` is used instead of `float`, 2: `long double` is used (macro constant) |
c erf, erff, erfl erf, erff, erfl
===============
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float erff( float arg );
```
| (1) | (since C99) |
|
```
double erf( double arg );
```
| (2) | (since C99) |
|
```
long double erfl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define erf( arg )
```
| (4) | (since C99) |
1-3) Computes the [error function](https://en.wikipedia.org/wiki/Error_function "enwiki:Error function") of `arg`.
4) Type-generic macro: If `arg` has type `long double`, `erfl` is called. Otherwise, if `arg` has integer type or the type `double`, `erf` is called. Otherwise, `erff` is called. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, value of the error function of `arg`, that is \(\frac{2}{\sqrt{\pi} }\int\_{0}^{arg}{e^{-{t^2} }\mathsf{d}t}\)2/√π∫arg
0*e*-t2d*t*, is returned. If a range error occurs due to underflow, the correct result (after rounding), that is \(\frac{2\cdot arg}{\sqrt{\pi} }\)2\*arg/√π, is returned. ### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ±0, ±0 is returned
* If the argument is ±∞, ±1 is returned
* If the argument is NaN, NaN is returned
### Notes
Underflow is guaranteed if `|arg| < [DBL\_MIN](http://en.cppreference.com/w/c/types/limits)\*([sqrt](http://en.cppreference.com/w/c/numeric/math/sqrt)(π)/2)`. \(\operatorname{erf}(\frac{x}{\sigma \sqrt{2} })\)erf(
x/σ√2) is the probability that a measurement whose errors are subject to a normal distribution with standard deviation \(\sigma\)σ is less than \(x\)x away from the mean value. ### Example
```
#include <stdio.h>
#include <math.h>
double phi(double x1, double x2)
{
return (erf(x2/sqrt(2)) - erf(x1/sqrt(2)))/2;
}
int main(void)
{
puts("normal variate probabilities:");
for(int n=-4; n<4; ++n)
printf("[%2d:%2d]: %5.2f%%\n", n, n+1, 100*phi(n, n+1));
puts("special values:");
printf("erf(-0) = %f\n", erf(-0.0));
printf("erf(Inf) = %f\n", erf(INFINITY));
}
```
Output:
```
normal variate probabilities:
[-4:-3]: 0.13%
[-3:-2]: 2.14%
[-2:-1]: 13.59%
[-1: 0]: 34.13%
[ 0: 1]: 34.13%
[ 1: 2]: 13.59%
[ 2: 3]: 2.14%
[ 3: 4]: 0.13%
special values:
erf(-0) = -0.000000
erf(Inf) = 1.000000
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.8.1 The erf functions (p: 249)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.5.1 The erf functions (p: 525)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.8.1 The erf functions (p: 230)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.5.1 The erf functions (p: 462)
### See also
| | |
| --- | --- |
| [erfcerfcferfcl](erfc "c/numeric/math/erfc")
(C99)(C99)(C99) | computes complementary error function (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/erf "cpp/numeric/math/erf") for `erf` |
### External links
[Weisstein, Eric W. "Erf."](http://mathworld.wolfram.com/Erf.html) From MathWorld--A Wolfram Web Resource.
c MATH_ERRNO, MATH_ERREXCEPT, math_errhandling MATH\_ERRNO, MATH\_ERREXCEPT, math\_errhandling
===============================================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define MATH_ERRNO 1
```
| | (since C99) |
|
```
#define MATH_ERREXCEPT 2
```
| | (since C99) |
|
```
#define math_errhandling /*implementation defined*/
```
| | (since C99) |
The macro constant `math_errhandling` expands to an expression of type `int` that is either equal to `MATH_ERRNO`, or equal to `MATH_ERREXCEPT`, or equal to their bitwise OR (`MATH_ERRNO | MATH_ERREXCEPT`).
The value of `math_errhandling` indicates the type of error handling that is performed by the floating-point operators and [functions](../math "c/numeric/math"):
| Constant | Explanation |
| --- | --- |
| `MATH_ERREXCEPT` | indicates that floating-point exceptions are used: at least `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")`, `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")`, and `[FE\_OVERFLOW](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` are defined in `<fenv.h>`. |
| `MATH_ERRNO` | indicates that floating-point operations use the variable `[errno](../../error/errno "c/error/errno")` to report errors. |
If the implementation supports IEEE floating-point arithmetic (IEC 60559), `math_errhandling & MATH_ERREXCEPT` is required to be non-zero.
The following floating-point error conditions are recognized:
| Condition | Explanation | errno | floating-point exception | Example |
| --- | --- | --- | --- | --- |
| Domain error | the argument is outside the range in which the operation is mathematically defined (the description of [each function](../math "c/numeric/math") lists the required domain errors) | `[EDOM](../../error/errno_macros "c/error/errno macros")` | `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` | `[acos](http://en.cppreference.com/w/c/numeric/math/acos)(2)` |
| Pole error | the mathematical result of the function is exactly infinite or undefined | `[ERANGE](../../error/errno_macros "c/error/errno macros")` | `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` | `[log](http://en.cppreference.com/w/c/numeric/math/log)(0.0)`, `1.0/0.0` |
| Range error due to overflow | the mathematical result is finite, but becomes infinite after rounding, or becomes the largest representable finite value after rounding down | `[ERANGE](../../error/errno_macros "c/error/errno macros")` | `[FE\_OVERFLOW](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` | `[pow](http://en.cppreference.com/w/c/numeric/math/pow)([DBL\_MAX](http://en.cppreference.com/w/c/types/limits),2)` |
| Range error due to underflow | the result is non-zero, but becomes zero after rounding, or becomes subnormal with a loss of precision | `[ERANGE](../../error/errno_macros "c/error/errno macros")` or unchanged (implementation-defined) | `[FE\_UNDERFLOW](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` or nothing (implementation-defined) | `DBL_TRUE_MIN/2` |
| Inexact result | the result has to be rounded to fit in the destination type | unchanged | `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` or nothing (unspecified) | `[sqrt](http://en.cppreference.com/w/c/numeric/math/sqrt)(2)`, `1.0/10.0` |
### Notes
Whether `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised by the mathematical library functions is unspecified in general, but may be explicitly specified in the description of the function (e.g. `[rint](rint "c/numeric/math/rint")` vs `[nearbyint](nearbyint "c/numeric/math/nearbyint")`).
Before C99, floating-point exceptions were not specified, `[EDOM](http://en.cppreference.com/w/c/error/errno_macros)` was required for any domain error, `[ERANGE](http://en.cppreference.com/w/c/error/errno_macros)` was required for overflows and implementation-defined for underflows.
### Example
```
#include <stdio.h>
#include <fenv.h>
#include <math.h>
#include <errno.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
printf("MATH_ERRNO is %s\n", math_errhandling & MATH_ERRNO ? "set" : "not set");
printf("MATH_ERREXCEPT is %s\n",
math_errhandling & MATH_ERREXCEPT ? "set" : "not set");
feclearexcept(FE_ALL_EXCEPT);
errno = 0;
printf("log(0) = %f\n", log(0));
if(errno == ERANGE)
perror("errno == ERANGE");
if(fetestexcept(FE_DIVBYZERO))
puts("FE_DIVBYZERO (pole error) reported");
}
```
Possible output:
```
MATH_ERRNO is set
MATH_ERREXCEPT is set
log(0) = -inf
errno = ERANGE: Numerical result out of range
FE_DIVBYZERO (pole error) reported
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12/9 MATH\_ERRNO, MATH\_ERREXCEPT, math\_errhandling (p: 170)
+ F.10/4 MATH\_ERREXCEPT, math\_errhandling (p: 377)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12/9 MATH\_ERRNO, MATH\_ERREXCEPT, math\_errhandling (p: 233)
+ F.10/4 MATH\_ERREXCEPT, math\_errhandling (p: 517)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12/9 MATH\_ERRNO, MATH\_ERREXCEPT, math\_errhandling (p: 214)
+ F.9/4 MATH\_ERREXCEPT, math\_errhandling> (p: 454)
### See also
| | |
| --- | --- |
| [FE\_ALL\_EXCEPTFE\_DIVBYZEROFE\_INEXACTFE\_INVALIDFE\_OVERFLOWFE\_UNDERFLOW](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")
(C99) | floating-point exceptions (macro constant) |
| [errno](../../error/errno "c/error/errno") | macro which expands to POSIX-compatible thread-local error number variable(macro variable) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/math_errhandling "cpp/numeric/math/math errhandling") for `math_errhandling` |
c nearbyint, nearbyintf, nearbyintl nearbyint, nearbyintf, nearbyintl
=================================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float nearbyintf( float arg );
```
| (1) | (since C99) |
|
```
double nearbyint( double arg );
```
| (2) | (since C99) |
|
```
long double nearbyintl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define nearbyint( arg )
```
| (4) | (since C99) |
1-3) Rounds the floating-point argument `arg` to an integer value in floating-point format, using the [current rounding mode](../fenv/fe_round "c/numeric/fenv/FE round").
4) Type-generic macro: If `arg` has type `long double`, `nearbyintl` is called. Otherwise, if `arg` has integer type or the type `double`, `nearbyint` is called. Otherwise, `nearbyintf` is called, respectively. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
The nearest integer value to `arg`, according to the [current rounding mode](../fenv/fe_round "c/numeric/fenv/FE round"), is returned.
### Error handling
This function is not subject to any of the errors specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is never raised
* If `arg` is ±∞, it is returned, unmodified
* If `arg` is ±0, it is returned, unmodified
* If `arg` is NaN, NaN is returned
### Notes
The only difference between `nearbyint` and `[rint](rint "c/numeric/math/rint")` is that `nearbyint` never raises `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")`.
The largest representable floating-point values are exact integers in all standard floating-point formats, so `nearbyint` never overflows on its own; however the result may overflow any integer type (including `[intmax\_t](../../types/integer "c/types/integer")`), when stored in an integer variable.
If the current rounding mode is `[FE\_TONEAREST](../fenv/fe_round "c/numeric/fenv/FE round")`, this function rounds to even in halfway cases (like `[rint](rint "c/numeric/math/rint")`, but unlike `[round](round "c/numeric/math/round")`).
### Example
```
#include <stdio.h>
#include <math.h>
#include <fenv.h>
int main(void)
{
#pragma STDC FENV_ACCESS ON
fesetround(FE_TONEAREST);
printf("rounding to nearest:\nnearbyint(+2.3) = %+.1f ", nearbyint(2.3));
printf("nearbyint(+2.5) = %+.1f ", nearbyint(2.5));
printf("nearbyint(+3.5) = %+.1f\n", nearbyint(3.5));
printf("nearbyint(-2.3) = %+.1f ", nearbyint(-2.3));
printf("nearbyint(-2.5) = %+.1f ", nearbyint(-2.5));
printf("nearbyint(-3.5) = %+.1f\n", nearbyint(-3.5));
fesetround(FE_DOWNWARD);
printf("rounding down: \nnearbyint(+2.3) = %+.1f ", nearbyint(2.3));
printf("nearbyint(+2.5) = %+.1f ", nearbyint(2.5));
printf("nearbyint(+3.5) = %+.1f\n", nearbyint(3.5));
printf("nearbyint(-2.3) = %+.1f ", nearbyint(-2.3));
printf("nearbyint(-2.5) = %+.1f ", nearbyint(-2.5));
printf("nearbyint(-3.5) = %+.1f\n", nearbyint(-3.5));
printf("nearbyint(-0.0) = %+.1f\n", nearbyint(-0.0));
printf("nearbyint(-Inf) = %+.1f\n", nearbyint(-INFINITY));
}
```
Output:
```
rounding to nearest:
nearbyint(+2.3) = +2.0 nearbyint(+2.5) = +2.0 nearbyint(+3.5) = +4.0
nearbyint(-2.3) = -2.0 nearbyint(-2.5) = -2.0 nearbyint(-3.5) = -4.0
rounding down:
nearbyint(+2.3) = +2.0 nearbyint(+2.5) = +2.0 nearbyint(+3.5) = +3.0
nearbyint(-2.3) = -3.0 nearbyint(-2.5) = -3.0 nearbyint(-3.5) = -4.0
nearbyint(-0.0) = -0.0
nearbyint(-Inf) = -inf
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.9.3 The nearbyint functions (p: 251-252)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.6.3 The nearbyint functions (p: 526)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.9.3 The nearbyint functions (p: 232)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.6.3 The nearbyint functions (p: 463)
### See also
| | |
| --- | --- |
| [rintrintfrintllrintlrintflrintlllrintllrintfllrintl](rint "c/numeric/math/rint")
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) | rounds to an integer using current rounding mode with exception if the result differs (function) |
| [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](round "c/numeric/math/round")
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) | rounds to nearest integer, rounding away from zero in halfway cases (function) |
| [fegetroundfesetround](../fenv/feround "c/numeric/fenv/feround")
(C99)(C99) | gets or sets rounding direction (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/nearbyint "cpp/numeric/math/nearbyint") for `nearbyint` |
c isfinite isfinite
========
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define isfinite(arg) /* implementation defined */
```
| | (since C99) |
Determines if the given floating point number `arg` has finite value i.e. it is normal, subnormal or zero, but not infinite or NaN. The macro returns an integral value.
`[FLT\_EVAL\_METHOD](../../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")` is ignored: even if the argument is evaluated with more range and precision than its type, it is first converted to its semantic type, and the classification is based on that.
### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
Nonzero integral value if `arg` has finite value, `0` otherwise.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
int main(void)
{
printf("isfinite(NAN) = %d\n", isfinite(NAN));
printf("isfinite(INFINITY) = %d\n", isfinite(INFINITY));
printf("isfinite(0.0) = %d\n", isfinite(0.0));
printf("isfinite(DBL_MIN/2.0) = %d\n", isfinite(DBL_MIN/2.0));
printf("isfinite(1.0) = %d\n", isfinite(1.0));
printf("isfinite(exp(800)) = %d\n", isfinite(exp(800)));
}
```
Possible output:
```
isfinite(NAN) = 0
isfinite(INFINITY) = 0
isfinite(0.0) = 1
isfinite(DBL_MIN/2.0) = 1
isfinite(1.0) = 1
isfinite(exp(800)) = 0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.3.2 The isfinite macro (p: 236)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.3.2 The isfinite macro (p: 216-217)
### See also
| | |
| --- | --- |
| [fpclassify](fpclassify "c/numeric/math/fpclassify")
(C99) | classifies the given floating-point value (function macro) |
| [isinf](isinf "c/numeric/math/isinf")
(C99) | checks if the given number is infinite (function macro) |
| [isnan](isnan "c/numeric/math/isnan")
(C99) | checks if the given number is NaN (function macro) |
| [isnormal](isnormal "c/numeric/math/isnormal")
(C99) | checks if the given number is normal (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/isfinite "cpp/numeric/math/isfinite") for `isfinite` |
c sqrt, sqrtf, sqrtl sqrt, sqrtf, sqrtl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float sqrtf( float arg );
```
| (1) | (since C99) |
|
```
double sqrt( double arg );
```
| (2) | |
|
```
long double sqrtl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define sqrt( arg )
```
| (4) | (since C99) |
1-3) Computes square root of `arg`.
4) Type-generic macro: If `arg` has type `long double`, `sqrtl` is called. Otherwise, if `arg` has integer type or the type `double`, `sqrt` is called. Otherwise, `sqrtf` is called. If `arg` is complex or imaginary, then the macro invokes the corresponding complex function (`[csqrtf](http://en.cppreference.com/w/c/numeric/complex/csqrt)`, `[csqrt](http://en.cppreference.com/w/c/numeric/complex/csqrt)`, `[csqrtl](http://en.cppreference.com/w/c/numeric/complex/csqrt)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, square root of `arg` (\({\small \sqrt{arg} }\)√arg), is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
Domain error occurs if `arg` is less than zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is less than -0, `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised and NaN is returned.
* If the argument is +∞ or ±0, it is returned, unmodified.
* If the argument is NaN, NaN is returned
### Notes
`sqrt` is required by the IEEE standard to be exact. The only other operations required to be exact are the [arithmetic operators](../../language/operator_arithmetic "c/language/operator arithmetic") and the function `[fma](fma "c/numeric/math/fma")`. After rounding to the return type (using default rounding mode), the result of `sqrt` is indistinguishable from the infinitely precise result. In other words, the error is less than 0.5 ulp. Other functions, including `[pow](pow "c/numeric/math/pow")`, are not so constrained.
### Example
```
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
// normal use
printf("sqrt(100) = %f\n", sqrt(100));
printf("sqrt(2) = %f\n", sqrt(2));
printf("golden ratio = %f\n", (1+sqrt(5))/2);
// special values
printf("sqrt(-0) = %f\n", sqrt(-0.0));
// error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("sqrt(-1.0) = %f\n", sqrt(-1));
if(errno == EDOM) perror(" errno == EDOM");
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID was raised");
}
```
Possible output:
```
sqrt(100) = 10.000000
sqrt(2) = 1.414214
golden ratio = 1.618034
sqrt(-0) = -0.000000
sqrt(-1.0) = -nan
errno = EDOM: Numerical argument out of domain
FE_INVALID was raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.7.5 The sqrt functions (p: 249)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.4.5 The sqrt functions (p: 525)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.7.5 The sqrt functions (p: 229-230)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.4.5 The sqrt functions (p: 462)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.5.2 The sqrt function
### See also
| | |
| --- | --- |
| [powpowfpowl](pow "c/numeric/math/pow")
(C99)(C99) | computes a number raised to the given power (\(\small{x^y}\)xy) (function) |
| [cbrtcbrtfcbrtl](cbrt "c/numeric/math/cbrt")
(C99)(C99)(C99) | computes cubic root (\(\small{\sqrt[3]{x} }\)3√x) (function) |
| [hypothypotfhypotl](hypot "c/numeric/math/hypot")
(C99)(C99)(C99) | computes square root of the sum of the squares of two given numbers (\(\scriptsize{\sqrt{x^2+y^2} }\)√x2+y2) (function) |
| [csqrtcsqrtfcsqrtl](../complex/csqrt "c/numeric/complex/csqrt")
(C99)(C99)(C99) | computes the complex square root (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/sqrt "cpp/numeric/math/sqrt") for `sqrt` |
| programming_docs |
c logb, logbf, logbl logb, logbf, logbl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float logbf( float arg );
```
| (1) | (since C99) |
|
```
double logb( double arg );
```
| (2) | (since C99) |
|
```
long double logbl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define logb( arg )
```
| (4) | (since C99) |
1-3) Extracts the value of the unbiased radix-independent exponent from the floating-point argument `arg`, and returns it as a floating-point value.
4) Type-generic macros: If `arg` has type `long double`, `logbl` is called. Otherwise, if `arg` has integer type or the type `double`, `logb` is called. Otherwise, `logbf` is called. Formally, the unbiased exponent is the signed integral part of log
r|arg| (returned by this function as a floating-point value), for non-zero arg, where `r` is `[FLT\_RADIX](../../types/limits "c/types/limits")`. If `arg` is subnormal, it is treated as though it was normalized.
### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the unbiased exponent of `arg` is returned as a signed floating-point value.
If a domain error occurs, an implementation-defined value is returned.
If a pole error occurs, `[-HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `-HUGE_VALF`, or `-HUGE_VALL` is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
Domain or range error may occur if `arg` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If `arg` is ±0, -∞ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* If `arg` is ±∞, +∞ is returned
* If `arg` is NaN, NaN is returned.
* In all other cases, the result is exact (`[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is never raised) and [the current rounding mode](../fenv/fe_round "c/numeric/fenv/FE round") is ignored
### Notes
[POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/logb.html) that a pole error occurs if `arg` is ±0.
The value of the exponent returned by `logb` is always 1 less than the exponent retuned by `[frexp](frexp "c/numeric/math/frexp")` because of the different normalization requirements: for the exponent `e` returned by `logb`, |arg\*r-e
| is between 1 and `r` (typically between `1` and `2`), but for the exponent `e` returned by `[frexp](frexp "c/numeric/math/frexp")`, |arg\*2-e
| is between `0.5` and `1`.
### Example
Compares different floating-point decomposition functions.
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <fenv.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
double f = 123.45;
printf("Given the number %.2f or %a in hex,\n", f, f);
double f3;
double f2 = modf(f, &f3);
printf("modf() makes %.0f + %.2f\n", f3, f2);
int i;
f2 = frexp(f, &i);
printf("frexp() makes %f * 2^%d\n", f2, i);
i = logb(f);
printf("logb()/logb() make %f * %d^%d\n", f/scalbn(1.0, i), FLT_RADIX, i);
// error handling
feclearexcept(FE_ALL_EXCEPT);
printf("logb(0) = %f\n", logb(0));
if(fetestexcept(FE_DIVBYZERO)) puts(" FE_DIVBYZERO raised");
}
```
Possible output:
```
Given the number 123.45 or 0x1.edccccccccccdp+6 in hex,
modf() makes 123 + 0.45
frexp() makes 0.964453 * 2^7
logb()/logb() make 1.928906 * 2^6
logb(0) = -Inf
FE_DIVBYZERO raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.6.11 The logb functions (p: 179-180)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.11 The logb functions (p: 381)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.6.11 The logb functions (p: 246)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.11 The logb functions (p: 522)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.6.11 The logb functions (p: 227)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.3.11 The logb functions (p: 459)
### See also
| | |
| --- | --- |
| [frexpfrexpffrexpl](frexp "c/numeric/math/frexp")
(C99)(C99) | breaks a number into significand and a power of `2` (function) |
| [ilogbilogbfilogbl](ilogb "c/numeric/math/ilogb")
(C99)(C99)(C99) | extracts exponent of the given number (function) |
| [scalbnscalbnfscalbnlscalblnscalblnfscalblnl](scalbn "c/numeric/math/scalbn")
(C99)(C99)(C99)(C99)(C99)(C99) | computes efficiently a number times `[FLT\_RADIX](../../types/limits "c/types/limits")` raised to a power (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/logb "cpp/numeric/math/logb") for `logb` |
c tanh, tanhf, tanhl tanh, tanhf, tanhl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float tanhf( float arg );
```
| (1) | (since C99) |
|
```
double tanh( double arg );
```
| (2) | |
|
```
long double tanhl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define tanh( arg )
```
| (4) | (since C99) |
1-3) Computes the hyperbolic tangent of `arg`.
4) Type-generic macro: If the argument has type `long double`, `tanhl` is called. Otherwise, if the argument has integer type or the type `double`, `tanh` is called. Otherwise, `tanhf` is called. If the argument is complex, then the macro invokes the corresponding complex function (`[ctanhf](http://en.cppreference.com/w/c/numeric/complex/ctanh)`, `[ctanh](http://en.cppreference.com/w/c/numeric/complex/ctanh)`, `[ctanhl](http://en.cppreference.com/w/c/numeric/complex/ctanh)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value representing a hyperbolic angle |
### Return value
If no errors occur, the hyperbolic tangent of `arg` (tanh(arg), or earg-e-arg/earg+e-arg) is returned. If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ±0, ±0 is returned
* If the argument is ±∞, ±1 is returned
* if the argument is NaN, NaN is returned
### Notes
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/tanh.html) that in case of underflow, `arg` is returned unmodified, and if that is not supported, an implementation-defined value no greater than DBL\_MIN, FLT\_MIN, and LDBL\_MIN is returned.
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("tanh(1) = %f\ntanh(-1) = %f\n", tanh(1), tanh(-1));
printf("tanh(0.1)*sinh(0.2)-cosh(0.2) = %f\n", tanh(0.1) * sinh(0.2) - cosh(0.2));
// special values
printf("tanh(+0) = %f\ntanh(-0) = %f\n", tanh(0.0), tanh(-0.0));
}
```
Output:
```
tanh(1) = 0.761594
tanh(-1) = -0.761594
tanh(0.1)*sinh(0.2)-cosh(0.2) = -1.000000
tanh(+0) = 0.000000
tanh(-0) = -0.000000
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.5.6 The tanh functions (p: 242)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.2.6 The tanh functions (p: 520)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.5.6 The tanh functions (p: 222-223)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.2.6 The tanh functions (p: 457)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.3.3 The tanh function
### See also
| | |
| --- | --- |
| [sinhsinhfsinhl](sinh "c/numeric/math/sinh")
(C99)(C99) | computes hyperbolic sine (\({\small\sinh{x} }\)sinh(x)) (function) |
| [coshcoshfcoshl](cosh "c/numeric/math/cosh")
(C99)(C99) | computes hyperbolic cosine (\({\small\cosh{x} }\)cosh(x)) (function) |
| [atanhatanhfatanhl](atanh "c/numeric/math/atanh")
(C99)(C99)(C99) | computes inverse hyperbolic tangent (\({\small\operatorname{artanh}{x} }\)artanh(x)) (function) |
| [ctanhctanhfctanhl](../complex/ctanh "c/numeric/complex/ctanh")
(C99)(C99)(C99) | computes the complex hyperbolic tangent (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/tanh "cpp/numeric/math/tanh") for `tanh` |
c cbrt, cbrtf, cbrtl cbrt, cbrtf, cbrtl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float cbrtf( float arg );
```
| (1) | (since C99) |
|
```
double cbrt( double arg );
```
| (2) | (since C99) |
|
```
long double cbrtl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define cbrt( arg )
```
| (4) | (since C99) |
1-3) Computes the cube root of `arg`.
4) Type-generic macro: If `arg` has type `long double`, `cbrtl` is called. Otherwise, if `arg` has integer type or the type `double`, `cbrt` is called. Otherwise, `cbrtf` is called. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the cube root of `arg` (\(\small{\sqrt[3]{arg} }\)3√arg), is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ±0 or ±∞, it is returned, unchanged
* if the argument is NaN, NaN is returned.
### Notes
`cbrt(arg)` is not equivalent to `[pow](http://en.cppreference.com/w/c/numeric/math/pow)(arg, 1.0/3)` because the rational number \(\small{\frac1{3} }\)1/3 is typically not equal to `1.0/3` and `std::pow` cannot raise a negative base to a fractional exponent. Moreover, `cbrt(arg)` usually gives more accurate results than `[pow](http://en.cppreference.com/w/c/numeric/math/pow)(arg, 1.0/3)` (see example). ### Example
```
#include <stdio.h>
#include <float.h>
#include <math.h>
int main(void)
{
printf("Normal use:\n"
"cbrt(729) = %f\n", cbrt(729));
printf("cbrt(-0.125) = %f\n", cbrt(-0.125));
printf("Special values:\n"
"cbrt(-0) = %f\n", cbrt(-0.0));
printf("cbrt(+inf) = %f\n", cbrt(INFINITY));
printf("Accuracy:\n"
"cbrt(343) = %.*f\n", DBL_DECIMAL_DIG, cbrt(343));
printf("pow(343,1.0/3) = %.*f\n", DBL_DECIMAL_DIG, pow(343, 1.0/3));
}
```
Possible output:
```
Normal use:
cbrt(729) = 9.000000
cbrt(-0.125) = -0.500000
Special values:
cbrt(-0) = -0.000000
cbrt(+inf) = inf
Accuracy:
cbrt(343) = 7.00000000000000000
pow(343,1.0/3) = 6.99999999999999911
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.7.1 The cbrt functions (p: 180-181)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.4.1 The cbrt functions (p: 381-)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.7.1 The cbrt functions (p: 247)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.4.1 The cbrt functions (p: 524)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.7.1 The cbrt functions (p: 228)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.4.1 The cbrt functions (p: 460)
### See also
| | |
| --- | --- |
| [powpowfpowl](pow "c/numeric/math/pow")
(C99)(C99) | computes a number raised to the given power (\(\small{x^y}\)xy) (function) |
| [sqrtsqrtfsqrtl](sqrt "c/numeric/math/sqrt")
(C99)(C99) | computes square root (\(\small{\sqrt{x} }\)√x) (function) |
| [hypothypotfhypotl](hypot "c/numeric/math/hypot")
(C99)(C99)(C99) | computes square root of the sum of the squares of two given numbers (\(\scriptsize{\sqrt{x^2+y^2} }\)√x2+y2) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/cbrt "cpp/numeric/math/cbrt") for `cbrt` |
c isinf isinf
=====
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define isinf(arg) /* implementation defined */
```
| | (since C99) |
Determines if the given floating-point number `arg` is positive or negative infinity. The macro returns an integral value.
`[FLT\_EVAL\_METHOD](../../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")` is ignored: even if the argument is evaluated with more range and precision than its type, it is first converted to its semantic type, and the classification is based on that.
### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating-point value |
### Return value
Nonzero integral value if `arg` has an infinite value, `0` otherwise.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
int main(void)
{
printf("isinf(NAN) = %d\n", isinf(NAN));
printf("isinf(INFINITY) = %d\n", isinf(INFINITY));
printf("isinf(0.0) = %d\n", isinf(0.0));
printf("isinf(DBL_MIN/2.0) = %d\n", isinf(DBL_MIN/2.0));
printf("isinf(1.0) = %d\n", isinf(1.0));
printf("isinf(exp(800)) = %d\n", isinf(exp(800)));
}
```
Possible output:
```
isinf(NAN) = 0
isinf(INFINITY) = 1
isinf(0.0) = 0
isinf(DBL_MIN/2.0) = 0
isinf(1.0) = 0
isinf(exp(800)) = 1
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.3.3 The isinf macro (p: 172)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.3.3 The isinf macro (p: 236)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.3.3 The isinf macro (p: 217)
### See also
| | |
| --- | --- |
| [fpclassify](fpclassify "c/numeric/math/fpclassify")
(C99) | classifies the given floating-point value (function macro) |
| [isfinite](isfinite "c/numeric/math/isfinite")
(C99) | checks if the given number has finite value (function macro) |
| [isnan](isnan "c/numeric/math/isnan")
(C99) | checks if the given number is NaN (function macro) |
| [isnormal](isnormal "c/numeric/math/isnormal")
(C99) | checks if the given number is normal (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/isinf "cpp/numeric/math/isinf") for `isinf` |
c isunordered isunordered
===========
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define isunordered(x, y) /* implementation defined */
```
| | (since C99) |
Determines if the floating point numbers `x` and `y` are unordered, that is, one or both are NaN and thus cannot be meaningfully compared with each other.
### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
Nonzero integral value if either `x` or `y` is NaN, `0` otherwise.
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("isunordered(NAN,1.0) = %d\n", isunordered(NAN,1.0));
printf("isunordered(1.0,NAN) = %d\n", isunordered(1.0,NAN));
printf("isunordered(NAN,NAN) = %d\n", isunordered(NAN,NAN));
printf("isunordered(1.0,0.0) = %d\n", isunordered(1.0,0.0));
return 0;
}
```
Possible output:
```
isunordered(NAN,1.0) = 1
isunordered(1.0,NAN) = 1
isunordered(NAN,NAN) = 1
isunordered(1.0,0.0) = 0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.14.6 The isunordered macro (p: 261)
+ F.10.11 Comparison macros (p: 531)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.14.6 The isunordered macro (p: 242)
### See also
| | |
| --- | --- |
| [fpclassify](fpclassify "c/numeric/math/fpclassify")
(C99) | classifies the given floating-point value (function macro) |
| [isnan](isnan "c/numeric/math/isnan")
(C99) | checks if the given number is NaN (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/isunordered "cpp/numeric/math/isunordered") for `isunordered` |
c pow, powf, powl pow, powf, powl
===============
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float powf( float base, float exponent );
```
| (1) | (since C99) |
|
```
double pow( double base, double exponent );
```
| (2) | |
|
```
long double powl( long double base, long double exponent );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define pow( base, exponent )
```
| (4) | (since C99) |
1-3) Computes the value of `base` raised to the power `exponent`.
4) Type-generic macro: If any argument has type `long double`, `powl` is called. Otherwise, if any argument has integer type or has type `double`, `pow` is called. Otherwise, `powf` is called. If at least one argument is complex or imaginary, then the macro invokes the corresponding complex function (`[cpowf](http://en.cppreference.com/w/c/numeric/complex/cpow)`, `[cpow](http://en.cppreference.com/w/c/numeric/complex/cpow)`, `[cpowl](http://en.cppreference.com/w/c/numeric/complex/cpow)`). ### Parameters
| | | |
| --- | --- | --- |
| base | - | base as floating point value |
| exponent | - | exponent as floating point value |
### Return value
If no errors occur, `base` raised to the power of `exponent` (baseexponent
) is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a pole error or a range error due to overflow occurs, `[±HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `±HUGE_VALF`, or `±HUGE_VALL` is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If `base` is finite and negative and `exponent` is finite and non-integer, a domain error occurs and a range error may occur.
If `base` is zero and `exponent` is zero, a domain error may occur.
If `base` is zero and `exponent` is negative, a domain error or a pole error may occur.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* `pow(+0, exponent)`, where `exponent` is a negative odd integer, returns `+∞` and raises `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")`
* `pow(-0, exponent)`, where `exponent` is a negative odd integer, returns `-∞` and raises `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")`
* `pow(±0, exponent)`, where `exponent` is negative, finite, and is an even integer or a non-integer, returns +∞ and raises `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")`
* `pow(±0, -∞)` returns +∞ and may raise `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` (until C23)
* `pow(+0, exponent)`, where `exponent` is a positive odd integer, returns +0
* `pow(-0, exponent)`, where `exponent` is a positive odd integer, returns -0
* `pow(±0, exponent)`, where `exponent` is positive non-integer or a positive even integer, returns +0
* `pow(-1, ±∞)` returns `1`
* `pow(+1, exponent)` returns `1` for any `exponent`, even when `exponent` is `NaN`
* `pow(base, ±0)` returns `1` for any `base`, even when `base` is `NaN`
* `pow(base, exponent)` returns `NaN` and raises `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` if `base` is finite and negative and `exponent` is finite and non-integer.
* `pow(base, -∞)` returns +∞ for any `|base|<1`
* `pow(base, -∞)` returns +0 for any `|base|>1`
* `pow(base, +∞)` returns +0 for any `|base|<1`
* `pow(base, +∞)` returns +∞ for any `|base|>1`
* `pow(-∞, exponent)` returns -0 if `exponent` is a negative odd integer
* `pow(-∞, exponent)` returns +0 if `exponent` is a negative non-integer or negative even integer
* `pow(-∞, exponent)` returns -∞ if `exponent` is a positive odd integer
* `pow(-∞, exponent)` returns +∞ if `exponent` is a positive non-integer or positive even integer
* `pow(+∞, exponent)` returns +0 for any negative `exponent`
* `pow(+∞, exponent)` returns +∞ for any positive `exponent`
* except where specified above, if any argument is NaN, NaN is returned
### Notes
Although `pow` cannot be used to obtain a root of a negative number, `[cbrt](cbrt "c/numeric/math/cbrt")` is provided for the common case where `exponent` is 1/3.
### Example
```
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
// typical usage
printf("pow(2, 10) = %f\n", pow(2,10));
printf("pow(2, 0.5) = %f\n", pow(2,0.5));
printf("pow(-2, -3) = %f\n", pow(-2,-3));
// special values
printf("pow(-1, NAN) = %f\n", pow(-1,NAN));
printf("pow(+1, NAN) = %f\n", pow(+1,NAN));
printf("pow(INFINITY, 2) = %f\n", pow(INFINITY, 2));
printf("pow(INFINITY, -1) = %f\n", pow(INFINITY, -1));
// error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("pow(-1, 1/3) = %f\n", pow(-1, 1.0/3));
if(errno == EDOM) perror(" errno == EDOM");
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
feclearexcept(FE_ALL_EXCEPT);
printf("pow(-0, -3) = %f\n", pow(-0.0, -3));
if(fetestexcept(FE_DIVBYZERO)) puts(" FE_DIVBYZERO raised");
}
```
Possible output:
```
pow(2, 10) = 1024.000000
pow(2, 0.5) = 1.414214
pow(-2, -3) = -0.125000
pow(-1, NAN) = nan
pow(+1, NAN) = 1.000000
pow(INFINITY, 2) = inf
pow(INFINITY, -1) = 0.000000
pow(-1, 1/3) = -nan
errno == EDOM: Numerical argument out of domain
FE_INVALID raised
pow(-0, -3) = -inf
FE_DIVBYZERO raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.7.4 The pow functions (p: 248-249)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.4.4 The pow functions (p: 524-525)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.7.4 The pow functions (p: 229)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.4.4 The pow functions (p: 461)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.5.1 The pow function
### See also
| | |
| --- | --- |
| [sqrtsqrtfsqrtl](sqrt "c/numeric/math/sqrt")
(C99)(C99) | computes square root (\(\small{\sqrt{x} }\)√x) (function) |
| [cbrtcbrtfcbrtl](cbrt "c/numeric/math/cbrt")
(C99)(C99)(C99) | computes cubic root (\(\small{\sqrt[3]{x} }\)3√x) (function) |
| [hypothypotfhypotl](hypot "c/numeric/math/hypot")
(C99)(C99)(C99) | computes square root of the sum of the squares of two given numbers (\(\scriptsize{\sqrt{x^2+y^2} }\)√x2+y2) (function) |
| [cpowcpowfcpowl](../complex/cpow "c/numeric/complex/cpow")
(C99)(C99)(C99) | computes the complex power function (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/pow "cpp/numeric/math/pow") for `pow` |
| programming_docs |
c exp, expf, expl exp, expf, expl
===============
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float expf( float arg );
```
| (1) | (since C99) |
|
```
double exp( double arg );
```
| (2) | |
|
```
long double expl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define exp( arg )
```
| (4) | (since C99) |
1-3) Computes the *e* (Euler's number, `2.7182818`) raised to the given power `arg`.
4) Type-generic macro: If `arg` has type `long double`, `expl` is called. Otherwise, if `arg` has integer type or the type `double`, `exp` is called. Otherwise, `expf` is called. If `arg` is complex or imaginary, then the macro invokes the corresponding complex function (`[cexpf](http://en.cppreference.com/w/c/numeric/complex/cexp)`, `[cexp](http://en.cppreference.com/w/c/numeric/complex/cexp)`, `[cexpl](http://en.cppreference.com/w/c/numeric/complex/cexp)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the base-*e* exponential of `arg` (earg
) is returned.
If a range error due to overflow occurs, `[+HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ±0, 1 is returned
* If the argument is -∞, +0 is returned
* If the argument is +∞, +∞ is returned
* If the argument is NaN, NaN is returned
### Notes
For IEEE-compatible type `double`, overflow is guaranteed if 709.8 < arg, and underflow is guaranteed if arg < -708.4.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
printf("exp(1) = %f\n", exp(1));
printf("FV of $100, continuously compounded at 3%% for 1 year = %f\n",
100*exp(0.03));
// special values
printf("exp(-0) = %f\n", exp(-0.0));
printf("exp(-Inf) = %f\n", exp(-INFINITY));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("exp(710) = %f\n", exp(710));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_OVERFLOW)) puts(" FE_OVERFLOW raised");
}
```
Possible output:
```
exp(1) = 2.718282
FV of $100, continuously compounded at 3% for 1 year = 103.045453
exp(-0) = 1.000000
exp(-Inf) = 0.000000
exp(710) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.6.1 The exp functions (p: 175)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.3.1 The exp functions (p: 379)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.6.1 The exp functions (p: 242)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.1 The exp functions (p: 520)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.6.1 The exp functions (p: 223)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.3.1 The exp functions (p: 458)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.4.1 The exp function
### See also
| | |
| --- | --- |
| [exp2exp2fexp2l](exp2 "c/numeric/math/exp2")
(C99)(C99)(C99) | computes *2* raised to the given power (\({\small 2^x}\)2x) (function) |
| [expm1expm1fexpm1l](expm1 "c/numeric/math/expm1")
(C99)(C99)(C99) | computes *e* raised to the given power, minus one (\({\small e^x-1}\)ex-1) (function) |
| [loglogflogl](log "c/numeric/math/log")
(C99)(C99) | computes natural (base-*e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [cexpcexpfcexpl](../complex/cexp "c/numeric/complex/cexp")
(C99)(C99)(C99) | computes the complex base-e exponential (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/exp "cpp/numeric/math/exp") for `exp` |
c exp2, exp2f, exp2l exp2, exp2f, exp2l
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float exp2f( float n );
```
| (1) | (since C99) |
|
```
double exp2( double n );
```
| (2) | (since C99) |
|
```
long double exp2l( long double n );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define exp2( n )
```
| (4) | (since C99) |
1-3) Computes 2 raised to the given power `n`.
4) Type-generic macro: If `n` has type `long double`, `exp2l` is called. Otherwise, if `n` has integer type or the type `double`, `exp2` is called. Otherwise, `exp2f` is called. ### Parameters
| | | |
| --- | --- | --- |
| n | - | floating point value |
### Return value
If no errors occur, the base-*2* exponential of `n` (2n
) is returned.
If a range error due to overflow occurs, `[+HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ±0, 1 is returned
* If the argument is -∞, +0 is returned
* If the argument is +∞, +∞ is returned
* If the argument is NaN, NaN is returned
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
printf("exp2(5) = %f\n", exp2(5));
printf("exp2(0.5) = %f\n", exp2(0.5));
printf("exp2(-4) = %f\n", exp2(-4));
// special values
printf("exp2(-0.9) = %f\n", exp2(-0.9));
printf("exp2(-Inf) = %f\n", exp2(-INFINITY));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("exp2(1024) = %f\n", exp2(1024));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_OVERFLOW)) puts(" FE_OVERFLOW raised");
}
```
Possible output:
```
exp2(5) = 32.000000
exp2(0.5) = 1.414214
exp2(-4) = 0.062500
exp2(-0.9) = 0.535887
exp2(-Inf) = 0.000000
exp2(1024) = Inf
errno == ERANGE: Result too large
FE_OVERFLOW raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.6.2 The exp2 functions (p: 177)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.3.2 The exp2 functions (p: 379)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.6.2 The exp2 functions (p: 242-243)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.2 The exp2 functions (p: 521)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.6.2 The exp2 functions (p: 223)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.3.2 The exp2 functions (p: 458)
### See also
| | |
| --- | --- |
| [expexpfexpl](exp "c/numeric/math/exp")
(C99)(C99) | computes *e* raised to the given power (\({\small e^x}\)ex) (function) |
| [expm1expm1fexpm1l](expm1 "c/numeric/math/expm1")
(C99)(C99)(C99) | computes *e* raised to the given power, minus one (\({\small e^x-1}\)ex-1) (function) |
| [log2log2flog2l](log2 "c/numeric/math/log2")
(C99)(C99)(C99) | computes base-2 logarithm (\({\small \log\_{2}{x} }\)log2(x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/exp2 "cpp/numeric/math/exp2") for `exp2` |
c log1p, log1pf, log1pl log1p, log1pf, log1pl
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float log1pf( float arg );
```
| (1) | (since C99) |
|
```
double log1p( double arg );
```
| (2) | (since C99) |
|
```
long double log1pl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define log1p( arg )
```
| (4) | (since C99) |
1-3) Computes the natural (base `e`) logarithm of `1+arg`. This function is more precise than the expression `[log](http://en.cppreference.com/w/c/numeric/math/log)(1+arg)` if `arg` is close to zero.
4) Type-generic macro: If `arg` has type `long double`, `log1pl` is called. Otherwise, if `arg` has integer type or the type `double`, `log1p` is called. Otherwise, `log1pf` is called. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur ln(1+arg) is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a pole error occurs, `-HUGE_VAL`, `-HUGE_VALF`, or `-HUGE_VALL` is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
Domain error occurs if `arg` is less than -1.
Pole error may occur if `arg` is -1.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ±0, it is returned unmodified
* If the argument is -1, -∞ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* If the argument is less than -1, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* If the argument is +∞, +∞ is returned
* If the argument is NaN, NaN is returned
### Notes
The functions `[expm1](expm1 "c/numeric/math/expm1")` and `log1p` are useful for financial calculations, for example, when calculating small daily interest rates: (1+x)n
-1 can be expressed as `[expm1](http://en.cppreference.com/w/c/numeric/math/expm1)(n \* log1p(x))`. These functions also simplify writing accurate inverse hyperbolic functions.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
printf("log1p(0) = %f\n", log1p(0));
printf("Interest earned in 2 days on $100, compounded daily at 1%%\n"
" on a 30/360 calendar = %f\n",
100*expm1(2*log1p(0.01/360)));
printf("log(1+1e-16) = %g, but log1p(1e-16) = %g\n",
log(1+1e-16), log1p(1e-16));
// special values
printf("log1p(-0) = %f\n", log1p(-0.0));
printf("log1p(+Inf) = %f\n", log1p(INFINITY));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("log1p(-1) = %f\n", log1p(-1));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_DIVBYZERO)) puts(" FE_DIVBYZERO raised");
}
```
Possible output:
```
log1p(0) = 0.000000
Interest earned in 2 days on $100, compounded daily at 1%
on a 30/360 calendar = 0.005556
log(1+1e-16) = 0, but log1p(1e-16) = 1e-16
log1p(-0) = -0.000000
log1p(+Inf) = Inf
log1p(-1) = -Inf
errno == ERANGE: Result too large
FE_DIVBYZERO raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.6.9 The log1p functions (p: 245)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.9 The log1p functions (p: 522)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.6.9 The log1p functions (p: 226)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.3.9 The log1p functions (p: 459)
### See also
| | |
| --- | --- |
| [loglogflogl](log "c/numeric/math/log")
(C99)(C99) | computes natural (base-*e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [log10log10flog10l](log10 "c/numeric/math/log10")
(C99)(C99) | computes common (base-*10*) logarithm (\({\small \log\_{10}{x} }\)log10(x)) (function) |
| [log2log2flog2l](log2 "c/numeric/math/log2")
(C99)(C99)(C99) | computes base-2 logarithm (\({\small \log\_{2}{x} }\)log2(x)) (function) |
| [expm1expm1fexpm1l](expm1 "c/numeric/math/expm1")
(C99)(C99)(C99) | computes *e* raised to the given power, minus one (\({\small e^x-1}\)ex-1) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/log1p "cpp/numeric/math/log1p") for `log1p` |
c div, ldiv, lldiv, imaxdiv div, ldiv, lldiv, imaxdiv
=========================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
div_t div( int x, int y );
```
| (1) | |
|
```
ldiv_t ldiv( long x, long y );
```
| (2) | |
|
```
lldiv_t lldiv( long long x, long long y );
```
| (3) | (since C99) |
| Defined in header `<inttypes.h>` | | |
|
```
imaxdiv_t imaxdiv( intmax_t x, intmax_t y );
```
| (4) | (since C99) |
Computes both the quotient and the remainder of the division of the numerator `x` by the denominator `y`.
| | |
| --- | --- |
| Computes quotient and remainder simultaneously. The quotient is the algebraic quotient with any fractional part discarded (truncated towards zero). The remainder is such that `quot * y + rem == x`. | (until C99) |
| Computes the quotient (the result of the expression `x/y`) and remainder (the result of the expression `x%y`) simultaneously. | (since C99) |
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | integer values |
### Return value
If both the remainder and the quotient can be represented as objects of the corresponding type (`int`, `long`, `long long`, `imaxdiv_t`, respectively), returns both as an object of type `div_t`, `ldiv_t`, `lldiv_t`, `imaxdiv_t` defined as follows:
div\_t
-------
```
struct div_t { int quot; int rem; };
```
or.
```
struct div_t { int rem; int quot; };
```
ldiv\_t
--------
```
struct ldiv_t { long quot; long rem; };
```
or.
```
struct ldiv_t { long rem; long quot; };
```
lldiv\_t
---------
```
struct lldiv_t { long long quot; long long rem; };
```
or.
```
struct lldiv_t { long long rem; long long quot; };
```
imaxdiv\_t
-----------
```
struct imaxdiv_t { intmax_t quot; intmax_t rem; };
```
or.
```
struct imaxdiv_t { intmax_t rem; intmax_t quot; };
```
If either the remainder or the quotient cannot be represented, the behavior is undefined.
### Notes
Until C99, the rounding direction of the quotient and the sign of the remainder in the built-in division and remainder operators was implementation-defined if either of the operands was negative, but it was well-defined in `div` and `ldiv`.
On many platforms, a single CPU instruction obtains both the quotient and the remainder, and this function may leverage that, although compilers are generally able to merge nearby `/` and `%` where suitable.
### Example
```
#include <assert.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
void reverse(char* first, char* last) {
for (--last; first < last; ++first, --last) {
char c = *last;
*last = *first;
*first = c;
}
}
// demo only: does not check for buffer overflow
char* itoa(int n, int base, char* buf)
{
assert(2 <= base && base <= 16);
div_t dv = {.quot = n};
char* p = buf;
do {
dv = div(dv.quot, base);
*p++ = "0123456789abcdef"[abs(dv.rem)];
} while(dv.quot);
if(n<0) *p++ = '-';
*p = '\0';
reverse(buf, p);
return buf;
}
int main(void)
{
char buf[100];
printf("%s\n", itoa(0, 2, buf));
printf("%s\n", itoa(007, 3, buf));
printf("%s\n", itoa(12346, 10, buf));
printf("%s\n", itoa(-12346, 10, buf));
printf("%s\n", itoa(-42, 2, buf));
printf("%s\n", itoa(INT_MAX, 16, buf));
printf("%s\n", itoa(INT_MIN, 16, buf));
}
```
Possible output:
```
0
21
12346
-12346
-101010
7fffffff
-80000000
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.8.2.2 The imaxdiv function (p: 159)
+ 7.22.6.2 The div, ldiv and lldiv functions (p: 259)
* C11 standard (ISO/IEC 9899:2011):
+ 7.8.2.2 The imaxdiv function (p: 219)
+ 7.22.6.2 The div, ldiv and lldiv functions (p: 356)
* C99 standard (ISO/IEC 9899:1999):
+ 7.8.2.2 The imaxdiv function (p: 200)
+ 7.20.6.2 The div, ldiv and lldiv functions (p: 320)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10 div\_t, ldiv\_t
+ 4.10.6.2 The div function
+ 4.10.6.4 The ldiv function
### See also
| | |
| --- | --- |
| [fmodfmodffmodl](fmod "c/numeric/math/fmod")
(C99)(C99) | computes remainder of the floating-point division operation (function) |
| [remainderremainderfremainderl](remainder "c/numeric/math/remainder")
(C99)(C99)(C99) | computes signed remainder of the floating-point division operation (function) |
| [remquoremquofremquol](remquo "c/numeric/math/remquo")
(C99)(C99)(C99) | computes signed remainder as well as the three last bits of the division operation (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/div "cpp/numeric/math/div") for `div` |
### External links
* [Euclidean Division](https://en.wikipedia.org/wiki/Euclidean_Division "enwiki:Euclidean Division")
c ilogb, ilogbf, ilogbl ilogb, ilogbf, ilogbl
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
int ilogbf( float arg );
```
| (1) | (since C99) |
|
```
int ilogb( double arg );
```
| (2) | (since C99) |
|
```
int ilogbl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define ilogb( arg )
```
| (4) | (since C99) |
| Defined in header `<math.h>` | | |
|
```
#define FP_ILOGB0 /*implementation-defined*/
```
| (5) | (since C99) |
|
```
#define FP_ILOGBNAN /*implementation-defined*/
```
| (6) | (since C99) |
1-3) Extracts the value of the unbiased exponent from the floating-point argument `arg`, and returns it as a signed integer value.
4) Type-generic macros: If `arg` has type `long double`, `ilogbl` is called. Otherwise, if `arg` has integer type or the type `double`, `ilogb` is called. Otherwise, `ilogbf` is called.
5) Expands to integer constant expression whose value is either `[INT\_MIN](../../types/limits "c/types/limits")` or `-[INT\_MAX](http://en.cppreference.com/w/c/types/limits)`.
6) Expands to integer constant expression whose value is either `[INT\_MIN](../../types/limits "c/types/limits")` or `+[INT\_MAX](http://en.cppreference.com/w/c/types/limits)`. Formally, the unbiased exponent is the integral part of log
r|arg| as a signed integral value, for non-zero arg, where `r` is `[FLT\_RADIX](../../types/limits "c/types/limits")`.
### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the unbiased exponent of `arg` is returned as a signed int value.
If `arg` is zero, `FP_ILOGB0` is returned.
If `arg` is infinite, `[INT\_MAX](../../types/limits "c/types/limits")` is returned.
If `arg` is a NaN, `FP_ILOGBNAN` is returned.
If the correct result is greater than `[INT\_MAX](../../types/limits "c/types/limits")` or smaller than `[INT\_MIN](../../types/limits "c/types/limits")`, the return value is unspecified and a domain error or range error may occur.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
A domain error or range error may occur if `arg` is zero, infinite, or NaN.
If the correct result is greater than `[INT\_MAX](../../types/limits "c/types/limits")` or smaller than `[INT\_MIN](../../types/limits "c/types/limits")`, a domain error or a range error may occur.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the correct result is greater than `[INT\_MAX](../../types/limits "c/types/limits")` or smaller than `[INT\_MIN](../../types/limits "c/types/limits")`, `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* If `arg` is ±0, ±∞, or NaN, `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* In all other cases, the result is exact (`[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is never raised) and [the current rounding mode](../fenv/fe_round "c/numeric/fenv/FE round") is ignored
### Notes
If `arg` is not zero, infinite, or NaN, the value returned is exactly equivalent to `(int)[logb](http://en.cppreference.com/w/c/numeric/math/logb)(arg)`.
[POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/ilogb.html) that a domain error occurs if `arg` is zero, infinite, NaN, or if the correct result is outside of the range of `int`.
POSIX also requires that, on XSI-conformant systems, the value returned when the correct result is greater than `[INT\_MAX](../../types/limits "c/types/limits")` is `[INT\_MAX](../../types/limits "c/types/limits")` and the value returned when the correct result is less than `[INT\_MIN](../../types/limits "c/types/limits")` is `[INT\_MIN](../../types/limits "c/types/limits")`.
The correct result can be represented as `int` on all known implementations. For overflow to occur, `[INT\_MAX](../../types/limits "c/types/limits")` must be less than `[LDBL\_MAX\_EXP](http://en.cppreference.com/w/c/types/limits)\*log2([FLT\_RADIX](http://en.cppreference.com/w/c/types/limits))` or `[INT\_MIN](../../types/limits "c/types/limits")` must be greater than `LDBL_MIN_EXP-[LDBL\_MANT\_DIG](http://en.cppreference.com/w/c/types/limits))\*log2([FLT\_RADIX](http://en.cppreference.com/w/c/types/limits))`.
The value of the exponent returned by `ilogb` is always 1 less than the exponent retuned by `[frexp](frexp "c/numeric/math/frexp")` because of the different normalization requirements: for the exponent `e` returned by `ilogb`, |arg\*r-e
| is between 1 and `r` (typically between `1` and `2`), but for the exponent `e` returned by `[frexp](frexp "c/numeric/math/frexp")`, |arg\*2-e
| is between `0.5` and `1`.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
double f = 123.45;
printf("Given the number %.2f or %a in hex,\n", f, f);
double f3;
double f2 = modf(f, &f3);
printf("modf() makes %.0f + %.2f\n", f3, f2);
int i;
f2 = frexp(f, &i);
printf("frexp() makes %f * 2^%d\n", f2, i);
i = ilogb(f);
printf("logb()/ilogb() make %f * %d^%d\n", f/scalbn(1.0, i), FLT_RADIX, i);
// error handling
feclearexcept(FE_ALL_EXCEPT);
printf("ilogb(0) = %d\n", ilogb(0));
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
}
```
Possible output:
```
Given the number 123.45 or 0x1.edccccccccccdp+6 in hex,
modf() makes 123 + 0.45
frexp() makes 0.964453 * 2^7
logb()/ilogb() make 1.92891 * 2^6
ilogb(0) = -2147483648
FE_INVALID raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12/8 Mathematics <math.h> (p: 232)
+ 7.12.6.5 The ilogb functions (p: 244)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.5 The ilogb functions (p: 521)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12/8 Mathematics <math.h> (p: 213)
+ 7.12.6.5 The ilogb functions (p: 224-225)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.3.5 The ilogb functions (p: 458)
### See also
| | |
| --- | --- |
| [frexpfrexpffrexpl](frexp "c/numeric/math/frexp")
(C99)(C99) | breaks a number into significand and a power of `2` (function) |
| [logblogbflogbl](logb "c/numeric/math/logb")
(C99)(C99)(C99) | extracts exponent of the given number (function) |
| [scalbnscalbnfscalbnlscalblnscalblnfscalblnl](scalbn "c/numeric/math/scalbn")
(C99)(C99)(C99)(C99)(C99)(C99) | computes efficiently a number times `[FLT\_RADIX](../../types/limits "c/types/limits")` raised to a power (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/ilogb "cpp/numeric/math/ilogb") for `ilogb` |
| programming_docs |
c tgamma, tgammaf, tgammal tgamma, tgammaf, tgammal
========================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float tgammaf( float arg );
```
| (1) | (since C99) |
|
```
double tgamma( double arg );
```
| (2) | (since C99) |
|
```
long double tgammal( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define tgamma( arg )
```
| (4) | (since C99) |
1-3) Computes the [gamma function](https://en.wikipedia.org/wiki/Gamma_function "enwiki:Gamma function") of `arg`.
4) Type-generic macro: If `arg` has type `long double`, `tgammal` is called. Otherwise, if `arg` has integer type or the type `double`, `tgamma` is called. Otherwise, `tgammaf` is called. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the value of the gamma function of `arg`, that is \(\Gamma(\mathtt{arg}) = \displaystyle\int\_0^\infty\!\! t^{\mathtt{arg}-1} e^{-t}\, dt\)∫∞
0*t*arg-1
*e*-t d*t*, is returned.
If a domain error occurs, an implementation-defined value (NaN where supported) is returned.
If a pole error occurs, `[±HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `±HUGE_VALF`, or `±HUGE_VALL` is returned.
If a range error due to overflow occurs, `[±HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `±HUGE_VALF`, or `±HUGE_VALL` is returned.
If a range error due to underflow occurs, the correct value (after rounding) is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If `arg` is zero or is an integer less than zero, a pole error or a domain error may occur.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ±0, ±∞ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If the argument is a negative integer, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If the argument is -∞, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If the argument is +∞, +∞ is returned.
* If the argument is NaN, NaN is returned
### Notes
If `arg` is a natural number, `tgamma(arg)` is the factorial of `arg-1`. Many implementations calculate the exact integer-domain factorial if the argument is a sufficiently small integer.
For IEEE-compatible type `double`, overflow happens if `0 < x < 1/DBL_MAX` or if `x > 171.7`.
[POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/tgamma.html) that a pole error occurs if the argument is zero, but a domain error occurs when the argument is a negative integer. It also specifies that in future, domain errors may be replaced by pole errors for negative integer arguments (in which case the return value in those cases would change from NaN to ±∞).
There is a non-standard function named `gamma` in various implementations, but its definition is inconsistent. For example, glibc and 4.2BSD version of `gamma` executes `lgamma`, but 4.4BSD version of `gamma` executes `tgamma`.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
printf("tgamma(10) = %f, 9!=%f\n", tgamma(10), 2*3*4*5*6*7*8*9.0);
printf("tgamma(0.5) = %f, sqrt(pi) = %f\n", sqrt(acos(-1)), tgamma(0.5));
// special values
printf("tgamma(+Inf) = %f\n", tgamma(INFINITY));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("tgamma(-1) = %f\n", tgamma(-1));
if(errno == ERANGE) perror(" errno == ERANGE");
else if(errno == EDOM) perror(" errno == EDOM");
if(fetestexcept(FE_DIVBYZERO)) puts(" FE_DIVBYZERO raised");
else if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
}
```
Possible output:
```
tgamma(10) = 362880.000000, 9!=362880.000000
tgamma(0.5) = 1.772454, sqrt(pi) = 1.772454
tgamma(+Inf) = inf
tgamma(-1) = nan
errno == EDOM: Numerical argument out of domain
FE_INVALID raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.8.4 The tgamma functions (p: 250)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.5.4 The tgamma functions (p: 525)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.8.4 The tgamma functions (p: 231)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.5.4 The tgamma functions (p: 462)
### See also
| | |
| --- | --- |
| [lgammalgammaflgammal](lgamma "c/numeric/math/lgamma")
(C99)(C99)(C99) | computes natural (base-*e*) logarithm of the gamma function (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/tgamma "cpp/numeric/math/tgamma") for `tgamma` |
### External links
[Weisstein, Eric W. "Gamma Function."](http://mathworld.wolfram.com/GammaFunction.html) From MathWorld--A Wolfram Web Resource.
c ceil, ceilf, ceill ceil, ceilf, ceill
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float ceilf( float arg );
```
| (1) | (since C99) |
|
```
double ceil( double arg );
```
| (2) | |
|
```
long double ceill( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define ceil( arg )
```
| (4) | (since C99) |
1-3) Computes the smallest integer value not less than `arg`.
4) Type-generic macro: If `arg` has type `long double`, `ceill` is called. Otherwise, if `arg` has integer type or the type `double`, `ceil` is called. Otherwise, `ceilf` is called. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the smallest integer value not less than `arg`, that is ⌈arg⌉, is returned.
Return value ![math-ceil.svg]() Argument ### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* The current [rounding mode](../fenv/fe_round "c/numeric/fenv/FE round") has no effect.
* If `arg` is ±∞, it is returned, unmodified
* If `arg` is ±0, it is returned, unmodified
* If arg is NaN, NaN is returned
### Notes
`[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be (but isn't required to be) raised when rounding a non-integer finite value.
The largest representable floating-point values are exact integers in all standard floating-point formats, so this function never overflows on its own; however the result may overflow any integer type (including `[intmax\_t](../../types/integer "c/types/integer")`), when stored in an integer variable.
This function (for double argument) behaves as if (except for the freedom to not raise `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")`) implemented by.
```
#include <math.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
double ceil(double x)
{
double result;
int save_round = fegetround();
fesetround(FE_UPWARD);
result = rint(x); // or nearbyint
fesetround(save_round);
return result;
}
```
### Example
```
#include <math.h>
#include <stdio.h>
int main(void)
{
printf("ceil(+2.4) = %+.1f\n", ceil(2.4));
printf("ceil(-2.4) = %+.1f\n", ceil(-2.4));
printf("ceil(-0.0) = %+.1f\n", ceil(-0.0));
printf("ceil(-Inf) = %+f\n", ceil(-INFINITY));
}
```
Possible output:
```
ceil(+2.4) = +3.0
ceil(-2.4) = -2.0
ceil(-0.0) = -0.0
ceil(-Inf) = -inf
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.9.1 The ceil functions (p: 251)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.6.1 The ceil functions (p: 526)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.9.1 The ceil functions (p: 231-232)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.6.1 The ceil functions (p: 462-463)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.6.1 The ceil function
### See also
| | |
| --- | --- |
| [floorfloorffloorl](floor "c/numeric/math/floor")
(C99)(C99) | computes largest integer not greater than the given value (function) |
| [trunctruncftruncl](trunc "c/numeric/math/trunc")
(C99)(C99)(C99) | rounds to nearest integer not greater in magnitude than the given value (function) |
| [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](round "c/numeric/math/round")
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) | rounds to nearest integer, rounding away from zero in halfway cases (function) |
| [nearbyintnearbyintfnearbyintl](nearbyint "c/numeric/math/nearbyint")
(C99)(C99)(C99) | rounds to an integer using current rounding mode (function) |
| [rintrintfrintllrintlrintflrintlllrintllrintfllrintl](rint "c/numeric/math/rint")
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) | rounds to an integer using current rounding mode with exception if the result differs (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/ceil "cpp/numeric/math/ceil") for `ceil` |
c hypot, hypotf, hypotl hypot, hypotf, hypotl
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float hypotf( float x, float y );
```
| (1) | (since C99) |
|
```
double hypot( double x, double y );
```
| (2) | (since C99) |
|
```
long double hypotl( long double x, long double y );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define hypot( x, y )
```
| (4) | (since C99) |
1-3) Computes the square root of the sum of the squares of `x` and `y`, without undue overflow or underflow at intermediate stages of the computation.
4) Type-generic macro: If any argument has type `long double`, the long double version of the function is called. Otherwise, if any argument has integer type or has type `double`, the double version of the function is called. Otherwise, the `float` version of the function is called. The value computed by this function is the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or the distance of the point `(x,y)` from the origin `(0,0)`, or the magnitude of a complex number `x+*i*y`.
### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
If no errors occur, the hypotenuse of a right-angled triangle, \(\scriptsize{\sqrt{x^2+y^2} }\)√x2
+y2
, is returned.
If a range error due to overflow occurs, `[+HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
If a range error due to underflow occurs, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* `hypot(x, y)`, `hypot(y, x)`, and `hypot(x, -y)` are equivalent
* if one of the arguments is ±0, `hypot` is equivalent to `[fabs](http://en.cppreference.com/w/c/numeric/math/fabs)` called with the non-zero argument
* if one of the arguments is ±∞, `hypot` returns +∞ even if the other argument is NaN
* otherwise, if any of the arguments is NaN, NaN is returned
### Notes
Implementations usually guarantee precision of less than 1 ulp ([units in the last place](https://en.wikipedia.org/wiki/Unit_in_the_last_place "enwiki:Unit in the last place")): [GNU](http://sourceware.org/git/?p=glibc.git;a=blob_plain;f=sysdeps/ieee754/dbl-64/e_hypot.c), [BSD](http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/msun/src/e_hypot.c).
`hypot(x, y)` is equivalent to `[cabs](http://en.cppreference.com/w/c/numeric/complex/cabs)(x + I\*y)`.
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/hypot.html) that underflow may only occur when both arguments are subnormal and the correct result is also subnormal (this forbids naive implementations).
`hypot(INFINITY, NAN)` returns +∞, but `[sqrt](http://en.cppreference.com/w/c/numeric/math/sqrt)(INFINITY\*INFINITY+NAN\*NAN)` returns NaN.
### Example
```
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
#include <float.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
// typical usage
printf("(1,1) cartesian is (%f,%f) polar\n", hypot(1,1), atan2(1,1));
// special values
printf("hypot(NAN,INFINITY) = %f\n", hypot(NAN,INFINITY));
// error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("hypot(DBL_MAX,DBL_MAX) = %f\n", hypot(DBL_MAX,DBL_MAX));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_OVERFLOW)) puts(" FE_OVERFLOW raised");
}
```
Possible output:
```
(1,1) cartesian is (1.414214,0.785398) polar
hypot(NAN,INFINITY) = inf
hypot(DBL_MAX,DBL_MAX) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.7.3 The hypot functions (p: 181)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.4.3 The hypot functions (p: 382)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.7.3 The hypot functions (p: 248)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.4.3 The hypot functions (p: 524)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.7.3 The hypot functions (p: 229)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.4.3 The hypot functions (p: 461)
### See also
| | |
| --- | --- |
| [powpowfpowl](pow "c/numeric/math/pow")
(C99)(C99) | computes a number raised to the given power (\(\small{x^y}\)xy) (function) |
| [sqrtsqrtfsqrtl](sqrt "c/numeric/math/sqrt")
(C99)(C99) | computes square root (\(\small{\sqrt{x} }\)√x) (function) |
| [cbrtcbrtfcbrtl](cbrt "c/numeric/math/cbrt")
(C99)(C99)(C99) | computes cubic root (\(\small{\sqrt[3]{x} }\)3√x) (function) |
| [cabscabsfcabsl](../complex/cabs "c/numeric/complex/cabs")
(C99)(C99)(C99) | computes the magnitude of a complex number (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/hypot "cpp/numeric/math/hypot") for `hypot` |
c ldexp, ldexpf, ldexpl ldexp, ldexpf, ldexpl
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float ldexpf( float arg, int exp );
```
| (1) | (since C99) |
|
```
double ldexp( double arg, int exp );
```
| (2) | |
|
```
long double ldexpl( long double arg, int exp );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define ldexp( arg, exp )
```
| (4) | (since C99) |
1-3) Multiplies a floating point value `arg` by the number 2 raised to the `exp` power.
4) Type-generic macro: If `arg` has type `long double`, `ldexpl` is called. Otherwise, if `arg` has integer type or the type `double`, `ldexp` is called. Otherwise, `ldexpf` is called, respectively. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
| exp | - | integer value |
### Return value
If no errors occur, `arg` multiplied by 2 to the power of `exp` (arg×2exp
) is returned.
If a range error due to overflow occurs, `[±HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `±HUGE_VALF`, or `±HUGE_VALL` is returned.
If a range error due to underflow occurs, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* Unless a range error occurs, `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is never raised (the result is exact)
* Unless a range error occurs, the [current rounding mode](../fenv/fe_round "c/numeric/fenv/FE round") is ignored
* If `arg` is ±0, it is returned, unmodified
* If `arg` is ±∞, it is returned, unmodified
* If `exp` is 0, then `arg` is returned, unmodified
* If `arg` is NaN, NaN is returned
### Notes
On binary systems (where `[FLT\_RADIX](../../types/limits "c/types/limits")` is `2`), `ldexp` is equivalent to `[scalbn](scalbn "c/numeric/math/scalbn")`.
The function `ldexp` ("load exponent"), together with its dual, `[frexp](frexp "c/numeric/math/frexp")`, can be used to manipulate the representation of a floating-point number without direct bit manipulations.
On many implementations, `ldexp` is less efficient than multiplication or division by a power of two using arithmetic operators.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
printf("ldexp(7, -4) = %f\n", ldexp(7, -4));
printf("ldexp(1, -1074) = %g (minimum positive subnormal double)\n",
ldexp(1, -1074));
printf("ldexp(nextafter(1,0), 1024) = %g (largest finite double)\n",
ldexp(nextafter(1,0), 1024));
// special values
printf("ldexp(-0, 10) = %f\n", ldexp(-0.0, 10));
printf("ldexp(-Inf, -1) = %f\n", ldexp(-INFINITY, -1));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("ldexp(1, 1024) = %f\n", ldexp(1, 1024));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_OVERFLOW)) puts(" FE_OVERFLOW raised");
}
```
Possible output:
```
ldexp(7, -4) = 0.437500
ldexp(1, -1074) = 4.94066e-324 (minimum positive subnormal double)
ldexp(nextafter(1,0), 1024) = 1.79769e+308 (largest finite double)
ldexp(-0, 10) = -0.000000
ldexp(-Inf, -1) = -inf
ldexp(1, 1024) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.6.6 The ldexp functions (p: 244)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.6 The ldexp functions (p: 522)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.6.6 The ldexp functions (p: 225)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.3.6 The ldexp functions (p: 459)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.4.3 The ldexp function
### See also
| | |
| --- | --- |
| [frexpfrexpffrexpl](frexp "c/numeric/math/frexp")
(C99)(C99) | breaks a number into significand and a power of `2` (function) |
| [scalbnscalbnfscalbnlscalblnscalblnfscalblnl](scalbn "c/numeric/math/scalbn")
(C99)(C99)(C99)(C99)(C99)(C99) | computes efficiently a number times `[FLT\_RADIX](../../types/limits "c/types/limits")` raised to a power (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/ldexp "cpp/numeric/math/ldexp") for `ldexp` |
c signbit signbit
=======
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define signbit(arg) /* implementation defined */
```
| | (since C99) |
Determines if the given floating point number `arg` is negative. The macro returns an integral value.
### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
Nonzero integral value if `arg` is negative, `0` otherwise.
### Notes
This macro detects the sign bit of zeroes, infinities, and NaNs. Along with `[copysign](copysign "c/numeric/math/copysign")`, this macro is one of the only two portable ways to examine the sign of a NaN.
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("signbit(+0.0) = %d\n", signbit(+0.0));
printf("signbit(-0.0) = %d\n", signbit(-0.0));
}
```
Possible output:
```
signbit(+0.0) = 0
signbit(-0.0) = 128
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.3.6 The signbit macro (p: 237)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.3.6 The signbit macro (p: 218)
### See also
| | |
| --- | --- |
| [fabsfabsffabsl](fabs "c/numeric/math/fabs")
(C99)(C99) | computes absolute value of a floating-point value (\(\small{|x|}\)|x|) (function) |
| [copysigncopysignfcopysignl](copysign "c/numeric/math/copysign")
(C99)(C99)(C99) | produces a value with the magnitude of a given value and the sign of another given value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/signbit "cpp/numeric/math/signbit") for `signbit` |
| programming_docs |
c isgreaterequal isgreaterequal
==============
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define isgreaterequal(x, y) /* implementation defined */
```
| | (since C99) |
Determines if the floating point number `x` is greater than or equal to the floating-point number `y`, without setting floating-point exceptions.
### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
Nonzero integral value if `x >= y`, `0` otherwise.
### Notes
The built-in `operator>=` for floating-point numbers may raise `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` if one or both of the arguments is NaN. This function is a "quiet" version of `operator>=`.
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("isgreaterequal(2.0,1.0) = %d\n", isgreaterequal(2.0,1.0));
printf("isgreaterequal(1.0,2.0) = %d\n", isgreaterequal(1.0,2.0));
printf("isgreaterequal(1.0,1.0) = %d\n", isgreaterequal(1.0,1.0));
printf("isgreaterequal(INFINITY,1.0) = %d\n", isgreaterequal(INFINITY,1.0));
printf("isgreaterequal(1.0,NAN) = %d\n", isgreaterequal(1.0,NAN));
return 0;
}
```
Possible output:
```
isgreaterequal(2.0,1.0) = 1
isgreaterequal(1.0,2.0) = 0
isgreaterequal(1.0,1.0) = 1
isgreaterequal(INFINITY,1.0) = 1
isgreaterequal(1.0,NAN) = 0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.14.2 The isgreaterequal macro (p: 259-260)
+ F.10.11 Comparison macros (p: 531)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.14.2 The isgreaterequal macro (p: 240-241)
### See also
| | |
| --- | --- |
| [islessequal](islessequal "c/numeric/math/islessequal")
(C99) | checks if the first floating-point argument is less or equal than the second (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/isgreaterequal "cpp/numeric/math/isgreaterequal") for `isgreaterequal` |
c sinh, sinhf, sinhl sinh, sinhf, sinhl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float sinhf( float arg );
```
| (1) | (since C99) |
|
```
double sinh( double arg );
```
| (2) | |
|
```
long double sinhl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define sinh( arg )
```
| (4) | (since C99) |
1-3) Computes hyperbolic sine of `arg`.
4) Type-generic macro: If the argument has type `long double`, `sinhl` is called. Otherwise, if the argument has integer type or the type `double`, `sinh` is called. Otherwise, `sinhf` is called. If the argument is complex, then the macro invokes the corresponding complex function (`[csinhf](http://en.cppreference.com/w/c/numeric/complex/csinh)`, `[csinh](http://en.cppreference.com/w/c/numeric/complex/csinh)`, `[csinhl](http://en.cppreference.com/w/c/numeric/complex/csinh)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value representing a hyperbolic angle |
### Return value
If no errors occur, the hyperbolic sine of `arg` (sinh(arg), or earg-e-arg/2) is returned. If a range error due to overflow occurs, `[±HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `±HUGE_VALF`, or `±HUGE_VALL` is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ±0 or ±∞, it is returned unmodified
* if the argument is NaN, NaN is returned
### Notes
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sinh.html) that in case of underflow, `arg` is returned unmodified, and if that is not supported, an implementation-defined value no greater than `[DBL\_MIN](../../types/limits "c/types/limits")`, `[FLT\_MIN](../../types/limits "c/types/limits")`, and `[LDBL\_MIN](../../types/limits "c/types/limits")` is returned.
### Example
```
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
printf("sinh(1) = %f\nsinh(-1)=%f\n", sinh(1), sinh(-1));
printf("log(sinh(1) + cosh(1))=%f\n", log(sinh(1)+cosh(1)));
// special values
printf("sinh(+0) = %f\nsinh(-0)=%f\n", sinh(0.0), sinh(-0.0));
// error handling
errno=0; feclearexcept(FE_ALL_EXCEPT);
printf("sinh(710.5) = %f\n", sinh(710.5));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_OVERFLOW)) puts(" FE_OVERFLOW raised");
}
```
Possible output:
```
sinh(1) = 1.175201
sinh(-1)=-1.175201
log(sinh(1) + cosh(1))=1.000000
sinh(+0) = 0.000000
sinh(-0)=-0.000000
sinh(710.5) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.5.5 The sinh functions (p: 176)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.2.5 The sinh functions (p: 379)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.5.5 The sinh functions (p: 241-242)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.2.5 The sinh functions (p: 520)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.5.5 The sinh functions (p: 222)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.2.5 The sinh functions (p: 457)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.3.2 The sinh function
### See also
| | |
| --- | --- |
| [coshcoshfcoshl](cosh "c/numeric/math/cosh")
(C99)(C99) | computes hyperbolic cosine (\({\small\cosh{x} }\)cosh(x)) (function) |
| [tanhtanhftanhl](tanh "c/numeric/math/tanh")
(C99)(C99) | computes hyperbolic tangent (\({\small\tanh{x} }\)tanh(x)) (function) |
| [asinhasinhfasinhl](asinh "c/numeric/math/asinh")
(C99)(C99)(C99) | computes inverse hyperbolic sine (\({\small\operatorname{arsinh}{x} }\)arsinh(x)) (function) |
| [csinhcsinhfcsinhl](../complex/csinh "c/numeric/complex/csinh")
(C99)(C99)(C99) | computes the complex hyperbolic sine (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/sinh "cpp/numeric/math/sinh") for `sinh` |
c lgamma, lgammaf, lgammal lgamma, lgammaf, lgammal
========================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float lgammaf( float arg );
```
| (1) | (since C99) |
|
```
double lgamma( double arg );
```
| (2) | (since C99) |
|
```
long double lgammal( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define lgamma( arg )
```
| (4) | (since C99) |
1-3) Computes the natural logarithm of the absolute value of the [gamma function](https://en.wikipedia.org/wiki/Gamma_function "enwiki:Gamma function") of `arg`.
4) Type-generic macro: If `arg` has type `long double`, `lgammal` is called. Otherwise, if `arg` has integer type or the type `double`, `lgamma` is called. Otherwise, `lgammaf` is called. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the value of the logarithm of the gamma function of `arg`, that is \(\log\_{e}|{\int\_0^\infty t^{arg-1} e^{-t} \mathsf{d}t}|\)log
e|∫∞
0*t*arg-1
*e*-t d*t*|, is returned.
If a pole error occurs, `[+HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
If a range error due to overflow occurs, `[±HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `±HUGE_VALF`, or `±HUGE_VALL` is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If `arg` is zero or is an integer less than zero, a pole error may occur.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is 1, +0 is returned
* If the argument is 2, +0 is returned
* If the argument is ±0, +∞ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If the argument is a negative integer, +∞ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If the argument is ±∞, +∞ is returned.
* If the argument is NaN, NaN is returned
### Notes
If `arg` is a natural number, `lgamma(arg)` is the logarithm of the factorial of `arg-1`.
The [POSIX version of `lgamma`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/lgamma.html) is not thread-safe: each execution of the function stores the sign of the gamma function of `arg` in the static external variable `signgam`. Some implementations provide `lgamma_r`, which takes a pointer to user-provided storage for singgam as the second parameter, and is thread-safe.
There is a non-standard function named `gamma` in various implementations, but its definition is inconsistent. For example, glibc and 4.2BSD version of `gamma` executes `lgamma`, but 4.4BSD version of `gamma` executes `tgamma`.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
printf("lgamma(10) = %f, log(9!)=%f\n", lgamma(10), log(2*3*4*5*6*7*8*9));
double pi = acos(-1);
printf("lgamma(0.5) = %f, log(sqrt(pi)) = %f\n", log(sqrt(pi)), lgamma(0.5));
// special values
printf("lgamma(1) = %f\n", lgamma(1));
printf("lgamma(+Inf) = %f\n", lgamma(INFINITY));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("lgamma(0) = %f\n", lgamma(0));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_DIVBYZERO)) puts(" FE_DIVBYZERO raised");
}
```
Possible output:
```
lgamma(10) = 12.801827, log(9!)=12.801827
lgamma(0.5) = 0.572365, log(sqrt(pi)) = 0.572365
lgamma(1) = 0.000000
lgamma(+Inf) = inf
lgamma(0) = inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.8.3 The lgamma functions (p: 182)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.5.3 The lgamma functions (p: 383)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.8.3 The lgamma functions (p: 250)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.5.3 The lgamma functions (p: 525)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.8.3 The lgamma functions (p: 231)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.5.3 The lgamma functions (p: 462)
### See also
| | |
| --- | --- |
| [tgammatgammaftgammal](tgamma "c/numeric/math/tgamma")
(C99)(C99)(C99) | computes gamma function (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/lgamma "cpp/numeric/math/lgamma") for `lgamma` |
### External links
[Weisstein, Eric W. "Log Gamma Function."](http://mathworld.wolfram.com/LogGammaFunction.html) From MathWorld--A Wolfram Web Resource.
c isnan isnan
=====
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define isnan(arg) /* implementation defined */
```
| | (since C99) |
Determines if the given floating point number `arg` is a not-a-number (NaN) value. The macro returns an integral value.
`[FLT\_EVAL\_METHOD](../../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")` is ignored: even if the argument is evaluated with more range and precision than its type, it is first converted to its semantic type, and the classification is based on that (this matters if the evaluation type supports NaNs, while the semantic type does not).
### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
Nonzero integral value if `arg` is a NaN, `0` otherwise.
### Notes
There are many different NaN values with different sign bits and payloads, see `[nan](nan "c/numeric/math/nan")`.
NaN values never compare equal to themselves or to other NaN values. Copying a NaN may change its bit pattern.
Another way to test if a floating-point value is NaN is to compare it with itself: `bool is_nan(double x) { return x != x; }`
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
int main(void)
{
printf("isnan(NAN) = %d\n", isnan(NAN));
printf("isnan(INFINITY) = %d\n", isnan(INFINITY));
printf("isnan(0.0) = %d\n", isnan(0.0));
printf("isnan(DBL_MIN/2.0) = %d\n", isnan(DBL_MIN/2.0));
printf("isnan(0.0 / 0.0) = %d\n", isnan(0.0/0.0));
printf("isnan(Inf - Inf) = %d\n", isnan(INFINITY - INFINITY));
}
```
Possible output:
```
isnan(NAN) = 1
isnan(INFINITY) = 0
isnan(0.0) = 0
isnan(DBL_MIN/2.0) = 0
isnan(0.0 / 0.0) = 1
isnan(Inf - Inf) = 1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.3.4 The isnan macro (p: 236-237)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.3.4 The isnan macro (p: 217)
### See also
| | |
| --- | --- |
| [nannanfnanl](nan "c/numeric/math/nan")
(C99)(C99)(C99) | returns a NaN (not-a-number) (function) |
| [fpclassify](fpclassify "c/numeric/math/fpclassify")
(C99) | classifies the given floating-point value (function macro) |
| [isfinite](isfinite "c/numeric/math/isfinite")
(C99) | checks if the given number has finite value (function macro) |
| [isinf](isinf "c/numeric/math/isinf")
(C99) | checks if the given number is infinite (function macro) |
| [isnormal](isnormal "c/numeric/math/isnormal")
(C99) | checks if the given number is normal (function macro) |
| [isunordered](isunordered "c/numeric/math/isunordered")
(C99) | checks if two floating-point values are unordered (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/isnan "cpp/numeric/math/isnan") for `isnan` |
c FP_NORMAL, FP_SUBNORMAL, FP_ZERO, FP_INFINITE, FP_NAN FP\_NORMAL, FP\_SUBNORMAL, FP\_ZERO, FP\_INFINITE, FP\_NAN
==========================================================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define FP_NORMAL /*implementation defined*/
```
| | (since C99) |
|
```
#define FP_SUBNORMAL /*implementation defined*/
```
| | (since C99) |
|
```
#define FP_ZERO /*implementation defined*/
```
| | (since C99) |
|
```
#define FP_INFINITE /*implementation defined*/
```
| | (since C99) |
|
```
#define FP_NAN /*implementation defined*/
```
| | (since C99) |
The `FP_NORMAL`, `FP_SUBNORMAL`, `FP_ZERO`, `FP_INFINITE`, `FP_NAN` macros each represent a distinct category of floating-point numbers. They all expand to an integer constant expression.
| Constant | Explanation |
| --- | --- |
| `FP_NORMAL` | indicates that the value is *normal*, i.e. not an infinity, subnormal, not-a-number or zero |
| `FP_SUBNORMAL` | indicates that the value is [*subnormal*](https://en.wikipedia.org/wiki/Subnormal_number "enwiki:Subnormal number") |
| `FP_ZERO` | indicates that the value is positive or negative zero |
| `FP_INFINITE` | indicates that the value is not representable by the underlying type (positive or negative infinity) |
| `FP_NAN` | indicates that the value is not-a-number (NaN) |
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
const char *show_classification(double x) {
switch(fpclassify(x)) {
case FP_INFINITE: return "Inf";
case FP_NAN: return "NaN";
case FP_NORMAL: return "normal";
case FP_SUBNORMAL: return "subnormal";
case FP_ZERO: return "zero";
default: return "unknown";
}
}
int main(void)
{
printf("1.0/0.0 is %s\n", show_classification(1/0.0));
printf("0.0/0.0 is %s\n", show_classification(0.0/0.0));
printf("DBL_MIN/2 is %s\n", show_classification(DBL_MIN/2));
printf("-0.0 is %s\n", show_classification(-0.0));
printf(" 1.0 is %s\n", show_classification(1.0));
}
```
Output:
```
1.0/0.0 is Inf
0.0/0.0 is NaN
DBL_MIN/2 is subnormal
-0.0 is zero
1.0 is normal
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12/6 FP\_NORMAL, ... (p: 169-170)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12/6 FP\_NORMAL, ... (p: 232)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12/6 FP\_NORMAL, ... (p: 213)
### See also
| | |
| --- | --- |
| [fpclassify](fpclassify "c/numeric/math/fpclassify")
(C99) | classifies the given floating-point value (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/FP_categories "cpp/numeric/math/FP categories") for `FP_categories` |
c acosh, acoshf, acoshl acosh, acoshf, acoshl
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float acoshf( float arg );
```
| (1) | (since C99) |
|
```
double acosh( double arg );
```
| (2) | (since C99) |
|
```
long double acoshl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define acosh( arg )
```
| (4) | (since C99) |
1-3) Computes the inverse hyperbolic cosine of `arg`.
4) Type-generic macro: If the argument has type `long double`, `acoshl` is called. Otherwise, if the argument has integer type or the type `double`, `acosh` is called. Otherwise, `acoshf` is called. If the argument is complex, then the macro invokes the corresponding complex function (`[cacoshf](http://en.cppreference.com/w/c/numeric/complex/cacosh)`, `[cacosh](http://en.cppreference.com/w/c/numeric/complex/cacosh)`, `[cacoshl](http://en.cppreference.com/w/c/numeric/complex/cacosh)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value representing the area of a hyperbolic sector |
### Return value
If no errors occur, the inverse hyperbolic cosine of `arg` (cosh-1
(arg), or arcosh(arg)) on the interval [0, +∞], is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the argument is less than 1, a domain error occurs.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is less than 1, `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised an NaN is returned
* if the argument is 1, +0 is returned
* if the argument is +∞, +∞ is returned
* if the argument is NaN, NaN is returned
### Notes
Although the C standard names this function "arc hyperbolic cosine", the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct name is "inverse hyperbolic cosine" (used by POSIX) or "area hyperbolic cosine".
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
printf("acosh(1) = %f\nacosh(10) = %f\n", acosh(1), acosh(10));
printf("acosh(DBL_MAX) = %f\nacosh(Inf) = %f\n", acosh(DBL_MAX), acosh(INFINITY));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("acosh(0.5) = %f\n", acosh(0.5));
if(errno == EDOM) perror(" errno == EDOM");
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
}
```
Possible output:
```
acosh(1) = 0.000000
acosh(10) = 2.993223
acosh(DBL_MAX) = 710.475860
acosh(Inf) = inf
acosh(0.5) = -nan
errno == EDOM: Numerical argument out of domain
FE_INVALID raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.5.1 The acosh functions (p: 240)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.2.1 The acosh functions (p: 520)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.5.1 The acosh functions (p: 221)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.2.1 The acosh functions (p: 457)
### See also
| | |
| --- | --- |
| [asinhasinhfasinhl](asinh "c/numeric/math/asinh")
(C99)(C99)(C99) | computes inverse hyperbolic sine (\({\small\operatorname{arsinh}{x} }\)arsinh(x)) (function) |
| [atanhatanhfatanhl](atanh "c/numeric/math/atanh")
(C99)(C99)(C99) | computes inverse hyperbolic tangent (\({\small\operatorname{artanh}{x} }\)artanh(x)) (function) |
| [coshcoshfcoshl](cosh "c/numeric/math/cosh")
(C99)(C99) | computes hyperbolic cosine (\({\small\cosh{x} }\)cosh(x)) (function) |
| [cacoshcacoshfcacoshl](../complex/cacosh "c/numeric/complex/cacosh")
(C99)(C99)(C99) | computes the complex arc hyperbolic cosine (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/acosh "cpp/numeric/math/acosh") for `acosh` |
### External links
[Weisstein, Eric W. "Inverse Hyperbolic Cosine."](http://mathworld.wolfram.com/InverseHyperbolicCosine.html) From MathWorld--A Wolfram Web Resource.
| programming_docs |
c log, logf, logl log, logf, logl
===============
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float logf( float arg );
```
| (1) | (since C99) |
|
```
double log( double arg );
```
| (2) | |
|
```
long double logl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define log( arg )
```
| (4) | (since C99) |
1-3) Computes the natural (base *e*) logarithm of `arg`.
4) Type-generic macro: If `arg` has type `long double`, `logl` is called. Otherwise, if `arg` has integer type or the type `double`, `log` is called. Otherwise, `logf` is called. If `arg` is complex or imaginary, then the macro invokes the corresponding complex function (`[clogf](http://en.cppreference.com/w/c/numeric/complex/clog)`, `[clog](http://en.cppreference.com/w/c/numeric/complex/clog)`, `[clogl](http://en.cppreference.com/w/c/numeric/complex/clog)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the natural (base-*e*) logarithm of `arg` (ln(arg) or log
e(arg)) is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a pole error occurs, `[-HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `-HUGE_VALF`, or `-HUGE_VALL` is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
Domain error occurs if `arg` is less than zero.
Pole error may occur if `arg` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ±0, -∞ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* If the argument is 1, +0 is returned
* If the argument is negative, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* If the argument is +∞, +∞ is returned
* If the argument is NaN, NaN is returned
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
printf("log(1) = %f\n", log(1));
printf("base-5 logarithm of 125 = %f\n", log(125)/log(5));
// special values
printf("log(1) = %f\n", log(1));
printf("log(+Inf) = %f\n", log(INFINITY));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("log(0) = %f\n", log(0));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_DIVBYZERO)) puts(" FE_DIVBYZERO raised");
}
```
Output:
```
log(1) = 0.000000
base-5 logarithm of 125 = 3.000000
log(1) = 0.000000
log(+Inf) = inf
log(0) = -inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.6.7 The log functions (p: 178-179)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.3.7 The log functions (p: 380)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.6.7 The log functions (p: 244-245)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.7 The log functions (p: 522)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.6.7 The log functions (p: 225)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.3.7 The log functions (p: 459)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.4.4 The log function
### See also
| | |
| --- | --- |
| [log10log10flog10l](log10 "c/numeric/math/log10")
(C99)(C99) | computes common (base-*10*) logarithm (\({\small \log\_{10}{x} }\)log10(x)) (function) |
| [log2log2flog2l](log2 "c/numeric/math/log2")
(C99)(C99)(C99) | computes base-2 logarithm (\({\small \log\_{2}{x} }\)log2(x)) (function) |
| [log1plog1pflog1pl](log1p "c/numeric/math/log1p")
(C99)(C99)(C99) | computes natural (base-*e*) logarithm of 1 plus the given number (\({\small \ln{(1+x)} }\)ln(1+x)) (function) |
| [expexpfexpl](exp "c/numeric/math/exp")
(C99)(C99) | computes *e* raised to the given power (\({\small e^x}\)ex) (function) |
| [clogclogfclogl](../complex/clog "c/numeric/complex/clog")
(C99)(C99)(C99) | computes the complex natural logarithm (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/log "cpp/numeric/math/log") for `log` |
c expm1, expm1f, expm1l expm1, expm1f, expm1l
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float expm1f( float arg );
```
| (1) | (since C99) |
|
```
double expm1( double arg );
```
| (2) | (since C99) |
|
```
long double expm1l( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define expm1( arg )
```
| (4) | (since C99) |
1-3) Computes the *e* (Euler's number, `2.7182818`) raised to the given power `arg`, minus `1.0`. This function is more accurate than the expression `[exp](http://en.cppreference.com/w/c/numeric/math/exp)(arg)-1.0` if `arg` is close to zero.
4) Type-generic macro: If `arg` has type `long double`, `expm1l` is called. Otherwise, if `arg` has integer type or the type `double`, `expm1` is called. Otherwise, `expm1f` is called. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur earg
-1 is returned.
If a range error due to overflow occurs, `[+HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `math_errhandling`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ±0, it is returned, unmodified
* If the argument is -∞, -1 is returned
* If the argument is +∞, +∞ is returned
* If the argument is NaN, NaN is returned
### Notes
The functions `expm1` and `[log1p](log1p "c/numeric/math/log1p")` are useful for financial calculations, for example, when calculating small daily interest rates: (1+x)n
-1 can be expressed as `expm1(n \* [log1p](http://en.cppreference.com/w/c/numeric/math/log1p)(x))`. These functions also simplify writing accurate inverse hyperbolic functions.
For IEEE-compatible type `double`, overflow is guaranteed if 709.8 < arg.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
printf("expm1(1) = %f\n", expm1(1));
printf("Interest earned in 2 days on $100, compounded daily at 1%%\n"
" on a 30/360 calendar = %f\n",
100*expm1(2*log1p(0.01/360)));
printf("exp(1e-16)-1 = %g, but expm1(1e-16) = %g\n",
exp(1e-16)-1, expm1(1e-16));
// special values
printf("expm1(-0) = %f\n", expm1(-0.0));
printf("expm1(-Inf) = %f\n", expm1(-INFINITY));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("expm1(710) = %f\n", expm1(710));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_OVERFLOW)) puts(" FE_OVERFLOW raised");
}
```
Possible output:
```
expm1(1) = 1.718282
Interest earned in 2 days on $100, compounded daily at 1%
on a 30/360 calendar = 0.005556
exp(1e-16)-1 = 0, but expm1(1e-16) = 1e-16
expm1(-0) = -0.000000
expm1(-Inf) = -1.000000
expm1(710) = inf
errno == ERANGE: Result too large
FE_OVERFLOW raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.6.3 The expm1 functions (p: 177)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.3.3 The expm1 functions (p: 379)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.6.3 The expm1 functions (p: 243)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.3 The expm1 functions (p: 521)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.6.3 The expm1 functions (p: 223-224)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.3.3 The expm1 functions (p: 458)
### See also
| | |
| --- | --- |
| [expexpfexpl](exp "c/numeric/math/exp")
(C99)(C99) | computes *e* raised to the given power (\({\small e^x}\)ex) (function) |
| [exp2exp2fexp2l](exp2 "c/numeric/math/exp2")
(C99)(C99)(C99) | computes *2* raised to the given power (\({\small 2^x}\)2x) (function) |
| [log1plog1pflog1pl](log1p "c/numeric/math/log1p")
(C99)(C99)(C99) | computes natural (base-*e*) logarithm of 1 plus the given number (\({\small \ln{(1+x)} }\)ln(1+x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/expm1 "cpp/numeric/math/expm1") for `expm1` |
c abs, labs, llabs, imaxabs abs, labs, llabs, imaxabs
=========================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
int abs( int n );
```
| | |
|
```
long labs( long n );
```
| | |
|
```
long long llabs( long long n );
```
| | (since C99) |
| Defined in header `<inttypes.h>` | | |
|
```
intmax_t imaxabs( intmax_t n );
```
| | (since C99) |
Computes the absolute value of an integer number. The behavior is undefined if the result cannot be represented by the return type.
### Parameters
| | | |
| --- | --- | --- |
| n | - | integer value |
### Return value
The absolute value of `n` (i.e. `|n|`), if it is representable.
### Notes
In 2's complement systems, the absolute value of the most-negative value is out of range, e.g. for 32-bit 2's complement type `int`, `[INT\_MIN](../../types/limits "c/types/limits")` is `-2147483648`, but the would-be result `2147483648` is greater than `[INT\_MAX](../../types/limits "c/types/limits")`, which is `2147483647`.
### Example
```
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main(void)
{
printf("abs(+3) = %d\n", abs(+3));
printf("abs(-3) = %d\n", abs(-3));
// printf("%+d\n", abs(INT_MIN)); // undefined behavior on 2's complement systems
}
```
Output:
```
abs(+3) = 3
abs(-3) = 3
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.8.2.1 The imaxabs function (p: 159)
+ 7.22.6.1 The abs, labs and llabs functions (p: 259)
* C11 standard (ISO/IEC 9899:2011):
+ 7.8.2.1 The imaxabs function (p: 218)
+ 7.22.6.1 The abs, labs and llabs functions (p: 356)
* C99 standard (ISO/IEC 9899:1999):
+ 7.8.2.1 The imaxabs function (p: 199-200)
+ 7.20.6.1 The abs, labs and llabs functions (p: 320)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.6.1 The abs function
+ 4.10.6.3 The labs function
### See also
| | |
| --- | --- |
| [fabsfabsffabsl](fabs "c/numeric/math/fabs")
(C99)(C99) | computes absolute value of a floating-point value (\(\small{|x|}\)|x|) (function) |
| [cabscabsfcabsl](../complex/cabs "c/numeric/complex/cabs")
(C99)(C99)(C99) | computes the magnitude of a complex number (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/abs "cpp/numeric/math/abs") for `abs` |
c HUGE_VALF, HUGE_VAL, HUGE_VALL HUGE\_VALF, HUGE\_VAL, HUGE\_VALL
=================================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define HUGE_VALF /*implementation defined*/
```
| | (since C99) |
|
```
#define HUGE_VAL /*implementation defined*/
```
| | |
|
```
#define HUGE_VALL /*implementation defined*/
```
| | (since C99) |
The `HUGE_VALF`, `HUGE_VAL` and `HUGE_VALL` macros expand to positive floating point constant expressions which compare equal to the values returned by floating-point functions and operators in case of overflow (see [math\_errhandling](math_errhandling "c/numeric/math/math errhandling")).
| Constant | Explanation |
| --- | --- |
| `HUGE_VALF` | Expands to positive `float` expression that indicates overflow |
| `HUGE_VAL` | Expands to positive `double` expression that indicates overflow, not necessarily representable as a `float` |
| `HUGE_VALL` | Expands to positive `long double` expression that indicates overflow, not necessarily representable as a `float` or `double` |
On implementations that support floating-point infinities, these macros always expand to the positive infinities of `float`, `double`, and `long double`, respectively.
### Example
```
#include <math.h>
#include <stdio.h>
int main(void)
{
double result = 1.0/0.0;
printf("1.0/0.0 = %f\n", result);
if (result == HUGE_VAL)
puts("1.0/0.0 == HUGE_VAL\n");
}
```
Possible output:
```
1.0/0.0 = inf
1.0/0.0 == HUGE_VAL
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12/3 HUGE\_VAL, HUGE\_VALF, HUGE\_VALL (p: 231)
+ F.10/2 HUGE\_VAL, HUGE\_VALF, HUGE\_VALL (p: 517)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12/3 HUGE\_VAL, HUGE\_VALF, HUGE\_VALL (p: 212)
+ F.9/2 HUGE\_VAL, HUGE\_VALF, HUGE\_VALL (p: 454)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5 HUGE\_VAL
### See also
| | |
| --- | --- |
| [INFINITY](infinity "c/numeric/math/INFINITY")
(C99) | evaluates to positive infinity or the value guaranteed to overflow a `float` (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/HUGE_VAL "cpp/numeric/math/HUGE VAL") for `HUGE_VAL` |
c fmod, fmodf, fmodl fmod, fmodf, fmodl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float fmodf( float x, float y );
```
| (1) | (since C99) |
|
```
double fmod( double x, double y );
```
| (2) | |
|
```
long double fmodl( long double x, long double y );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define fmod( x, y )
```
| (4) | (since C99) |
1-3) Computes the floating-point remainder of the division operation `x/y`.
4) Type-generic macro: If any argument has type `long double`, `fmodl` is called. Otherwise, if any argument has integer type or has type `double`, `fmod` is called. Otherwise, `fmodf` is called. The floating-point remainder of the division operation `x/y` calculated by this function is exactly the value `x - n*y`, where `n` is `x/y` with its fractional part truncated.
The returned value has the same sign as `x` and is less or equal to `y` in magnitude.
### Parameters
| | | |
| --- | --- | --- |
| x, y | - | floating point values |
### Return value
If successful, returns the floating-point remainder of the division `x/y` as defined above.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
Domain error may occur if `y` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If `x` is ±0 and `y` is not zero, ±0 is returned
* If `x` is ±∞ and `y` is not NaN, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `y` is ±0 and `x` is not NaN, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If `y` is ±∞ and `x` is finite, `x` is returned.
* If either argument is NaN, NaN is returned
### Notes
[POSIX requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fmod.html) that a domain error occurs if `x` is infinite or `y` is zero.
`fmod`, but not `[remainder](remainder "c/numeric/math/remainder")` is useful for doing silent wrapping of floating-point types to unsigned integer types: `(0.0 <= (y = fmod([rint](http://en.cppreference.com/w/c/numeric/math/rint)(x), 65536.0 )) ? y : 65536.0 + y)` is in the range `[-0.0 .. 65535.0]`, which corresponds to `unsigned short`, but `[remainder](http://en.cppreference.com/w/c/numeric/math/remainder)([rint](http://en.cppreference.com/w/c/numeric/math/rint)(x), 65536.0)` is in the range `[-32767.0, +32768.0]`, which is outside of the range of `signed short`.
The `double` version of `fmod` behaves as if implemented as follows:
```
double fmod(double x, double y)
{
#pragma STDC FENV_ACCESS ON
double result = remainder(fabs(x), (y = fabs(y)));
if (signbit(result)) result += y;
return copysign(result, x);
}
```
### Example
```
#include <stdio.h>
#include <math.h>
#include <fenv.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
printf("fmod(+5.1, +3.0) = %.1f\n", fmod(5.1,3));
printf("fmod(-5.1, +3.0) = %.1f\n", fmod(-5.1,3));
printf("fmod(+5.1, -3.0) = %.1f\n", fmod(5.1,-3));
printf("fmod(-5.1, -3.0) = %.1f\n", fmod(-5.1,-3));
// special values
printf("fmod(+0.0, 1.0) = %.1f\n", fmod(0, 1));
printf("fmod(-0.0, 1.0) = %.1f\n", fmod(-0.0, 1));
printf("fmod(+5.1, Inf) = %.1f\n", fmod(5.1, INFINITY));
// error handling
feclearexcept(FE_ALL_EXCEPT);
printf("fmod(+5.1, 0) = %.1f\n", fmod(5.1, 0));
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
}
```
Possible output:
```
fmod(+5.1, +3.0) = 2.1
fmod(-5.1, +3.0) = -2.1
fmod(+5.1, -3.0) = 2.1
fmod(-5.1, -3.0) = -2.1
fmod(+0.0, 1.0) = 0.0
fmod(-0.0, 1.0) = -0.0
fmod(+5.1, Inf) = 5.1
fmod(+5.1, 0) = nan
FE_INVALID raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.10.1 The fmod functions (p: 185)
+ 7.25 Type-generic math <tgmath.h> (p: 274-275)
+ F.10.7.1 The fmod functions (p: 385)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.10.1 The fmod functions (p: 254)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.7.1 The fmod functions (p: 528)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.10.1 The fmod functions (p: 235)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.7.1 The fmod functions (p: 465)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.6.4 The fmod function
### See also
| | |
| --- | --- |
| [divldivlldiv](div "c/numeric/math/div")
(C99) | computes quotient and remainder of integer division (function) |
| [remainderremainderfremainderl](remainder "c/numeric/math/remainder")
(C99)(C99)(C99) | computes signed remainder of the floating-point division operation (function) |
| [remquoremquofremquol](remquo "c/numeric/math/remquo")
(C99)(C99)(C99) | computes signed remainder as well as the three last bits of the division operation (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/fmod "cpp/numeric/math/fmod") for `fmod` |
c fma, fmaf, fmal fma, fmaf, fmal
===============
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float fmaf( float x, float y, float z );
```
| (1) | (since C99) |
|
```
double fma( double x, double y, double z );
```
| (2) | (since C99) |
|
```
long double fmal( long double x, long double y, long double z );
```
| (3) | (since C99) |
|
```
#define FP_FAST_FMA /* implementation-defined */
```
| (4) | (since C99) |
|
```
#define FP_FAST_FMAF /* implementation-defined */
```
| (5) | (since C99) |
|
```
#define FP_FAST_FMAL /* implementation-defined */
```
| (6) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define fma( x, y, z )
```
| (7) | (since C99) |
1-3) Computes `(x*y) + z` as if to infinite precision and rounded only once to fit the result type.
4-6) If the macro constants `FP_FAST_FMA`, `FP_FAST_FMAF`, or `FP_FAST_FMAL` are defined, the corresponding function `fmaf`, `fma`, or `fmal` evaluates faster (in addition to being more precise) than the expression `x*y+z` for `float`, `double`, and `long double` arguments, respectively. If defined, these macros evaluate to integer `1`.
7) Type-generic macro: If any argument has type `long double`, `fmal` is called. Otherwise, if any argument has integer type or has type `double`, `fma` is called. Otherwise, `fmaf` is called. ### Parameters
| | | |
| --- | --- | --- |
| x, y, z | - | floating point values |
### Return value
If successful, returns the value of `(x*y) + z` as if calculated to infinite precision and rounded once to fit the result type (or, alternatively, calculated as a single ternary floating-point operation).
If a range error due to overflow occurs, `[±HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `±HUGE_VALF`, or `±HUGE_VALL` is returned.
If a range error due to underflow occurs, the correct value (after rounding) is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If x is zero and y is infinite or if x is infinite and y is zero, and z is not a NaN, then NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If x is zero and y is infinite or if x is infinite and y is zero, and z is a NaN, then NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be raised
* If `x*y` is an exact infinity and z is an infinity with the opposite sign, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* If x or y are NaN, NaN is returned
* If z is NaN, and `x*y` aren't 0\*Inf or Inf\*0, then NaN is returned (without `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")`).
### Notes
This operation is commonly implemented in hardware as [fused multiply-add](https://en.wikipedia.org/wiki/Multiply%E2%80%93accumulate_operation "enwiki:Multiply–accumulate operation") CPU instruction. If supported by hardware, the appropriate `FP_FAST_FMA*` macros are expected to be defined, but many implementations make use of the CPU instruction even when the macros are not defined.
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fma.html) that the situation where the value `x*y` is invalid and z is a NaN is a domain error.
Due to its infinite intermediate precision, `fma` is a common building block of other correctly-rounded mathematical operations, such as `[sqrt](sqrt "c/numeric/math/sqrt")` or even the division (where not provided by the CPU, e.g. Itanium).
As with all floating-point expressions, the expression `(x*y) + z` may be compiled as a fused mutiply-add unless the [`#pragma`](../../preprocessor/impl "c/preprocessor/impl") `STDC FP_CONTRACT` is off.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
// demo the difference between fma and built-in operators
double in = 0.1;
printf("0.1 double is %.23f (%a)\n", in, in);
printf("0.1*10 is 1.0000000000000000555112 (0x8.0000000000002p-3),"
" or 1.0 if rounded to double\n");
double expr_result = 0.1 * 10 - 1;
printf("0.1 * 10 - 1 = %g : 1 subtracted after "
"intermediate rounding to 1.0\n", expr_result);
double fma_result = fma(0.1, 10, -1);
printf("fma(0.1, 10, -1) = %g (%a)\n", fma_result, fma_result);
// fma use in double-double arithmetic
printf("\nin double-double arithmetic, 0.1 * 10 is representable as ");
double high = 0.1 * 10;
double low = fma(0.1, 10, -high);
printf("%g + %g\n\n", high, low);
//error handling
feclearexcept(FE_ALL_EXCEPT);
printf("fma(+Inf, 10, -Inf) = %f\n", fma(INFINITY, 10, -INFINITY));
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
}
```
Possible output:
```
0.1 double is 0.10000000000000000555112 (0x1.999999999999ap-4)
0.1*10 is 1.0000000000000000555112 (0x8.0000000000002p-3), or 1.0 if rounded to double
0.1 * 10 - 1 = 0 : 1 subtracted after intermediate rounding to 1.0
fma(0.1, 10, -1) = 5.55112e-17 (0x1p-54)
in double-double arithmetic, 0.1 * 10 is representable as 1 + 5.55112e-17
fma(+Inf, 10, -Inf) = -nan
FE_INVALID raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.13.1 The fma functions (p: 188-189)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.10.1 The fma functions (p: 386)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.13.1 The fma functions (p: 258)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.10.1 The fma functions (p: 530)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.13.1 The fma functions (p: 239)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.10.1 The fma functions (p: 466)
### See also
| | |
| --- | --- |
| [remainderremainderfremainderl](remainder "c/numeric/math/remainder")
(C99)(C99)(C99) | computes signed remainder of the floating-point division operation (function) |
| [remquoremquofremquol](remquo "c/numeric/math/remquo")
(C99)(C99)(C99) | computes signed remainder as well as the three last bits of the division operation (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/fma "cpp/numeric/math/fma") for `fma` |
| programming_docs |
c modf, modff, modfl modf, modff, modfl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float modff( float arg, float* iptr );
```
| (1) | (since C99) |
|
```
double modf( double arg, double* iptr );
```
| (2) | |
|
```
long double modfl( long double arg, long double* iptr );
```
| (3) | (since C99) |
1-3) Decomposes given floating point value `arg` into integral and fractional parts, each having the same type and sign as `arg`. The integral part (in floating-point format) is stored in the object pointed to by `iptr`. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
| iptr | - | pointer to floating point value to store the integral part to |
### Return value
If no errors occur, returns the fractional part of `x` with the same sign as `x`. The integral part is put into the value pointed to by `iptr`.
The sum of the returned value and the value stored in `*iptr` gives `arg` (allowing for rounding).
### Error handling
This function is not subject to any errors specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If `arg` is ±0, ±0 is returned, and ±0 is stored in `*iptr`.
* If `arg` is ±∞, ±0 is returned, and ±∞ is stored in `*iptr`.
* If `arg` is NaN, NaN is returned, and NaN is stored in `*iptr`.
* The returned value is exact, [the current rounding mode](../fenv/fe_round "c/numeric/fenv/FE round") is ignored
### Notes
This function behaves as if implemented as follows:
```
double modf(double value, double *iptr)
{
#pragma STDC FENV_ACCESS ON
int save_round = fegetround();
fesetround(FE_TOWARDZERO);
*iptr = std::nearbyint(value);
fesetround(save_round);
return copysign(isinf(value) ? 0.0 : value - (*iptr), value);
}
```
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
int main(void)
{
double f = 123.45;
printf("Given the number %.2f or %a in hex,\n", f, f);
double f3;
double f2 = modf(f, &f3);
printf("modf() makes %.2f + %.2f\n", f3, f2);
int i;
f2 = frexp(f, &i);
printf("frexp() makes %f * 2^%d\n", f2, i);
i = ilogb(f);
printf("logb()/ilogb() make %f * %d^%d\n", f/scalbn(1.0, i), FLT_RADIX, i);
// special values
f2 = modf(-0.0, &f3);
printf("modf(-0) makes %.2f + %.2f\n", f3, f2);
f2 = modf(-INFINITY, &f3);
printf("modf(-Inf) makes %.2f + %.2f\n", f3, f2);
}
```
Possible output:
```
Given the number 123.45 or 0x1.edccccccccccdp+6 in hex,
modf() makes 123.00 + 0.45
frexp() makes 0.964453 * 2^7
logb()/ilogb() make 1.92891 * 2^6
modf(-0) makes -0.00 + -0.00
modf(-Inf) makes -INF + -0.00
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.6.12 The modf functions (p: 246-247)
+ F.10.3.12 The modf functions (p: 523)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.6.12 The modf functions (p: 227)
+ F.9.3.12 The modf functions (p: 460)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.4.6 The modf function
### See also
| | |
| --- | --- |
| [trunctruncftruncl](trunc "c/numeric/math/trunc")
(C99)(C99)(C99) | rounds to nearest integer not greater in magnitude than the given value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/modf "cpp/numeric/math/modf") for `modf` |
c log10, log10f, log10l log10, log10f, log10l
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float log10f( float arg );
```
| (1) | (since C99) |
|
```
double log10( double arg );
```
| (2) | |
|
```
long double log10l( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define log10( arg )
```
| (4) | (since C99) |
1-3) Computes the common (base-*10*) logarithm of `arg`.
4) Type-generic macro: If `arg` has type `long double`, `log10l` is called. Otherwise, if `arg` has integer type or the type `double`, `log10` is called. Otherwise, `log10f` is called. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the common (base-*10*) logarithm of `arg` (log
10(arg) or lg(arg)) is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a pole error occurs, `[-HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `-HUGE_VALF`, or `-HUGE_VALL` is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
Domain error occurs if `arg` is less than zero.
Pole error may occur if `arg` is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ±0, -∞ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* If the argument is 1, +0 is returned
* If the argument is negative, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* If the argument is +∞, +∞ is returned
* If the argument is NaN, NaN is returned
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
printf("log10(1000) = %f\n", log10(1000));
printf("log10(0.001) = %f\n", log10(0.001));
printf("base-5 logarithm of 125 = %f\n", log10(125)/log10(5));
// special values
printf("log10(1) = %f\n", log10(1));
printf("log10(+Inf) = %f\n", log10(INFINITY));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("log10(0) = %f\n", log10(0));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_DIVBYZERO)) puts(" FE_DIVBYZERO raised");
}
```
Possible output:
```
log10(1000) = 3.000000
log10(0.001) = -3.000000
base-5 logarithm of 125 = 3.000000
log10(1) = 0.000000
log10(+Inf) = inf
log10(0) = -inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.6.8 The log10 functions (p: 179)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.3.8 The log10 functions (p: 380)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.6.8 The log10 functions (p: 245)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.8 The log10 functions (p: 522)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.6.8 The log10 functions (p: 225-226)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.3.8 The log10 functions (p: 459)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.4.5 The log10 function
### See also
| | |
| --- | --- |
| [loglogflogl](log "c/numeric/math/log")
(C99)(C99) | computes natural (base-*e*) logarithm (\({\small \ln{x} }\)ln(x)) (function) |
| [log2log2flog2l](log2 "c/numeric/math/log2")
(C99)(C99)(C99) | computes base-2 logarithm (\({\small \log\_{2}{x} }\)log2(x)) (function) |
| [log1plog1pflog1pl](log1p "c/numeric/math/log1p")
(C99)(C99)(C99) | computes natural (base-*e*) logarithm of 1 plus the given number (\({\small \ln{(1+x)} }\)ln(1+x)) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/log10 "cpp/numeric/math/log10") for `log10` |
c frexp, frexpf, frexpl frexp, frexpf, frexpl
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float frexpf( float arg, int* exp );
```
| (1) | (since C99) |
|
```
double frexp( double arg, int* exp );
```
| (2) | |
|
```
long double frexpl( long double arg, int* exp );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define frexp( arg, exp )
```
| (4) | (since C99) |
1-3) Decomposes given floating point value `x` into a normalized fraction and an integral power of two.
4) Type-generic macro: If `arg` has type `long double`, `frexpl` is called. Otherwise, if `arg` has integer type or the type `double`, `frexp` is called. Otherwise, `frexpf` is called, respectively. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
| exp | - | pointer to integer value to store the exponent to |
### Return value
If `arg` is zero, returns zero and stores zero in `*exp`.
Otherwise (if `arg` is not zero), if no errors occur, returns the value `x` in the range `(-1;-0.5], [0.5; 1)` and stores an integer value in `\*[exp](http://en.cppreference.com/w/c/numeric/math/exp)` such that x×2(\*exp)
=arg.
If the value to be stored in `*exp` is outside the range of `int`, the behavior is unspecified.
If `arg` is not a floating-point number, the behavior is unspecified.
### Error handling
This function is not subject to any errors specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If `arg` is ±0, it is returned, unmodified, and `0` is stored in `\*[exp](http://en.cppreference.com/w/c/numeric/math/exp)`.
* If `arg` is ±∞, it is returned, and an unspecified value is stored in `\*[exp](http://en.cppreference.com/w/c/numeric/math/exp)`.
* If `arg` is NaN, NaN is returned, and an unspecified value is stored in `\*[exp](http://en.cppreference.com/w/c/numeric/math/exp)`.
* No floating-point exceptions are raised.
* If `[FLT\_RADIX](../../types/limits "c/types/limits")` is 2 (or a power of 2), the returned value is exact, [the current rounding mode](../fenv/fe_round "c/numeric/fenv/FE round") is ignored
### Notes
On a binary system (where `[FLT\_RADIX](../../types/limits "c/types/limits")` is `2`), `frexp` may be implemented as.
```
{
*exp = (value == 0) ? 0 : (int)(1 + logb(value));
return scalbn(value, -(*exp));
}
```
The function `frexp`, together with its dual, `[ldexp](ldexp "c/numeric/math/ldexp")`, can be used to manipulate the representation of a floating-point number without direct bit manipulations.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
int main(void)
{
double f = 123.45;
printf("Given the number %.2f or %a in hex,\n", f, f);
double f3;
double f2 = modf(f, &f3);
printf("modf() makes %.0f + %.2f\n", f3, f2);
int i;
f2 = frexp(f, &i);
printf("frexp() makes %f * 2^%d\n", f2, i);
i = ilogb(f);
printf("logb()/ilogb() make %f * %d^%d\n", f/scalbn(1.0, i), FLT_RADIX, i);
}
```
Possible output:
```
Given the number 123.45 or 0x1.edccccccccccdp+6 in hex,
modf() makes 123 + 0.45
frexp() makes 0.964453 * 2^7
logb()/ilogb() make 1.92891 * 2^6
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.6.4 The frexp functions (p: 243)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.4 The frexp functions (p: 521)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.6.4 The frexp functions (p: 224)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.3.4 The frexp functions (p: 458)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.4.2 The frexp function
### See also
| | |
| --- | --- |
| [ldexpldexpfldexpl](ldexp "c/numeric/math/ldexp")
(C99)(C99) | multiplies a number by `2` raised to a power (function) |
| [logblogbflogbl](logb "c/numeric/math/logb")
(C99)(C99)(C99) | extracts exponent of the given number (function) |
| [ilogbilogbfilogbl](ilogb "c/numeric/math/ilogb")
(C99)(C99)(C99) | extracts exponent of the given number (function) |
| [modfmodffmodfl](modf "c/numeric/math/modf")
(C99)(C99) | breaks a number into integer and fractional parts (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/frexp "cpp/numeric/math/frexp") for `frexp` |
c nextafter, nextafterf, nextafterl, nexttoward, nexttowardf, nexttowardl nextafter, nextafterf, nextafterl, nexttoward, nexttowardf, nexttowardl
=======================================================================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float nextafterf( float from, float to );
```
| (1) | (since C99) |
|
```
double nextafter( double from, double to );
```
| (2) | (since C99) |
|
```
long double nextafterl( long double from, long double to );
```
| (3) | (since C99) |
|
```
float nexttowardf( float from, long double to );
```
| (4) | (since C99) |
|
```
double nexttoward( double from, long double to );
```
| (5) | (since C99) |
|
```
long double nexttowardl( long double from, long double to );
```
| (6) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define nextafter(from, to)
```
| (7) | (since C99) |
|
```
#define nexttoward(from, to)
```
| (8) | (since C99) |
1-3) First, converts both arguments to the type of the function, then returns the next representable value of `from` in the direction of `to`. If `from` equals to `to`, `to` is returned.
4-6) First, converts the first argument to the type of the function, then returns the next representable value of `from` in the direction of `to`. If `from` equals to `to`, `to` is returned, converted from `long double` to the return type of the function without loss of range or precision.
7) Type-generic macro: If any argument has type `long double`, `nextafterl` is called. Otherwise, if any argument has integer type or has type `double`, `nextafter` is called. Otherwise, `nextafterf` is called.
8) Type-generic macro: If the argument `from` has type `long double`, `nexttowardl` is called. Otherwise, if `from` has integer type or the type `double`, `nexttoward` is called. Otherwise, `nexttowardf` is called. ### Parameters
| | | |
| --- | --- | --- |
| from, to | - | floating point values |
### Return value
If no errors occur, the next representable value of `from` in the direction of `to`. is returned. If `from` equals `to`, then `to` is returned, converted to the type of the function.
If a range error due to overflow occurs, `[±HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `±HUGE_VALF`, or `±HUGE_VALL` is returned (with the same sign as `from`).
If a range error occurs due to underflow, the correct result is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if `from` is finite, but the expected result is an infinity, raises `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` and `[FE\_OVERFLOW](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")`
* if `from` does not equal `to` and the result is subnormal or zero, raises `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` and `[FE\_UNDERFLOW](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")`
* in any case, the returned value is independent of the current rounding mode
* if either `from` or `to` is NaN, NaN is returned
### Notes
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/nextafter.html) that the overflow and the underflow conditions are range errors (`[errno](../../error/errno "c/error/errno")` may be set).
IEC 60559 recommends that `from` is returned whenever `from == to`. These functions return `to` instead, which makes the behavior around zero consistent: `nextafter(-0.0, +0.0)` returns `+0.0` and `nextafter(+0.0, -0.0)` returns `-0.0`.
`nextafter` is typically implemented by manipulation of IEEE representation ([glibc](https://github.com/bminor/glibc/blob/master/math/s_nextafter.c) [musl](https://github.com/ifduyue/musl/blob/master/src/math/nextafter.c)).
### Example
```
#include <math.h>
#include <stdio.h>
#include <float.h>
#include <fenv.h>
int main(void)
{
float from1 = 0, to1 = nextafterf(from1, 1);
printf("The next representable float after %.2f is %.20g (%a)\n", from1, to1, to1);
float from2 = 1, to2 = nextafterf(from2, 2);
printf("The next representable float after %.2f is %.20f (%a)\n", from2, to2, to2);
double from3 = nextafter(0.1, 0), to3 = 0.1;
printf("The number 0.1 lies between two valid doubles:\n"
" %.56f (%a)\nand %.55f (%a)\n", from3, from3, to3, to3);
// difference between nextafter and nexttoward:
long double dir = nextafterl(from1, 1); // first subnormal long double
float x = nextafterf(from1, dir); // first converts dir to float, giving 0
printf("Using nextafter, next float after %.2f (%a) is %.20g (%a)\n",
from1, from1, x, x);
x = nexttowardf(from1, dir);
printf("Using nexttoward, next float after %.2f (%a) is %.20g (%a)\n",
from1, from1, x, x);
// special values
{
#pragma STDC FENV_ACCESS ON
feclearexcept(FE_ALL_EXCEPT);
double from4 = DBL_MAX, to4 = nextafter(from4, INFINITY);
printf("The next representable double after %.2g (%a) is %.23f (%a)\n",
from4, from4, to4, to4);
if(fetestexcept(FE_OVERFLOW)) puts(" raised FE_OVERFLOW");
if(fetestexcept(FE_INEXACT)) puts(" raised FE_INEXACT");
} // end FENV_ACCESS block
float from5 = 0.0, to5 = nextafter(from5, -0.0);
printf("nextafter(+0.0, -0.0) gives %.2g (%a)\n", to5, to5);
}
```
Output:
```
The next representable float after 0.00 is 1.4012984643248170709e-45 (0x1p-149)
The next representable float after 1.00 is 1.00000011920928955078 (0x1.000002p+0)
The number 0.1 lies between two valid doubles:
0.09999999999999999167332731531132594682276248931884765625 (0x1.9999999999999p-4)
and 0.1000000000000000055511151231257827021181583404541015625 (0x1.999999999999ap-4)
Using nextafter, next float after 0.00 (0x0p+0) is 0 (0x0p+0)
Using nexttoward, next float after 0.00 (0x0p+0) is 1.4012984643248170709e-45 (0x1p-149)
The next representable double after 1.8e+308 (0x1.fffffffffffffp+1023) is inf (inf)
raised FE_OVERFLOW
raised FE_INEXACT
nextafter(+0.0, -0.0) gives -0 (-0x0p+0)
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.11.3 The nextafter functions (p: 187)
+ 7.12.11.4 The nexttoward functions (p: 187)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.8.3 The nextafter functions (p: 386)
+ F.10.8.4 The nexttoward functions (p: 386)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.11.3 The nextafter functions (p: 256)
+ 7.12.11.4 The nexttoward functions (p: 257)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.8.3 The nextafter functions (p: 529)
+ F.10.8.4 The nexttoward functions (p: 529)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.11.3 The nextafter functions (p: 237)
+ 7.12.11.4 The nexttoward functions (p: 238)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.8.3 The nextafter functions (p: 466)
+ F.9.8.4 The nexttoward functions (p: 466)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/nextafter "cpp/numeric/math/nextafter") for `nextafter` |
c copysign, copysignf, copysignl copysign, copysignf, copysignl
==============================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float copysignf( float x, float y );
```
| (1) | (since C99) |
|
```
double copysign( double x, double y );
```
| (2) | (since C99) |
|
```
long double copysignl( long double x, long double y );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define copysign(x, y)
```
| (4) | (since C99) |
1-3) Composes a floating point value with the magnitude of `x` and the sign of `y`.
4) Type-generic macro: If any argument has type `long double`, `copysignl` is called. Otherwise, if any argument has integer type or has type `double`, `copysign` is called. Otherwise, `copysignf` is called. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | floating point values |
### Return value
If no errors occur, the floating point value with the magnitude of `x` and the sign of `y` is returned.
If `x` is NaN, then NaN with the sign of `y` is returned.
If `y` is -0, the result is only negative if the implementation supports the signed zero consistently in arithmetic operations.
### Error handling
This function is not subject to any errors specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* The returned value is exact (`[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is never raised) and independent of the current [rounding mode](../fenv/fe_round "c/numeric/fenv/FE round").
### Notes
`copysign` is the only portable way to manipulate the sign of a NaN value (to examine the sign of a NaN, `[signbit](signbit "c/numeric/math/signbit")` may also be used).
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("copysign(1.0,+2.0) = %+.1f\n", copysign(1.0,+2.0));
printf("copysign(1.0,-2.0) = %+.1f\n", copysign(1.0,-2.0));
printf("copysign(INFINITY,-2.0) = %f\n", copysign(INFINITY,-2.0));
printf("copysign(NAN,-2.0) = %f\n", copysign(NAN,-2.0));
}
```
Possible output:
```
copysign(1.0,+2.0) = +1.0
copysign(1.0,-2.0) = -1.0
copysign(INFINITY,-2.0) = -inf
copysign(NAN,-2.0) = -nan
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.11.1 The copysign functions (p: 255)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.8.1 The copysign functions (p: 529)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.11.1 The copysign functions (p: 236)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.8.1 The copysign functions (p: 465)
### See also
| | |
| --- | --- |
| [fabsfabsffabsl](fabs "c/numeric/math/fabs")
(C99)(C99) | computes absolute value of a floating-point value (\(\small{|x|}\)|x|) (function) |
| [signbit](signbit "c/numeric/math/signbit")
(C99) | checks if the given number is negative (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/copysign "cpp/numeric/math/copysign") for `copysign` |
| programming_docs |
c nan, nanf, nanl, nand32, nand64, nand128 nan, nanf, nanl, nand32, nand64, nand128
========================================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float nanf( const char* arg );
```
| (1) | (since C99) |
|
```
double nan( const char* arg );
```
| (2) | (since C99) |
|
```
long double nanl( const char* arg );
```
| (3) | (since C99) |
|
```
_Decimal32 nand32( const char* arg );
```
| (4) | (since C23) |
|
```
_Decimal64 nand64( const char* arg );
```
| (5) | (since C23) |
|
```
_Decimal128 nand128( const char* arg );
```
| (6) | (since C23) |
Converts the implementation-defined character string `arg` into the corresponding quiet NaN value, as if by calling the appropriate parsing function `*strtoX*`, as follows:
* The call `nan("n-char-sequence")`, where n-char-sequence is a sequence of digits, Latin letters, and underscores, is equivalent to the call `/\*strtoX\*/("NAN(n-char-sequence)", (char\*\*)[NULL](http://en.cppreference.com/w/c/types/NULL));`.
* The call `nan("")` is equivalent to the call `/\*strtoX\*/("NAN()", (char\*\*)[NULL](http://en.cppreference.com/w/c/types/NULL));`.
* The call `nan("string")`, where `string` is neither an n-char-sequence nor an empty string, is equivalent to the call `/\*strtoX\*/("NAN", (char\*\*)[NULL](http://en.cppreference.com/w/c/types/NULL));`.
1) The parsing function is `[strtof](../../string/byte/strtof "c/string/byte/strtof")`.
2) The parsing function is `[strtod](../../string/byte/strtof "c/string/byte/strtof")`.
3) The parsing function is `[strtold](../../string/byte/strtof "c/string/byte/strtof")`.
4) The parsing function is `strtod32`.
5) The parsing function is `strtod64`.
6) The parsing function is `strtod128`.
| | |
| --- | --- |
| The functions returning decimal floating point values are declared if and only the implementation predefines `__STDC_IEC_60559_DFP__` (i.e. the implementation supports decimal floating point numbers). | (since C23) |
### Parameters
| | | |
| --- | --- | --- |
| arg | - | narrow character string identifying the contents of a NaN |
### Return value
The quiet NaN value that corresponds to the identifying string `arg` or zero if the implementation does not support quiet NaNs.
If the implementation supports IEEE floating-point arithmetic (IEC 60559), it also supports quiet NaNs.
### Error handling
This function is not subject to any of the error conditions specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
### Example
```
#include <stdio.h>
#include <math.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
int main(void)
{
double f1 = nan("1");
uint64_t f1n; memcpy(&f1n, &f1, sizeof f1);
printf("nan(\"1\") = %f (%" PRIx64 ")\n", f1, f1n);
double f2 = nan("2");
uint64_t f2n; memcpy(&f2n, &f2, sizeof f2);
printf("nan(\"2\") = %f (%" PRIx64 ")\n", f2, f2n);
double f3 = nan("0xF");
uint64_t f3n; memcpy(&f3n, &f3, sizeof f3);
printf("nan(\"0xF\") = %f (%" PRIx64 ")\n", f3, f3n);
}
```
Possible output:
```
nan("1") = nan (7ff8000000000001)
nan("2") = nan (7ff8000000000002)
nan("0xF") = nan (7ff800000000000f)
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.11.2 The nan functions (p: 186-187)
+ F.10.8.2 The nan functions (p: 386)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.11.2 The nan functions (p: 256)
+ F.10.8.2 The nan functions (p: 529)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.11.2 The nan functions (p: 237)
+ F.9.8.2 The fabs functions (p: 465)
### See also
| | |
| --- | --- |
| [isnan](isnan "c/numeric/math/isnan")
(C99) | checks if the given number is NaN (function macro) |
| [NAN](nan "c/numeric/math/NAN")
(C99) | evaluates to a quiet NaN of type `float` (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/nan "cpp/numeric/math/nan") for `nanf, nan, nanl` |
c islessequal islessequal
===========
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define islessequal(x, y) /* implementation defined */
```
| | (since C99) |
Determines if the floating point number `x` is less than or equal to the floating-point number `y`, without setting floating-point exceptions.
### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
Nonzero integral value if `x <= y`, `0` otherwise.
### Notes
The built-in `operator<=` for floating-point numbers may raise `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` if one or both of the arguments is NaN. This function is a "quiet" version of `operator<=`.
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("islessequal(2.0,1.0) = %d\n", islessequal(2.0,1.0));
printf("islessequal(1.0,2.0) = %d\n", islessequal(1.0,2.0));
printf("islessequal(1.0,1.0) = %d\n", islessequal(1.0,1.0));
printf("islessequal(INFINITY,1.0) = %d\n", islessequal(INFINITY,1.0));
printf("islessequal(1.0,NAN) = %d\n", islessequal(1.0,NAN));
return 0;
}
```
Possible output:
```
islessequal(2.0,1.0) = 0
islessequal(1.0,2.0) = 1
islessequal(1.0,1.0) = 1
islessequal(INFINITY,1.0) = 0
islessequal(1.0,NAN) = 0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.14.4 The islessequal macro (p: 260)
+ F.10.11 Comparison macros (p: 531)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.14.4 The islessequal macro (p: 241)
### See also
| | |
| --- | --- |
| [isgreaterequal](isgreaterequal "c/numeric/math/isgreaterequal")
(C99) | checks if the first floating-point argument is greater or equal than the second (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/islessequal "cpp/numeric/math/islessequal") for `islessequal` |
c islessgreater islessgreater
=============
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define islessgreater(x, y) /* implementation defined */
```
| | (since C99) |
Determines if the floating point number `x` is less than or greater than the floating-point number `y`, without setting floating-point exceptions.
### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
Nonzero integral value if `x < y || x > y`, `0` otherwise.
### Notes
The built-in `operator<` and `operator>` for floating-point numbers may raise `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` if one or both of the arguments is NaN. This function is a "quiet" version of the expression `x < y || x > y`. The macro does not evaluate x and y twice.
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("islessgreater(2.0,1.0) = %d\n", islessgreater(2.0,1.0));
printf("islessgreater(1.0,2.0) = %d\n", islessgreater(1.0,2.0));
printf("islessgreater(1.0,1.0) = %d\n", islessgreater(1.0,1.0));
printf("islessgreater(INFINITY,1.0) = %d\n", islessgreater(INFINITY,1.0));
printf("islessgreater(1.0,NAN) = %d\n", islessgreater(1.0,NAN));
return 0;
}
```
Possible output:
```
islessgreater(2.0,1.0) = 1
islessgreater(1.0,2.0) = 1
islessgreater(1.0,1.0) = 0
islessgreater(INFINITY,1.0) = 1
islessgreater(1.0,NAN) = 0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.14.5 The islessgreater macro (p: 261)
+ F.10.11 Comparison macros (p: 531)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.14.5 The islessgreater macro (p: 241-242)
### See also
| | |
| --- | --- |
| [isless](isless "c/numeric/math/isless")
(C99) | checks if the first floating-point argument is less than the second (function macro) |
| [isgreater](isgreater "c/numeric/math/isgreater")
(C99) | checks if the first floating-point argument is greater than the second (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/islessgreater "cpp/numeric/math/islessgreater") for `islessgreater` |
c atan2, atan2f, atan2l atan2, atan2f, atan2l
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float atan2f( float y, float x );
```
| (1) | (since C99) |
|
```
double atan2( double y, double x );
```
| (2) | |
|
```
long double atan2l( long double y, long double x );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define atan2( y, x )
```
| (4) | (since C99) |
1-3) Computes the arc tangent of `y/x` using the signs of arguments to determine the correct quadrant.
4) Type-generic macro: If any argument has type `long double`, `atan2l` is called. Otherwise, if any argument has integer type or has type `double`, `atan2` is called. Otherwise, `atan2f` is called. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | floating point value |
### Return value
If no errors occur, the arc tangent of `y/x` (arctan(y/x)) in the range [-π ; +π] radians, is returned. Y argument Return value [![math-atan2.png]()](https://en.cppreference.com/w/File:math-atan2.png) X argument If a domain error occurs, an implementation-defined value is returned.
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in `math_errhandling`.
Domain error may occur if `x` and `y` are both zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If `x` and `y` are both zero, domain error *does not* occur
* If `x` and `y` are both zero, range error does not occur either
* If `y` is zero, pole error does not occur
* If `y` is `±0` and `x` is negative or `-0`, `±π` is returned
* If `y` is `±0` and `x` is positive or `+0`, `±0` is returned
* If `y` is `±∞` and `x` is finite, `±π/2` is returned
* If `y` is `±∞` and `x` is `-∞`, `±3π/4` is returned
* If `y` is `±∞` and `x` is `+∞`, `±π/4` is returned
* If `x` is `±0` and `y` is negative, `-π/2` is returned
* If `x` is `±0` and `y` is positive, `+π/2` is returned
* If `x` is `-∞` and `y` is finite and positive, `+π` is returned
* If `x` is `-∞` and `y` is finite and negative, `-π` is returned
* If `x` is `+∞` and `y` is finite and positive, `+0` is returned
* If `x` is `+∞` and `y` is finite and negative, `-0` is returned
* If either `x` is NaN or `y` is NaN, NaN is returned
### Notes
`atan2(y, x)` is equivalent to `[carg](http://en.cppreference.com/w/c/numeric/complex/carg)(x + I\*y)`.
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/atan2.html) that in case of underflow, `y/x` is the value returned, and if that is not supported, an implementation-defined value no greater than `DBL_MIN`, `FLT_MIN`, and `LDBL_MIN` is returned.
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
// normal usage: the signs of the two arguments determine the quadrant
// atan2(1,1) = +pi/4, Quad I
printf("(+1,+1) cartesian is (%f,%f) polar\n", hypot( 1, 1), atan2( 1, 1));
// atan2(1, -1) = +3pi/4, Quad II
printf("(+1,-1) cartesian is (%f,%f) polar\n", hypot( 1,-1), atan2( 1,-1));
// atan2(-1,-1) = -3pi/4, Quad III
printf("(-1,-1) cartesian is (%f,%f) polar\n", hypot(-1,-1), atan2(-1,-1));
// atan2(-1,-1) = -pi/4, Quad IV
printf("(-1,+1) cartesian is (%f,%f) polar\n", hypot(-1, 1), atan2(-1, 1));
// special values
printf("atan2(0, 0) = %f atan2(0, -0)=%f\n", atan2(0,0), atan2(0,-0.0));
printf("atan2(7, 0) = %f atan2(7, -0)=%f\n", atan2(7,0), atan2(7,-0.0));
}
```
Output:
```
(+1,+1) cartesian is (1.414214,0.785398) polar
(+1,-1) cartesian is (1.414214,2.356194) polar
(-1,-1) cartesian is (1.414214,-2.356194) polar
(-1,+1) cartesian is (1.414214,-0.785398) polar
atan2(0, 0) = 0.000000 atan2(0, -0)=3.141593
atan2(7, 0) = 1.570796 atan2(7, -0)=1.570796
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.4.4 The atan2 functions (p: 174)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.1.4 The atan2 functions (p: 378)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.4.4 The atan2 functions (p: 239)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.1.4 The atan2 functions (p: 519)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.4.4 The atan2 functions (p: 219)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.1.4 The atan2 functions (p: 456)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.2.4 The atan2 function
### See also
| | |
| --- | --- |
| [asinasinfasinl](asin "c/numeric/math/asin")
(C99)(C99) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) |
| [acosacosfacosl](acos "c/numeric/math/acos")
(C99)(C99) | computes arc cosine (\({\small\arccos{x} }\)arccos(x)) (function) |
| [atanatanfatanl](atan "c/numeric/math/atan")
(C99)(C99) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [cargcargfcargl](../complex/carg "c/numeric/complex/carg")
(C99)(C99)(C99) | computes the phase angle of a complex number (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/atan2 "cpp/numeric/math/atan2") for `atan2` |
c fabs, fabsf, fabsl, fabsd32, fabsd64, fabsd128 fabs, fabsf, fabsl, fabsd32, fabsd64, fabsd128
==============================================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float fabsf( float arg );
```
| (1) | (since C99) |
|
```
double fabs( double arg );
```
| (2) | |
|
```
long double fabsl( long double arg );
```
| (3) | (since C99) |
|
```
_Decimal32 fabsd32( _Decimal32 arg );
```
| (4) | (since C23) |
|
```
_Decimal64 fabsd64( _Decimal64 arg );
```
| (5) | (since C23) |
|
```
_Decimal128 fabsd128( _Decimal128 arg );
```
| (6) | (since C23) |
| Defined in header `<tgmath.h>` | | |
|
```
#define fabs( arith )
```
| (7) | (since C99) |
1-6) Computes the absolute value of a floating point value `arg`.
| | |
| --- | --- |
| The functions with decimal floating point parameters are declared if and only the implementation predefines `__STDC_IEC_60559_DFP__` (i.e. the implementation supports decimal floating point numbers). | (since C23) |
7) Type-generic macro: If the argument has type `_Decimal128`, `_Decimal64`, `_Decimal32`, (since C23)`long double`, `double`, or `float`, `fabsd128`, `fabsd64`, `fabsd32`, (since C23)`fabsl`, `fabs`, or `fabsf` is called, respectively. Otherwise, if the argument has integer type, `fabs` is called. Otherwise, if the argument is complex, then the macro invokes the corresponding complex function (`[cabsf](../complex/cabs "c/numeric/complex/cabs")`, `[cabs](../complex/cabs "c/numeric/complex/cabs")`, `[cabsl](../complex/cabs "c/numeric/complex/cabs")`). Otherwise, the behavior is undefined. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
| arith | - | floating point or integer value |
### Return value
If successful, returns the absolute value of `arg` (\(\small |arg| \)|arg|). The value returned is exact and does not depend on any rounding modes.
### Error handling
This function is not subject to any of the error conditions specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is ±0, +0 is returned
* If the argument is ±∞, +∞ is returned
* If the argument is NaN, NaN is returned
### Example
```
#include <stdio.h>
#include <math.h>
#define PI 3.14159
/* This numerical integration assumes all area is positive. */
double integrate(double a, double b, /* assume a < b */
double f(double),
unsigned steps) { /* assume steps > 0 */
const double dx = (b-a)/steps;
double sum = 0.0;
for (double x = a; x < b; x += dx)
sum += fabs(f(x));
return dx*sum;
}
int main(void)
{
printf("fabs(+3) = %f\n", fabs(+3.0));
printf("fabs(-3) = %f\n", fabs(-3.0));
// special values
printf("fabs(-0) = %f\n", fabs(-0.0));
printf("fabs(-Inf) = %f\n", fabs(-INFINITY));
printf("%f\n", integrate(-PI,+PI,sin,10*1000));
}
```
Output:
```
fabs(+3) = 3.000000
fabs(-3) = 3.000000
fabs(-0) = 0.000000
fabs(-Inf) = inf
4.000000
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.7.2 The fabs functions (p: 181)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.4.2 The fabs functions (p: 382)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.7.2 The fabs functions (p: 248)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.4.2 The fabs functions (p: 524)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.7.2 The fabs functions (p: 228-229)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.4.2 The fabs functions (p: 460)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.6.2 The fabs function
### See also
| | |
| --- | --- |
| [abslabsllabs](abs "c/numeric/math/abs")
(C99) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) |
| [copysigncopysignfcopysignl](copysign "c/numeric/math/copysign")
(C99)(C99)(C99) | produces a value with the magnitude of a given value and the sign of another given value (function) |
| [signbit](signbit "c/numeric/math/signbit")
(C99) | checks if the given number is negative (function macro) |
| [cabscabsfcabsl](../complex/cabs "c/numeric/complex/cabs")
(C99)(C99)(C99) | computes the magnitude of a complex number (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/fabs "cpp/numeric/math/fabs") for `fabs` |
c acos, acosf, acosl acos, acosf, acosl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float acosf( float arg );
```
| (1) | (since C99) |
|
```
double acos( double arg );
```
| (2) | |
|
```
long double acosl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define acos( arg )
```
| (4) | (since C99) |
1-3) Computes the principal value of the arc cosine of `arg`.
4) Type-generic macro: If the argument has type `long double`, `acosl` is called. Otherwise, if the argument has integer type or the type `double`, `acos` is called. Otherwise, `acosf` is called. If the argument is complex, then the macro invokes the corresponding complex function (`[cacosf](http://en.cppreference.com/w/c/numeric/complex/cacos)`, `[cacos](http://en.cppreference.com/w/c/numeric/complex/cacos)`, `[cacosl](http://en.cppreference.com/w/c/numeric/complex/cacos)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the arc cosine of `arg` (arccos(arg)) in the range [0 ; π], is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
Domain error occurs if `arg` is outside the range `[-1.0; 1.0]`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is +1, the value `+0` is returned.
* If |arg| > 1, a domain error occurs and NaN is returned.
* if the argument is NaN, NaN is returned
### Example
```
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
#include <string.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
printf("acos(-1) = %f\n", acos(-1));
printf("acos(0.0) = %f 2*acos(0.0) = %f\n", acos(0), 2*acos(0));
printf("acos(0.5) = %f 3*acos(0.5) = %f\n", acos(0.5), 3*acos(0.5));
printf("acos(1) = %f\n", acos(1));
// error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("acos(1.1) = %f\n", acos(1.1));
if(errno == EDOM) perror(" errno == EDOM");
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
}
```
Possible output:
```
acos(-1) = 3.141593
acos(0.0) = 1.570796 2*acos(0.0) = 3.141593
acos(0.5) = 1.047198 3*acos(0.5) = 3.141593
acos(1) = 0.000000
acos(1.1) = nan
errno == EDOM: Numerical argument out of domain
FE_INVALID raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.4.1 The acos functions (p: 238)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.1.1 The acos functions (p: 518)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.4.1 The acos functions (p: 218)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.1.1 The acos functions (p: 455)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.2.1 The acos function
### See also
| | |
| --- | --- |
| [asinasinfasinl](asin "c/numeric/math/asin")
(C99)(C99) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) |
| [atanatanfatanl](atan "c/numeric/math/atan")
(C99)(C99) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [atan2atan2fatan2l](atan2 "c/numeric/math/atan2")
(C99)(C99) | computes arc tangent, using signs to determine quadrants (function) |
| [coscosfcosl](cos "c/numeric/math/cos")
(C99)(C99) | computes cosine (\({\small\cos{x} }\)cos(x)) (function) |
| [cacoscacosfcacosl](../complex/cacos "c/numeric/complex/cacos")
(C99)(C99)(C99) | computes the complex arc cosine (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/acos "cpp/numeric/math/acos") for `acos` |
| programming_docs |
c floor, floorf, floorl floor, floorf, floorl
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float floorf( float arg );
```
| (1) | (since C99) |
|
```
double floor( double arg );
```
| (2) | |
|
```
long double floorl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define floor( arg )
```
| (4) | (since C99) |
1-3) Computes the largest integer value not greater than `arg`.
4) Type-generic macro: If `arg` has type `long double`, `floorl` is called. Otherwise, if `arg` has integer type or the type `double`, `floor` is called. Otherwise, `floorf` is called. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the largest integer value not greater than `arg`, that is ⌊arg⌋, is returned.
Return value ![math-floor.svg]() Argument ### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* The current [rounding mode](../fenv/fe_round "c/numeric/fenv/FE round") has no effect.
* If `arg` is ±∞, it is returned, unmodified
* If `arg` is ±0, it is returned, unmodified
* If arg is NaN, NaN is returned
### Notes
`[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` may be (but isn't required to be) raised when rounding a non-integer finite value.
The largest representable floating-point values are exact integers in all standard floating-point formats, so this function never overflows on its own; however the result may overflow any integer type (including `[intmax\_t](../../types/integer "c/types/integer")`), when stored in an integer variable.
### Example
```
#include <math.h>
#include <stdio.h>
int main(void)
{
printf("floor(+2.7) = %+.1f\n", floor(2.7));
printf("floor(-2.7) = %+.1f\n", floor(-2.7));
printf("floor(-0.0) = %+.1f\n", floor(-0.0));
printf("floor(-Inf) = %+f\n", floor(-INFINITY));
}
```
Possible output:
```
floor(+2.7) = +2.0
floor(-2.7) = -3.0
floor(-0.0) = -0.0
floor(-Inf) = -inf
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.9.2 The floor functions (p: 251)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.6.2 The floor functions (p: 526)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.9.2 The floor functions (p: 232)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.6.2 The floor functions (p: 463)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.6.3 The floor function
### See also
| | |
| --- | --- |
| [ceilceilfceill](ceil "c/numeric/math/ceil")
(C99)(C99) | computes smallest integer not less than the given value (function) |
| [trunctruncftruncl](trunc "c/numeric/math/trunc")
(C99)(C99)(C99) | rounds to nearest integer not greater in magnitude than the given value (function) |
| [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](round "c/numeric/math/round")
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) | rounds to nearest integer, rounding away from zero in halfway cases (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/floor "cpp/numeric/math/floor") for `floor` |
c erfc, erfcf, erfcl erfc, erfcf, erfcl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float erfcf( float arg );
```
| (1) | (since C99) |
|
```
double erfc( double arg );
```
| (2) | (since C99) |
|
```
long double erfcl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define erfc( arg )
```
| (4) | (since C99) |
1-3) Computes the [complementary error function](https://en.wikipedia.org/wiki/Complementary_error_function "enwiki:Complementary error function") of `arg`, that is `1.0-erf(arg)`, but without loss of precision for large `arg`.
4) Type-generic macro: If `arg` has type `long double`, `erfcl` is called. Otherwise, if `arg` has integer type or the type `double`, `erfc` is called. Otherwise, `erfcf` is called. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, value of the complementary error function of `arg`, that is \(\frac{2}{\sqrt{\pi} }\int\_{arg}^{\infty}{e^{-{t^2} }\mathsf{d}t}\)2/√π∫∞
arg*e*-t2d*t* or \({\small 1-\operatorname{erf}(arg)}\)1-erf(arg), is returned. If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If the argument is +∞, +0 is returned
* If the argument is -∞, 2 is returned
* If the argument is NaN, NaN is returned
### Notes
For the IEEE-compatible type `double`, underflow is guaranteed if `arg` > 26.55.
### Example
```
#include <stdio.h>
#include <math.h>
double normalCDF(double x) // Phi(-∞, x) aka N(x)
{
return erfc(-x/sqrt(2))/2;
}
int main(void)
{
puts("normal cumulative distribution function:");
for(double n=0; n<1; n+=0.1)
printf("normalCDF(%.2f) %5.2f%%\n", n, 100*normalCDF(n));
puts("special values:");
printf("erfc(-Inf) = %f\n", erfc(-INFINITY));
printf("erfc(Inf) = %f\n", erfc(INFINITY));
}
```
Output:
```
normal cumulative distribution function:
normalCDF(0.00) 50.00%
normalCDF(0.10) 53.98%
normalCDF(0.20) 57.93%
normalCDF(0.30) 61.79%
normalCDF(0.40) 65.54%
normalCDF(0.50) 69.15%
normalCDF(0.60) 72.57%
normalCDF(0.70) 75.80%
normalCDF(0.80) 78.81%
normalCDF(0.90) 81.59%
normalCDF(1.00) 84.13%
special values:
erfc(-Inf) = 2.000000
erfc(Inf) = 0.000000
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.8.2 The erfc functions (p: 249-250)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.5.2 The erfc functions (p: 525)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.8.2 The erfc functions (p: 230)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.5.2 The erfc functions (p: 462)
### See also
| | |
| --- | --- |
| [erferfferfl](erf "c/numeric/math/erf")
(C99)(C99)(C99) | computes error function (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/erfc "cpp/numeric/math/erfc") for `erfc` |
### External links
[Weisstein, Eric W. "Erfc."](http://mathworld.wolfram.com/Erfc.html) From MathWorld--A Wolfram Web Resource.
c fmin, fminf, fminl fmin, fminf, fminl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float fminf( float x, float y );
```
| (1) | (since C99) |
|
```
double fmin( double x, double y );
```
| (2) | (since C99) |
|
```
long double fminl( long double x, long double y );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define fmin( x, y )
```
| (4) | (since C99) |
1-3) Returns the smaller of two floating point arguments, treating NaNs as missing data (between a NaN and a numeric value, the numeric value is chosen).
4) Type-generic macro: If any argument has type `long double`, `fminl` is called. Otherwise, if any argument has integer type or has type `double`, `fmin` is called. Otherwise, `fminf` is called. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | floating point values |
### Return value
If successful, returns the smaller of two floating point values. The value returned is exact and does not depend on any rounding modes.
### Error handling
This function is not subject to any of the error conditions specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If one of the two arguments is NaN, the value of the other argument is returned
* Only if both arguments are NaN, NaN is returned
### Notes
This function is not required to be sensitive to the sign of zero, although some implementations additionally enforce that if one argument is +0 and the other is -0, then -0 is returned.
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("fmin(2,1) = %f\n", fmin(2,1));
printf("fmin(-Inf,0) = %f\n", fmin(-INFINITY,0));
printf("fmin(NaN,-1) = %f\n", fmin(NAN,-1));
}
```
Possible output:
```
fmin(2,1) = 1.000000
fmin(-Inf,0) = -inf
fmin(NaN,-1) = -1.000000
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.12.3 The fmin functions (p: 258)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.9.3 The fmin functions (p: 530)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.12.3 The fmin functions (p: 239)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.9.3 The fmin functions (p: 466)
### See also
| | |
| --- | --- |
| [isless](isless "c/numeric/math/isless")
(C99) | checks if the first floating-point argument is less than the second (function macro) |
| [fmaxfmaxffmaxl](fmax "c/numeric/math/fmax")
(C99)(C99)(C99) | determines larger of two floating-point values (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/fmin "cpp/numeric/math/fmin") for `fmin` |
c fdim, fdimf, fdiml fdim, fdimf, fdiml
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float fdimf( float x, float y );
```
| (1) | (since C99) |
|
```
double fdim( double x, double y );
```
| (2) | (since C99) |
|
```
long double fdiml( long double x, long double y );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define fdim( x, y )
```
| (4) | (since C99) |
1-3) Returns the positive difference between `x` and `y`, that is, if `x>y`, returns `x-y`, otherwise (if `x≤y`), returns +0.
4) Type-generic macro: If any argument has type `long double`, `fdiml` is called. Otherwise, if any argument has integer type or has type `double`, `fdim` is called. Otherwise, `fdimf` is called. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | floating point value |
### Return value
If successful, returns the positive difference between x and y.
If a range error due to overflow occurs, `[+HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `+HUGE_VALF`, or `+HUGE_VALL` is returned.
If a range error due to underflow occurs, the correct value (after rounding) is returned.
### Error handling
Errors are reported as specified in `math_errhandling`.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If either argument is NaN, NaN is returned
### Notes
Equivalent to `[fmax](http://en.cppreference.com/w/c/numeric/math/fmax)(x-y, 0)` except for the NaN handling requirements.
### Example
```
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
// #pragma STDC FENV_ACCESS ON
int main(void)
{
printf("fdim(4, 1) = %f, fdim(1, 4)=%f\n", fdim(4,1), fdim(1,4));
printf("fdim(4,-1) = %f, fdim(1,-4)=%f\n", fdim(4,-1), fdim(1,-4));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("fdim(1e308, -1e308) = %f\n", fdim(1e308, -1e308));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_OVERFLOW)) puts(" FE_OVERFLOW raised");
}
```
Possible output:
```
fdim(4, 1) = 3.000000, fdim(1, 4)=0.000000
fdim(4,-1) = 5.000000, fdim(1,-4)=5.000000
fdim(1e308, -1e308) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.12.1 The fdim functions (p: 187-188)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.9.1 The fdim functions (p: 386)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.12.1 The fdim functions (p: 257)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.9.1 The fdim functions (p: 530)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.12.1 The fdim functions (p: 238)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.9.1 The fdim functions (p: 466)
### See also
| | |
| --- | --- |
| [abslabsllabs](abs "c/numeric/math/abs")
(C99) | computes absolute value of an integral value (\(\small{|x|}\)|x|) (function) |
| [fmaxfmaxffmaxl](fmax "c/numeric/math/fmax")
(C99)(C99)(C99) | determines larger of two floating-point values (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/fdim "cpp/numeric/math/fdim") for `fdim` |
c fmax, fmaxf, fmaxl fmax, fmaxf, fmaxl
==================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float fmaxf( float x, float y );
```
| (1) | (since C99) |
|
```
double fmax( double x, double y );
```
| (2) | (since C99) |
|
```
long double fmaxl( long double x, long double y );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define fmax( x, y )
```
| (4) | (since C99) |
1-3) Returns the larger of two floating point arguments, treating NaNs as missing data (between a NaN and a numeric value, the numeric value is chosen).
4) Type-generic macro: If any argument has type `long double`, `fmaxl` is called. Otherwise, if any argument has integer type or has type `double`, `fmax` is called. Otherwise, `fmaxf` is called. ### Parameters
| | | |
| --- | --- | --- |
| x, y | - | floating point values |
### Return value
If successful, returns the larger of two floating point values. The value returned is exact and does not depend on any rounding modes.
### Error handling
This function is not subject to any of the error conditions specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* If one of the two arguments is NaN, the value of the other argument is returned.
* Only if both arguments are NaN is NaN returned.
### Notes
This function is not required to be sensitive to the sign of zero, although some implementations additionally enforce that if one argument is +0 and the other is -0, then +0 is returned.
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("fmax(2,1) = %f\n", fmax(2,1));
printf("fmax(-Inf,0) = %f\n", fmax(-INFINITY,0));
printf("fmax(NaN,-1) = %f\n", fmax(NAN,-1));
}
```
Output:
```
fmax(2,1) = 2.000000
fmax(-Inf,0) = 0.000000
fmax(NaN,-1) = -1.000000
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.12.12.2 The fmax functions (p: 188)
+ 7.25 Type-generic math <tgmath.h> (p: 397)
+ F.10.9.2 The fmax functions (p: 386)
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.12.2 The fmax functions (p: 257-258)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.9.2 The fmax functions (p: 530)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.12.2 The fmax functions (p: 238-239)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.9.2 The fmax functions (p: 466)
### See also
| | |
| --- | --- |
| [isgreater](isgreater "c/numeric/math/isgreater")
(C99) | checks if the first floating-point argument is greater than the second (function macro) |
| [fminfminffminl](fmin "c/numeric/math/fmin")
(C99)(C99)(C99) | determines smaller of two floating-point values (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/fmax "cpp/numeric/math/fmax") for `fmax` |
c isless isless
======
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define isless(x, y) /* implementation defined */
```
| | (since C99) |
Determines if the floating point number `x` is less than the floating-point number `y`, without setting floating-point exceptions.
### Parameters
| | | |
| --- | --- | --- |
| x | - | floating point value |
| y | - | floating point value |
### Return value
Nonzero integral value if `x < y`, `0` otherwise.
### Notes
The built-in `operator<` for floating-point numbers may raise `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` if one or both of the arguments is NaN. This function is a "quiet" version of `operator<`.
### Example
```
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("isless(2.0,1.0) = %d\n", isless(2.0,1.0));
printf("isless(1.0,2.0) = %d\n", isless(1.0,2.0));
printf("isless(INFINITY,1.0) = %d\n", isless(INFINITY,1.0));
printf("isless(1.0,NAN) = %d\n", isless(1.0,NAN));
return 0;
}
```
Possible output:
```
isless(2.0,1.0) = 0
isless(1.0,2.0) = 1
isless(INFINITY,1.0) = 0
isless(1.0,NAN) = 0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.14.3 The isless macro (p: 260)
+ F.10.11 Comparison macros (p: 531)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.14.3 The isless macro (p: 241)
### See also
| | |
| --- | --- |
| [isgreater](isgreater "c/numeric/math/isgreater")
(C99) | checks if the first floating-point argument is greater than the second (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/isless "cpp/numeric/math/isless") for `isless` |
c atanh, atanhf, atanhl atanh, atanhf, atanhl
=====================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float atanhf( float arg );
```
| (1) | (since C99) |
|
```
double atanh( double arg );
```
| (2) | (since C99) |
|
```
long double atanhl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define atanh( arg )
```
| (4) | (since C99) |
1-3) Computes the inverse hyperbolic tangent of `arg`.
4) Type-generic macro: If the argument has type `long double`, `atanhl` is called. Otherwise, if the argument has integer type or the type `double`, `atanh` is called. Otherwise, `atanhf` is called. If the argument is complex, then the macro invokes the corresponding complex function (`[catanhf](http://en.cppreference.com/w/c/numeric/complex/catanh)`, `[catanh](http://en.cppreference.com/w/c/numeric/complex/catanh)`, `[catanhl](http://en.cppreference.com/w/c/numeric/complex/catanh)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value representing the area of a hyperbolic sector |
### Return value
If no errors occur, the inverse hyperbolic tangent of `arg` (tanh-1
(arg), or artanh(arg)), is returned.
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a pole error occurs, `[±HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `±HUGE_VALF`, or `±HUGE_VALL` is returned (with the correct sign).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the argument is not on the interval [-1, +1], a range error occurs.
If the argument is ±1, a pole error occurs.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ±0, it is returned unmodified
* if the argument is ±1, ±∞ is returned and `[FE\_DIVBYZERO](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* if |arg|>1, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised.
* if the argument is NaN, NaN is returned
### Notes
Although the C standard names this function "arc hyperbolic tangent", the inverse functions of the hyperbolic functions are the area functions. Their argument is the area of a hyperbolic sector, not an arc. The correct name is "inverse hyperbolic tangent" (used by POSIX) or "area hyperbolic tangent".
[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/atanh.html) that in case of underflow, `arg` is returned unmodified, and if that is not supported, an implementation-defined value no greater than DBL\_MIN, FLT\_MIN, and LDBL\_MIN is returned.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
printf("atanh(0) = %f\natanh(-0) = %f\n", atanh(0), atanh(-0.0));
printf("atanh(0.9) = %f\n", atanh(0.9));
//error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("atanh(-1) = %f\n", atanh(-1));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_DIVBYZERO)) puts(" FE_DIVBYZERO raised");
}
```
Possible output:
```
atanh(0) = 0.000000
atanh(-0) = -0.000000
atanh(0.9) = 1.472219
atanh(-1) = -inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.5.3 The atanh functions (p: 241)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.2.3 The atanh functions (p: 520)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.5.3 The atanh functions (p: 221-222)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.2.3 The atanh functions (p: 457)
### See also
| | |
| --- | --- |
| [asinhasinhfasinhl](asinh "c/numeric/math/asinh")
(C99)(C99)(C99) | computes inverse hyperbolic sine (\({\small\operatorname{arsinh}{x} }\)arsinh(x)) (function) |
| [acoshacoshfacoshl](acosh "c/numeric/math/acosh")
(C99)(C99)(C99) | computes inverse hyperbolic cosine (\({\small\operatorname{arcosh}{x} }\)arcosh(x)) (function) |
| [tanhtanhftanhl](tanh "c/numeric/math/tanh")
(C99)(C99) | computes hyperbolic tangent (\({\small\tanh{x} }\)tanh(x)) (function) |
| [catanhcatanhfcatanhl](../complex/catanh "c/numeric/complex/catanh")
(C99)(C99)(C99) | computes the complex arc hyperbolic tangent (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/atanh "cpp/numeric/math/atanh") for `atanh` |
### External links
[Weisstein, Eric W. "Inverse Hyperbolic Tangent."](http://mathworld.wolfram.com/InverseHyperbolicTangent.html) From MathWorld--A Wolfram Web Resource.
| programming_docs |
c sin, sinf, sinl sin, sinf, sinl
===============
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float sinf( float arg );
```
| (1) | (since C99) |
|
```
double sin( double arg );
```
| (2) | |
|
```
long double sinl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define sin( arg )
```
| (4) | (since C99) |
1-3) Computes the sine of `arg` (measured in radians).
4) Type-generic macro: If the argument has type `long double`, `sinl` is called. Otherwise, if the argument has integer type or the type `double`, `sin` is called. Otherwise, `sinf` is called. If the argument is complex, then the macro invokes the corresponding complex function (`[csinf](http://en.cppreference.com/w/c/numeric/complex/csin)`, `[csin](http://en.cppreference.com/w/c/numeric/complex/csin)`, `[csinl](http://en.cppreference.com/w/c/numeric/complex/csin)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value representing an angle in radians |
### Return value
If no errors occur, the sine of `arg` (sin(arg)) in the range [-1 ; +1], is returned.
| | |
| --- | --- |
| The result may have little or no significance if the magnitude of `arg` is large. | (until C99) |
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ±0, it is returned unmodified
* if the argument is ±∞, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* if the argument is NaN, NaN is returned
### Notes
The case where the argument is infinite is not specified to be a domain error in C, but it is defined as a [domain error in POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sin.html).
POSIX also specifies that in case of underflow, `arg` is returned unmodified, and if that is not supported, an implementation-defined value no greater than DBL\_MIN, FLT\_MIN, and LDBL\_MIN is returned.
### Example
```
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
double pi = acos(-1);
// typical usage
printf("sin(pi/6) = %f\n", sin(pi/6));
printf("sin(pi/2) = %f\n", sin(pi/2));
printf("sin(-3*pi/4) = %f\n", sin(-3*pi/4));
// special values
printf("sin(+0) = %f\n", sin(0.0));
printf("sin(-0) = %f\n", sin(-0.0));
// error handling
feclearexcept(FE_ALL_EXCEPT);
printf("sin(INFINITY) = %f\n", sin(INFINITY));
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
}
```
Possible output:
```
sin(pi/6) = 0.500000
sin(pi/2) = 1.000000
sin(-3*pi/4) = -0.707107
sin(+0) = 0.000000
sin(-0) = -0.000000
sin(INFINITY) = -nan
FE_INVALID raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.4.6 The sin functions (p: 239-240)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.1.6 The sin functions (p: 519)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.4.6 The sin functions (p: 220)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.1.6 The sin functions (p: 456)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.2.6 The sin function
### See also
| | |
| --- | --- |
| [coscosfcosl](cos "c/numeric/math/cos")
(C99)(C99) | computes cosine (\({\small\cos{x} }\)cos(x)) (function) |
| [tantanftanl](tan "c/numeric/math/tan")
(C99)(C99) | computes tangent (\({\small\tan{x} }\)tan(x)) (function) |
| [asinasinfasinl](asin "c/numeric/math/asin")
(C99)(C99) | computes arc sine (\({\small\arcsin{x} }\)arcsin(x)) (function) |
| [csincsinfcsinl](../complex/csin "c/numeric/complex/csin")
(C99)(C99)(C99) | computes the complex sine (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/sin "cpp/numeric/math/sin") for `sin` |
c scalbn, scalbnf, scalbnl, scalbln, scalblnf, scalblnl scalbn, scalbnf, scalbnl, scalbln, scalblnf, scalblnl
=====================================================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float scalbnf( float arg, int exp );
```
| (1) | (since C99) |
|
```
double scalbn( double arg, int exp );
```
| (2) | (since C99) |
|
```
long double scalbnl( long double arg, int exp );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define scalbn( arg, exp )
```
| (4) | (since C99) |
| Defined in header `<math.h>` | | |
|
```
float scalblnf( float arg, long exp );
```
| (5) | (since C99) |
|
```
double scalbln( double arg, long exp );
```
| (6) | (since C99) |
|
```
long double scalblnl( long double arg, long exp );
```
| (7) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define scalbln( arg, exp )
```
| (8) | (since C99) |
1-3,5-7) Multiplies a floating point value `arg` by `[FLT\_RADIX](../../types/limits "c/types/limits")` raised to power `exp`.
4,8) Type-generic macros: If `arg` has type `long double`, `scalbnl` or `scalblnl` is called. Otherwise, if `arg` has integer type or the type `double`, `scalbn` or `scalbln` is called. Otherwise, `scalbnf` or `scalblnf` is called, respectively. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
| exp | - | integer value |
### Return value
If no errors occur, `arg` multiplied by `[FLT\_RADIX](../../types/limits "c/types/limits")` to the power of `exp` (arg×FLT\_RADIXexp
) is returned.
If a range error due to overflow occurs, `[±HUGE\_VAL](huge_val "c/numeric/math/HUGE VAL")`, `±HUGE_VALF`, or `±HUGE_VALL` is returned.
If a range error due to underflow occurs, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* Unless a range error occurs, `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is never raised (the result is exact)
* Unless a range error occurs, the [current rounding mode](../fenv/fe_round "c/numeric/fenv/FE round") is ignored
* If `arg` is ±0, it is returned, unmodified
* If `arg` is ±∞, it is returned, unmodified
* If `exp` is 0, then `arg` is returned, unmodified
* If `arg` is NaN, NaN is returned
### Notes
On binary systems (where `[FLT\_RADIX](../../types/limits "c/types/limits")` is `2`), `scalbn` is equivalent to `[ldexp](ldexp "c/numeric/math/ldexp")`.
Although `scalbn` and `scalbln` are specified to perform the operation efficiently, on many implementations they are less efficient than multiplication or division by a power of two using arithmetic operators.
The `scalbln` function is provided because the factor required to scale from the smallest positive floating-point value to the largest finite one may be greater than 32767, the standard-guaranteed `[INT\_MAX](../../types/limits "c/types/limits")`. In particular, for the 80-bit `long double`, the factor is 32828.
The GNU implementation does not set `errno` regardless of `math_errhandling`.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
printf("scalbn(7, -4) = %f\n", scalbn(7, -4));
printf("scalbn(1, -1074) = %g (minimum positive subnormal double)\n",
scalbn(1, -1074));
printf("scalbn(nextafter(1,0), 1024) = %g (largest finite double)\n",
scalbn(nextafter(1,0), 1024));
// special values
printf("scalbn(-0, 10) = %f\n", scalbn(-0.0, 10));
printf("scalbn(-Inf, -1) = %f\n", scalbn(-INFINITY, -1));
// error handling
errno = 0; feclearexcept(FE_ALL_EXCEPT);
printf("scalbn(1, 1024) = %f\n", scalbn(1, 1024));
if(errno == ERANGE) perror(" errno == ERANGE");
if(fetestexcept(FE_OVERFLOW)) puts(" FE_OVERFLOW raised");
}
```
Possible output:
```
scalbn(7, -4) = 0.437500
scalbn(1, -1074) = 4.94066e-324 (minimum positive subnormal double)
scalbn(nextafter(1,0), 1024) = 1.79769e+308 (largest finite double)
scalbn(-0, 10) = -0.000000
scalbn(-Inf, -1) = -inf
scalbn(1, 1024) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.6.13 The scalbn functions (p: 247)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.3.13 The scalbn functions (p: 523)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.6.13 The scalbn functions (p: 228)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.3.13 The scalbn functions (p: 460)
### See also
| | |
| --- | --- |
| [frexpfrexpffrexpl](frexp "c/numeric/math/frexp")
(C99)(C99) | breaks a number into significand and a power of `2` (function) |
| [ldexpldexpfldexpl](ldexp "c/numeric/math/ldexp")
(C99)(C99) | multiplies a number by `2` raised to a power (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/scalbn "cpp/numeric/math/scalbn") for `scalbn` |
c tan, tanf, tanl tan, tanf, tanl
===============
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float tanf( float arg );
```
| (1) | (since C99) |
|
```
double tan( double arg );
```
| (2) | |
|
```
long double tanl( long double arg );
```
| (3) | (since C99) |
| Defined in header `<tgmath.h>` | | |
|
```
#define tan( arg )
```
| (4) | (since C99) |
1-3) Computes the tangent of `arg` (measured in radians).
4) Type-generic macro: If the argument has type `long double`, `tanl` is called. Otherwise, if the argument has integer type or the type `double`, `tan` is called. Otherwise, `tanf` is called. If the argument is complex, then the macro invokes the corresponding complex function (`[ctanf](http://en.cppreference.com/w/c/numeric/complex/ctan)`, `[ctan](http://en.cppreference.com/w/c/numeric/complex/ctan)`, `[ctanl](http://en.cppreference.com/w/c/numeric/complex/ctan)`). ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value representing angle in radians |
### Return value
If no errors occur, the tangent of `arg` (tan(arg)) is returned.
| | |
| --- | --- |
| The result may have little or no significance if the magnitude of `arg` is large. | (until C99) |
If a domain error occurs, an implementation-defined value is returned (NaN where supported).
If a range error occurs due to underflow, the correct result (after rounding) is returned.
### Error handling
Errors are reported as specified in [math\_errhandling](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* if the argument is ±0, it is returned unmodified
* if the argument is ±∞, NaN is returned and `[FE\_INVALID](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised
* if the argument is NaN, NaN is returned
### Notes
The case where the argument is infinite is not specified to be a domain error in C, but it is defined as a [domain error in POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/tan.html).
The function has mathematical poles at π(1/2 + n); however no common floating-point representation is able to represent π/2 exactly, thus there is no value of the argument for which a pole error occurs.
### Example
```
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
int main(void)
{
double pi = acos(-1);
// typical usage
printf("tan (pi/4) = %+f\n", tan( pi/4)); // 45 deg
printf("tan(3*pi/4) = %+f\n", tan(3*pi/4)); // 135 deg
printf("tan(5*pi/4) = %+f\n", tan(5*pi/4)); // -135 deg
printf("tan(7*pi/4) = %+f\n", tan(7*pi/4)); // -45 deg
// special values
printf("tan(+0) = %f\n", tan(0.0));
printf("tan(-0) = %f\n", tan(-0.0));
// error handling
feclearexcept(FE_ALL_EXCEPT);
printf("tan(INFINITY) = %f\n", tan(INFINITY));
if(fetestexcept(FE_INVALID)) puts(" FE_INVALID raised");
}
```
Possible output:
```
tan (pi/4) = +1.000000
tan(3*pi/4) = -1.000000
tan(5*pi/4) = +1.000000
tan(7*pi/4) = -1.000000
tan(+0) = 0.000000
tan(-0) = -0.000000
tan(INFINITY) = -nan
FE_INVALID raised
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.4.7 The tan functions (p: 240)
+ 7.25 Type-generic math <tgmath.h> (p: 373-375)
+ F.10.1.7 The tan functions (p: 519)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.4.7 The tan functions (p: 220)
+ 7.22 Type-generic math <tgmath.h> (p: 335-337)
+ F.9.1.7 The tan functions (p: 457)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.5.2.7 The tan function
### See also
| | |
| --- | --- |
| [sinsinfsinl](sin "c/numeric/math/sin")
(C99)(C99) | computes sine (\({\small\sin{x} }\)sin(x)) (function) |
| [coscosfcosl](cos "c/numeric/math/cos")
(C99)(C99) | computes cosine (\({\small\cos{x} }\)cos(x)) (function) |
| [atanatanfatanl](atan "c/numeric/math/atan")
(C99)(C99) | computes arc tangent (\({\small\arctan{x} }\)arctan(x)) (function) |
| [ctanctanfctanl](../complex/ctan "c/numeric/complex/ctan")
(C99)(C99)(C99) | computes the complex tangent (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/tan "cpp/numeric/math/tan") for `tan` |
c isnormal isnormal
========
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
#define isnormal(arg) /* implementation defined */
```
| | (since C99) |
Determines if the given floating point number `arg` is normal, i.e. is neither zero, subnormal, infinite, nor `NaN`. The macro returns an integral value.
`[FLT\_EVAL\_METHOD](../../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")` is ignored: even if the argument is evaluated with more range and precision than its type, it is first converted to its semantic type, and the classification is based on that.
### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
Nonzero integral value if `arg` is normal, `0` otherwise.
### Example
```
#include <stdio.h>
#include <math.h>
#include <float.h>
int main(void)
{
printf("isnormal(NAN) = %d\n", isnormal(NAN));
printf("isnormal(INFINITY) = %d\n", isnormal(INFINITY));
printf("isnormal(0.0) = %d\n", isnormal(0.0));
printf("isnormal(DBL_MIN/2.0) = %d\n", isnormal(DBL_MIN/2.0));
printf("isnormal(1.0) = %d\n", isnormal(1.0));
}
```
Output:
```
isnormal(NAN) = 0
isnormal(INFINITY) = 0
isnormal(0.0) = 0
isnormal(DBL_MIN/2.0) = 0
isnormal(1.0) = 1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.12.3.5 The isnormal macro (p: 237)
* C99 standard (ISO/IEC 9899:1999):
+ 7.12.3.5 The isnormal macro (p: 217-218)
### See also
| | |
| --- | --- |
| [fpclassify](fpclassify "c/numeric/math/fpclassify")
(C99) | classifies the given floating-point value (function macro) |
| [isfinite](isfinite "c/numeric/math/isfinite")
(C99) | checks if the given number has finite value (function macro) |
| [isinf](isinf "c/numeric/math/isinf")
(C99) | checks if the given number is infinite (function macro) |
| [isnan](isnan "c/numeric/math/isnan")
(C99) | checks if the given number is NaN (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/math/isnormal "cpp/numeric/math/isnormal") for `isnormal` |
c roundeven, roundevenf, roundevenl roundeven, roundevenf, roundevenl
=================================
| Defined in header `<math.h>` | | |
| --- | --- | --- |
|
```
float roundevenf( float arg );
```
| (1) | (since C23) |
|
```
double roundeven( double arg );
```
| (2) | (since C23) |
|
```
long double roundevenl( long double arg );
```
| (3) | (since C23) |
| Defined in header `<tgmath.h>` | | |
|
```
#define roundeven( arg )
```
| (4) | (since C23) |
1-3) Computes the nearest integer value to `arg` (in floating-point format), rounding halfway cases to nearest even integer, regardless of the current rounding mode.
4) Type-generic macro: If `arg` has type `long double`, `roundevenl` is called. Otherwise, if `arg` has integer type or the type `double`, `roundeven` is called. Otherwise, `roundevenf` is called, respectively. ### Parameters
| | | |
| --- | --- | --- |
| arg | - | floating point value |
### Return value
If no errors occur, the nearest integer value to `arg`, rounding halfway cases to nearest even integer, is returned.
### Error handling
This function is not subject to any of the errors specified in [`math_errhandling`](math_errhandling "c/numeric/math/math errhandling").
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
* `[FE\_INEXACT](../fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is never raised
* If `arg` is ±∞, it is returned, unmodified
* If `arg` is ±0, it is returned, unmodified
* If `arg` is NaN, NaN is returned
### Example
```
#include <math.h>
#include <stdio.h>
int main(void)
{
printf("roundeven(+2.4) = %+.1f\n", roundeven(2.4));
printf("roundeven(-2.4) = %+.1f\n", roundeven(-2.4));
printf("roundeven(+2.5) = %+.1f\n", roundeven(2.5));
printf("roundeven(-2.5) = %+.1f\n", roundeven(-2.5));
printf("roundeven(+2.6) = %+.1f\n", roundeven(2.6));
printf("roundeven(-2.6) = %+.1f\n", roundeven(-2.6));
printf("roundeven(+3.5) = %+.1f\n", roundeven(3.5));
printf("roundeven(-3.5) = %+.1f\n", roundeven(-3.5));
printf("roundeven(-0.0) = %+.1f\n", roundeven(-0.0));
printf("roundeven(-Inf) = %+f\n", roundeven(-INFINITY));
}
```
Possible output:
```
roundeven(+2.4) = +2.0
roundeven(-2.4) = -2.0
roundeven(+2.5) = +2.0
roundeven(-2.5) = -2.0
roundeven(+2.6) = +3.0
roundeven(-2.6) = -3.0
roundeven(+3.5) = +4.0
roundeven(-3.5) = -4.0
roundeven(-0.0) = -0.0
roundeven(-Inf) = -inf
```
### References
* C23 standard (ISO/IEC 9899:2023):
+ 7.12.9.8 The roundeven functions (p: 265-266)
+ 7.27 Type-generic math <tgmath.h> (p: 386-390)
+ F.10.6.8 The roundeven functions (p: 532)
### See also
| | |
| --- | --- |
| [rintrintfrintllrintlrintflrintlllrintllrintfllrintl](rint "c/numeric/math/rint")
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) | rounds to an integer using current rounding mode with exception if the result differs (function) |
| [roundroundfroundllroundlroundflroundlllroundllroundfllroundl](round "c/numeric/math/round")
(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99)(C99) | rounds to nearest integer, rounding away from zero in halfway cases (function) |
c srand srand
=====
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
void srand( unsigned seed );
```
| | |
Seeds the pseudo-random number generator used by `[rand()](rand "c/numeric/random/rand")` with the value `seed`.
If `rand()` is used before any calls to `srand()`, `rand()` behaves as if it was seeded with `srand(1)`.
Each time `rand()` is seeded with the same `seed`, it must produce the same sequence of values.
`srand()` is not guaranteed to be thread-safe.
### Parameters
| | | |
| --- | --- | --- |
| seed | - | the seed value |
### Return value
(none).
### Notes
Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to `rand()`, and the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.
Standard practice is to use the result of a call to `[time](http://en.cppreference.com/w/c/chrono/time)(0)` as the seed. However, `time()` returns a `[time\_t](../../chrono/time_t "c/chrono/time t")` value, and `time_t` is not guaranteed to be an integral type. In practice, though, every major implementation defines `time_t` to be an integral type, and this is also what POSIX requires.
### Example
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL)); //use current time as seed for random generator
int random_variable = rand();
printf("Random value on [0,%d]: %d\n", RAND_MAX, random_variable);
}
```
Possible output:
```
Random value on [0 2147483647]: 1373858591
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.2.2 The srand function (p: 252-253)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.2.2 The srand function (p: 346-347)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.2.2 The srand function (p: 312-313)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.2.2 The srand function
### See also
| | |
| --- | --- |
| [rand](rand "c/numeric/random/rand") | generates a pseudo-random number (function) |
| [RAND\_MAX](rand_max "c/numeric/random/RAND MAX") | maximum possible value generated by `[rand](http://en.cppreference.com/w/c/numeric/random/rand)()` (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/random/srand "cpp/numeric/random/srand") for `srand` |
| programming_docs |
c RAND_MAX RAND\_MAX
=========
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
#define RAND_MAX /*implementation defined*/
```
| | |
Expands to an integer constant expression equal to the maximum value returned by the function `[rand()](rand "c/numeric/random/rand")`. This value is implementation dependent. It's guaranteed that this value is at least `32767`.
### Example
```
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL)); // use current time as seed for random generator
printf("RAND_MAX: %i\n", RAND_MAX);
printf("INT_MAX: %i\n", INT_MAX);
printf("Random value on [0,1]: %f\n", (double)rand() / RAND_MAX);
}
```
Possible output:
```
RAND_MAX: 2147483647
INT_MAX: 2147483647
Random value on [0,1]: 0.362509
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22/3 General utilities <stdlib.h> (p: 248)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22/3 General utilities <stdlib.h> (p: 340)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20/3 General utilities <stdlib.h> (p: 306)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10 GENERAL UTILITIES <stdlib.h>
### See also
| | |
| --- | --- |
| [rand](rand "c/numeric/random/rand") | generates a pseudo-random number (function) |
| [srand](srand "c/numeric/random/srand") | seeds pseudo-random number generator (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/random/RAND_MAX "cpp/numeric/random/RAND MAX") for `RAND_MAX` |
c rand rand
====
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
int rand();
```
| | |
Returns a pseudo-random integer value between `0` and `[RAND\_MAX](rand_max "c/numeric/random/RAND MAX")` (`0` and `RAND_MAX` included).
`[srand()](srand "c/numeric/random/srand")` seeds the pseudo-random number generator used by `rand()`. If `rand()` is used before any calls to `srand()`, `rand()` behaves as if it was seeded with `[srand](http://en.cppreference.com/w/c/numeric/random/srand)(1)`. Each time `rand()` is seeded with `srand()`, it must produce the same sequence of values.
`rand()` is not guaranteed to be thread-safe.
### Parameters
(none).
### Return value
Pseudo-random integer value between `0` and `[RAND\_MAX](rand_max "c/numeric/random/RAND MAX")`, inclusive.
### Notes
There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of `rand()` have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between `1` and `0` between calls). `rand()` is not recommended for serious random-number generation needs, like cryptography.
POSIX requires that the period of the pseudo-random number generator used by `rand` be at least 232
.
POSIX offered a thread-safe version of rand called `rand_r`, which is obsolete in favor of the [`drand48`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/drand48.html) family of functions.
### Example
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL)); // use current time as seed for random generator
int random_variable = rand();
printf("Random value on [0,%d]: %d\n", RAND_MAX, random_variable);
// roll a 6-sided die 20 times
for (int n=0; n != 20; ++n) {
int x = 7;
while(x > 6)
x = 1 + rand()/((RAND_MAX + 1u)/6); // Note: 1+rand()%6 is biased
printf("%d ", x);
}
}
```
Possible output:
```
Random value on [0,2147483647]: 448749574
3 1 3 1 4 2 2 1 3 6 4 4 3 1 6 2 3 2 6 1
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.2.1 The rand function (p: 252)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.2.1 The rand function (p: 346)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.2.1 The rand function (p: 312)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.2.1 The rand function
### See also
| | |
| --- | --- |
| [srand](srand "c/numeric/random/srand") | seeds pseudo-random number generator (function) |
| [RAND\_MAX](rand_max "c/numeric/random/RAND MAX") | maximum possible value generated by `rand()` (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric/random/rand "cpp/numeric/random/rand") for `rand` |
c setjmp setjmp
======
| Defined in header `<setjmp.h>` | | |
| --- | --- | --- |
|
```
#define setjmp(env) /* implementation-defined */
```
| | |
Saves the current execution context into a variable `env` of type `[jmp\_buf](jmp_buf "c/program/jmp buf")`. This variable can later be used to restore the current execution context by `[longjmp](longjmp "c/program/longjmp")` function. That is, when a call to `[longjmp](longjmp "c/program/longjmp")` function is made, the execution continues at the particular call site that constructed the `[jmp\_buf](jmp_buf "c/program/jmp buf")` variable passed to `[longjmp](longjmp "c/program/longjmp")`. In that case `setjmp` returns the value passed to `[longjmp](longjmp "c/program/longjmp")`.
The invocation of `setjmp` must appear only in one of the following contexts:
* the entire controlling expression of [`if`](../language/if "c/language/if"), [`switch`](../language/switch "c/language/switch"), [`while`](../language/while "c/language/while"), [`do-while`](../language/do "c/language/do"), [`for`](../language/for "c/language/for").
```
switch(setjmp(env)) { ..
```
* one operand of a relational or equality operator with the other operand an integer constant expression, with the resulting expression being the entire controlling expression of [`if`](../language/if "c/language/if"), [`switch`](../language/switch "c/language/switch"), [`while`](../language/while "c/language/while"), [`do-while`](../language/do "c/language/do"), [`for`](../language/for "c/language/for").
```
if(setjmp(env) > 10) { ...
```
* the operand of a unary ! operator with the resulting expression being the entire controlling expression of [`if`](../language/if "c/language/if"), [`switch`](../language/switch "c/language/switch"), [`while`](../language/while "c/language/while"), [`do-while`](../language/do "c/language/do"), [`for`](../language/for "c/language/for").
```
while(!setjmp(env)) { ...
```
* the entire expression of an [expression statement](../language/statements#Expression_statements "c/language/statements") (possibly cast to `void`).
```
setjmp(env);
```
If `setjmp` appears in any other context, the behavior is undefined.
Upon return to the scope of `setjmp`, all accessible objects, floating-point status flags, and other components of the abstract machine have the same values as they had when `[longjmp](longjmp "c/program/longjmp")` was executed, except for the non-[volatile](https://en.cppreference.com/w/cpp/language/cv "cpp/language/cv") local variables in the function containing the invocation of `setjmp`, whose values are indeterminate if they have been changed since the `setjmp` invocation.
### Parameters
| | | |
| --- | --- | --- |
| env | - | variable to save the execution state of the program to. |
### Return value
`0` if the macro was called by the original code and the execution context was saved to `env`.
Non-zero value if a non-local jump was just performed. The return value is the same as passed to `[longjmp](longjmp "c/program/longjmp")`.
### Notes
Above requirements forbid using return value of `setjmp` in data flow (e.g. to initialize or assign an object with it). The return value can only be either used in control flow or discarded.
### Example
```
#include <stdio.h>
#include <setjmp.h>
#include <stdnoreturn.h>
jmp_buf my_jump_buffer;
noreturn void foo(int count)
{
printf("foo(%d) called\n", count);
longjmp(my_jump_buffer, count+1); // will return count+1 out of setjmp
}
int main(void)
{
volatile int count = 0; // modified local vars in setjmp scope must be volatile
if (setjmp(my_jump_buffer) != 5) // compare against constant in an if
foo(++count);
}
```
Output:
```
foo(1) called
foo(2) called
foo(3) called
foo(4) called
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.13.1.1 The setjmp macro (p: 191)
* C11 standard (ISO/IEC 9899:2011):
+ 7.13.1.1 The setjmp macro (p: 262-263)
* C99 standard (ISO/IEC 9899:1999):
+ 7.13.1.1 The setjmp macro (p: 243-244)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.6.1 The setjmp macro
### See also
| | |
| --- | --- |
| [longjmp](longjmp "c/program/longjmp") | jumps to specified location (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/setjmp "cpp/utility/program/setjmp") for `setjmp` |
c SIG_DFL, SIG_IGN SIG\_DFL, SIG\_IGN
==================
| Defined in header `<signal.h>` | | |
| --- | --- | --- |
|
```
#define SIG_DFL /*implementation defined*/
```
| | |
|
```
#define SIG_IGN /*implementation defined*/
```
| | |
The `SIG_DFL` and `SIG_IGN` macros expand into integral expressions that are not equal to an address of any function. The macros define signal handling strategies for `[signal](http://en.cppreference.com/w/c/program/signal)()` function.
| Constant | Explanation |
| --- | --- |
| `SIG_DFL` | default signal handling |
| `SIG_IGN` | signal is ignored |
### Example
```
#include <signal.h>
#include <stdio.h>
int main(void)
{
/* using the default signal handler */
raise(SIGTERM);
printf("Exit main()\n"); /* never reached */
}
```
Output:
```
(none)
```
### Example
```
#include <signal.h>
#include <stdio.h>
int main(void)
{
/* ignoring the signal */
signal(SIGTERM, SIG_IGN);
raise(SIGTERM);
printf("Exit main()\n");
}
```
Output:
```
Exit main()
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.14/3 Signal handling <signal.h> (p: 193)
* C11 standard (ISO/IEC 9899:2011):
+ 7.14/3 Signal handling <signal.h> (p: 265)
* C99 standard (ISO/IEC 9899:1999):
+ 7.14/3 Signal handling <signal.h> (p: 246)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.7 SIGNAL HANDLING <signal.h>
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/SIG_strategies "cpp/utility/program/SIG strategies") for `SIG_DFL, SIG_IGN` |
c _Exit \_Exit
======
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
void _Exit( int exit_code );
```
| | (since C99) (until C11) |
|
```
_Noreturn void _Exit( int exit_code );
```
| | (since C11) |
Causes normal program termination to occur without completely cleaning the resources.
Functions passed to `[at\_quick\_exit()](at_quick_exit "c/program/at quick exit")` or `[atexit()](atexit "c/program/atexit")` are not called. Whether open streams with unwritten buffered data are flushed, open streams are closed, or temporary files are removed is implementation-defined.
If `exit_code` is `0` or `[EXIT\_SUCCESS](exit_status "c/program/EXIT status")`, an implementation-defined status indicating successful termination is returned to the host environment. If `exit_code` is `[EXIT\_FAILURE](exit_status "c/program/EXIT status")`, an implementation-defined status, indicating *unsuccessful* termination, is returned. In other cases an implementation-defined status value is returned.
### Parameters
| | | |
| --- | --- | --- |
| exit\_code | - | exit status of the program |
### Return value
(none).
### Example
```
#include <stdlib.h>
#include <stdio.h>
/* _Exit does not call functions registered with atexit. */
void f1(void)
{
puts("pushed first");
}
void f2(void)
{
puts("pushed second");
}
int main(void)
{
printf("Enter main()\n");
atexit(f1);
atexit(f2);
fflush(stdout); /* _Exit may not flush unwritten buffered data */
_Exit(0);
}
```
Output:
```
Enter main()
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.4.5 The \_Exit function (p: 256)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.4.5 The \_Exit function (p: 352)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.4.4 The \_Exit function (p: 316)
### See also
| | |
| --- | --- |
| [abort](abort "c/program/abort") | causes abnormal program termination (without cleaning up) (function) |
| [exit](exit "c/program/exit") | causes normal program termination with cleaning up (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/_Exit "cpp/utility/program/ Exit") for `_Exit` |
c system system
======
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
int system( const char *command );
```
| | |
Calls the host environment's command processor with the parameter `command`. Returns an implementation-defined value (usually the value that the invoked program returns).
If command is a null pointer, checks if the host environment has a command processor and returns a nonzero value if and only if the command processor exists.
### Parameters
| | | |
| --- | --- | --- |
| command | - | character string identifying the command to be run in the command processor. If a null pointer is given, command processor is checked for existence |
### Return value
Implementation-defined value. If `command` is a null pointer, returns a nonzero value if and only if the command processor exists.
### Notes
On POSIX systems, the return value can be decomposed using [`WEXITSTATUS` and `WSTOPSIG`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html).
The related POSIX function [popen](http://pubs.opengroup.org/onlinepubs/9699919799/functions/popen.html) makes the output generated by `command` available to the caller.
### Example
In this example there is a system call of the unix command **date +%A** and a system call to (possibly installed) **gcc** compiler with command-line argument (*--version*):
```
#include <stdlib.h>
int main(void) {
system("date +%A");
system("gcc --version");
}
```
Possible output:
```
Wednesday
gcc (GCC) 11.2.0
...
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.4.8 The system function (p: 257)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.4.8 The system function (p: 353-354)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.4.6 The system function (p: 317)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.4.5 The system function
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/system "cpp/utility/program/system") for `system` |
c SIG_ERR SIG\_ERR
========
| Defined in header `<signal.h>` | | |
| --- | --- | --- |
|
```
#define SIG_ERR /* implementation defined */
```
| | |
A value of type `void (*)(int)`. When returned by `[signal](signal "c/program/signal")`, indicates that an error has occurred.
### Example
```
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void signal_handler(int sig)
{
printf("Received signal: %d\n", sig);
}
int main(void)
{
/* Install a signal handler. */
if (signal(SIGTERM, signal_handler) == SIG_ERR)
{
printf("Error while installing a signal handler.\n");
exit(EXIT_FAILURE);
}
printf("Sending signal: %d\n", SIGTERM);
if (raise(SIGTERM) != 0)
{
printf("Error while raising the SIGTERM signal.\n");
exit(EXIT_FAILURE);
}
printf("Exit main()\n");
return EXIT_SUCCESS;
}
```
Output:
```
Sending signal: 15
Received signal: 15
Exit main()
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.14/3 Signal handling <signal.h> (p: 194)
* C11 standard (ISO/IEC 9899:2011):
+ 7.14/3 Signal handling <signal.h> (p: 265)
* C99 standard (ISO/IEC 9899:1999):
+ 7.14/3 Signal handling <signal.h> (p: 246)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.7 SIGNAL HANDLING <signal.h>
### See also
| | |
| --- | --- |
| [signal](signal "c/program/signal") | sets a signal handler for particular signal (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/SIG_ERR "cpp/utility/program/SIG ERR") for `SIG_ERR` |
c abort abort
=====
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
void abort(void);
```
| | (until C11) |
|
```
_Noreturn void abort(void);
```
| | (since C11) |
Causes abnormal program termination unless `[SIGABRT](sig_types "c/program/SIG types")` is being caught by a signal handler passed to signal and the handler does not return.
Functions passed to `[atexit()](atexit "c/program/atexit")` are not called. Whether open resources such as files are closed is implementation defined. An implementation defined status is returned to the host environment that indicates unsuccessful execution.
### Parameters
(none).
### Return value
(none).
### Notes
POSIX [specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/abort.html) that the `abort()` function overrides blocking or ignoring the `SIGABRT` signal.
Some compiler intrinsics, e.g. [`__builtin_trap`](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html) (gcc, clang, and icc) or [`__debugbreak`](https://docs.microsoft.com/en-us/cpp/intrinsics/debugbreak?view=msvc-160) (msvc), can be used to terminate the program as fast as possible.
### Example
```
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("data.txt","r");
if (fp == NULL) {
fprintf(stderr, "error opening file data.txt in function main()\n");
abort();
}
/* Normal processing continues here. */
fclose(fp);
printf("Normal Return\n");
return 0;
}
```
Output:
```
error opening file data.txt in function main()
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.4.1 The abort function (p: 255)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.4.1 The abort function (p: 350)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.4.1 The abort function (p: 315)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.4.1 The abort function
### See also
| | |
| --- | --- |
| [exit](exit "c/program/exit") | causes normal program termination with cleaning up (function) |
| [atexit](atexit "c/program/atexit") | registers a function to be called on `[exit()](exit "c/program/exit")` invocation (function) |
| [quick\_exit](quick_exit "c/program/quick exit")
(C11) | causes normal program termination without completely cleaning up (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/abort "cpp/utility/program/abort") for `abort` |
c quick_exit quick\_exit
===========
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
_Noreturn void quick_exit( int exit_code );
```
| | (since C11) |
Causes normal program termination to occur without completely cleaning the resources.
Functions passed to `[at\_quick\_exit](at_quick_exit "c/program/at quick exit")` are called in reverse order of their registration. After calling the registered functions, calls `[\_Exit](http://en.cppreference.com/w/c/program/_Exit)(exit_code)`.
Functions passed to `[atexit](atexit "c/program/atexit")` or signal handlers passed to `[signal](signal "c/program/signal")` are not called.
### Parameters
| | | |
| --- | --- | --- |
| exit\_code | - | exit status of the program |
### Return value
(none).
### Example
```
#include <stdlib.h>
#include <stdio.h>
void f1(void)
{
puts("pushed first");
fflush(stdout);
}
void f2(void)
{
puts("pushed second");
}
void f3(void)
{
puts("won't be called");
}
int main(void)
{
at_quick_exit(f1);
at_quick_exit(f2);
atexit(f3);
quick_exit(0);
}
```
Output:
```
pushed second
pushed first
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.4.7 The quick\_exit function (p: 257)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.4.7 The quick\_exit function (p: 353)
### See also
| | |
| --- | --- |
| [abort](abort "c/program/abort") | causes abnormal program termination (without cleaning up) (function) |
| [atexit](atexit "c/program/atexit") | registers a function to be called on `[exit()](exit "c/program/exit")` invocation (function) |
| [at\_quick\_exit](at_quick_exit "c/program/at quick exit")
(C11) | registers a function to be called on **`quick_exit`** invocation (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/quick_exit "cpp/utility/program/quick exit") for `quick_exit` |
| programming_docs |
c SIGTERM, SIGSEGV, SIGINT, SIGILL, SIGABRT, SIGFPE SIGTERM, SIGSEGV, SIGINT, SIGILL, SIGABRT, SIGFPE
=================================================
| Defined in header `<signal.h>` | | |
| --- | --- | --- |
|
```
#define SIGTERM /*implementation defined*/
```
| | |
|
```
#define SIGSEGV /*implementation defined*/
```
| | |
|
```
#define SIGINT /*implementation defined*/
```
| | |
|
```
#define SIGILL /*implementation defined*/
```
| | |
|
```
#define SIGABRT /*implementation defined*/
```
| | |
|
```
#define SIGFPE /*implementation defined*/
```
| | |
Each of the above macro constants expands to an integer constant expression with distinct values, which represent different signals sent to the program.
| Constant | Explanation |
| --- | --- |
| `SIGTERM` | termination request, sent to the program |
| `SIGSEGV` | invalid memory access (segmentation fault) |
| `SIGINT` | external interrupt, usually initiated by the user |
| `SIGILL` | invalid program image, such as invalid instruction |
| `SIGABRT` | abnormal termination condition, as is e.g. initiated by `[abort()](abort "c/program/abort")` |
| `SIGFPE` | erroneous arithmetic operation such as divide by zero |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.14/3 Signal handling <signal.h> (p: 193)
* C11 standard (ISO/IEC 9899:2011):
+ 7.14/3 Signal handling <signal.h> (p: 265)
* C99 standard (ISO/IEC 9899:1999):
+ 7.14/3 Signal handling <signal.h> (p: 246)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.7 SIGNAL HANDLING <signal.h>
### See also
| | |
| --- | --- |
| [signal](signal "c/program/signal") | sets a signal handler for particular signal (function) |
| [raise](raise "c/program/raise") | runs the signal handler for particular signal (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/SIG_types "cpp/utility/program/SIG types") for signal types |
c longjmp longjmp
=======
| Defined in header `<setjmp.h>` | | |
| --- | --- | --- |
|
```
void longjmp( jmp_buf env, int status );
```
| | (until C11) |
|
```
_Noreturn void longjmp( jmp_buf env, int status );
```
| | (since C11) |
Loads the execution context `env` saved by a previous call to `[setjmp](setjmp "c/program/setjmp")`. This function does not return. Control is transferred to the call site of the macro `[setjmp](setjmp "c/program/setjmp")` that set up `env`. That `[setjmp](setjmp "c/program/setjmp")` then returns the value, passed as the `status`.
If the function that called `[setjmp](setjmp "c/program/setjmp")` has exited (whether by return or by a different `longjmp` higher up the stack), the behavior is undefined. In other words, only long jumps up the call stack are allowed.
| | |
| --- | --- |
| Jumping across threads (if the function that called `setjmp` was executed by another thread) is also undefined behavior. | (since C11) |
| | |
| --- | --- |
| If when `[setjmp](setjmp "c/program/setjmp")` was called, a [VLA](../language/array "c/language/array") or another [variably-modified type](../language/declarations "c/language/declarations") variable was in scope and control left that scope, `longjmp` to that `setjmp` invokes undefined behavior even if control remained within the function.
On the way up the stack, `longjmp` does not deallocate any VLAs, memory leaks may occur if their lifetimes are terminated in this way:
```
void g(int n)
{
int a[n]; // a may remain allocated
h(n); // does not return
}
void h(int n)
{
int b[n]; // b may remain allocated
longjmp(buf, 2); // might cause a memory leak for h's b and g's a
}
```
| (since C99) |
### Parameters
| | | |
| --- | --- | --- |
| env | - | variable referring to the execution state of the program saved by `[setjmp](setjmp "c/program/setjmp")` |
| status | - | the value to return from `[setjmp](setjmp "c/program/setjmp")`. If it is equal to `0`, `1` is used instead |
### Return value
(none).
### Notes
`longjmp` is intended for handling unexpected error conditions where the function cannot return meaningfully. This is similar to exception handling in other programming languages.
### Example
```
#include <stdio.h>
#include <setjmp.h>
#include <stdnoreturn.h>
jmp_buf my_jump_buffer;
noreturn void foo(int count)
{
printf("foo(%d) called\n", count);
longjmp(my_jump_buffer, count+1); // will return count+1 out of setjmp
}
int main(void)
{
volatile int count = 0; // modified local vars in setjmp scope must be volatile
if (setjmp(my_jump_buffer) != 5) // compare against constant in an if
foo(++count);
}
```
Output:
```
foo(1) called
foo(2) called
foo(3) called
foo(4) called
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.13.2.1 The longjmp macro (p: 191-192)
* C11 standard (ISO/IEC 9899:2011):
+ 7.13.2.1 The longjmp macro (p: 263-264)
* C99 standard (ISO/IEC 9899:1999):
+ 7.13.2.1 The longjmp macro (p: 244-245)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.6.2.1 The longjmp function
### See also
| | |
| --- | --- |
| [setjmp](setjmp "c/program/setjmp") | saves the context (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/longjmp "cpp/utility/program/longjmp") for `longjmp` |
c at_quick_exit at\_quick\_exit
===============
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
int at_quick_exit( void (*func)(void) );
```
| | (since C11) |
Registers the function pointed to by `func` to be called on quick program termination (via `[quick\_exit](quick_exit "c/program/quick exit")`).
Calling the function from several threads does not induce a data race. The implementation shall support the registration of at least `32` functions.
### Parameters
| | | |
| --- | --- | --- |
| func | - | pointer to a function to be called on quick program termination |
### Return value
`0` if the registration succeeds, nonzero value otherwise.
### Example
```
#include <stdlib.h>
#include <stdio.h>
void f1(void)
{
puts("pushed first");
fflush(stdout);
}
void f2(void)
{
puts("pushed second");
}
int main(void)
{
at_quick_exit(f1);
at_quick_exit(f2);
quick_exit(0);
}
```
Output:
```
pushed second
pushed first
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.4.3 The at\_quick\_exit function (p: 255)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.4.3 The at\_quick\_exit function (p: 351)
### See also
| | |
| --- | --- |
| [atexit](atexit "c/program/atexit") | registers a function to be called on `[exit()](exit "c/program/exit")` invocation (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/at_quick_exit "cpp/utility/program/at quick exit") for `at_quick_exit` |
c EXIT_SUCCESS, EXIT_FAILURE EXIT\_SUCCESS, EXIT\_FAILURE
============================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
#define EXIT_SUCCESS /*implementation defined*/
```
| | |
|
```
#define EXIT_FAILURE /*implementation defined*/
```
| | |
The `EXIT_SUCCESS` and `EXIT_FAILURE` macros expand into integral expressions that can be used as arguments to the `[exit](exit "c/program/exit")` function (and, therefore, as the values to return from the [main function](../language/main_function "c/language/main function")), and indicate program execution status.
| Constant | Explanation |
| --- | --- |
| `EXIT_SUCCESS` | successful execution of a program |
| `EXIT_FAILURE` | unsuccessful execution of a program |
### Notes
Both `EXIT_SUCCESS` and the value zero indicate successful program execution status (see `[exit](exit "c/program/exit")`), although it is not required that `EXIT_SUCCESS` equals zero.
### Example
```
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("data.txt","r");
if (fp == NULL)
{
fprintf(stderr, "fopen() failed in file %s at line # %d", __FILE__,__LINE__);
exit(EXIT_FAILURE);
}
/* Normal processing continues here. */
fclose(fp);
printf("Normal Return\n");
return EXIT_SUCCESS;
}
```
Output:
```
fopen() failed in file main.cpp at line # 9
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22/3 General utilities <stdlib.h> (p: 248)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22/3 General utilities <stdlib.h> (p: 340)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20/3 General utilities <stdlib.h> (p: 306)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10 General utilities <stdlib.h>
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/EXIT_status "cpp/utility/program/EXIT status") for `EXIT_SUCCESS, EXIT_FAILURE` |
c atexit atexit
======
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
int atexit( void (*func)(void) );
```
| | |
Registers the function pointed to by `func` to be called on normal program termination (via `[exit()](exit "c/program/exit")` or returning from `main()`). The functions will be called in reverse order they were registered, i.e. the function registered last will be executed first.
The same function may be registered more than once.
`atexit` is thread-safe: calling the function from several threads does not induce a data race.
The implementation is guaranteed to support the registration of at least `32` functions. The exact limit is implementation-defined.
### Parameters
| | | |
| --- | --- | --- |
| func | - | pointer to a function to be called on normal program termination |
### Return value
`0` if the registration succeeds, nonzero value otherwise.
### Example
```
#include <stdlib.h>
#include <stdio.h>
void f1(void)
{
puts("f1");
}
void f2(void)
{
puts("f2");
}
int main(void)
{
if ( ! atexit(f1) && ! atexit(f2) && ! atexit(f2) )
return EXIT_SUCCESS ;
// atexit registration failed
return EXIT_FAILURE ;
} // <- if registration was successful calls f2, f2, f1
```
Output:
```
f2
f2
f1
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.4.2 The atexit function (p: 255)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.4.2 The atexit function (p: 350)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.4.2 The atexit function (p: 315)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.4.2 The atexit function
### See also
| | |
| --- | --- |
| [at\_quick\_exit](at_quick_exit "c/program/at quick exit")
(C11) | registers a function to be called on [`quick_exit`](quick_exit "c/program/quick exit") invocation (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/atexit "cpp/utility/program/atexit") for `atexit` |
c sig_atomic_t sig\_atomic\_t
==============
| Defined in header `<signal.h>` | | |
| --- | --- | --- |
|
```
typedef /* unspecified */ sig_atomic_t;
```
| | |
An integer type which can be accessed as an atomic entity even in the presence of asynchronous interrupts made by signals.
### Example
```
#include <signal.h>
#include <stdio.h>
volatile sig_atomic_t gSignalStatus = 0;
void signal_handler(int status)
{
gSignalStatus = status;
}
int main(void)
{
/* Install a signal handler. */
signal(SIGINT, signal_handler);
printf("SignalValue: %d\n", gSignalStatus);
printf("Sending signal: %d\n", SIGINT);
raise(SIGINT);
printf("SignalValue: %d\n", gSignalStatus);
}
```
Possible output:
```
SignalValue: 0
Sending signal: 2
SignalValue: 2
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.14/2 Signal handling <signal.h> (p: 194-195)
* C11 standard (ISO/IEC 9899:2011):
+ 7.14/2 Signal handling <signal.h> (p: 265)
* C99 standard (ISO/IEC 9899:1999):
+ 7.14/2 Signal handling <signal.h> (p: 246)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.7 SIGNAL HANDLING <signal.h>
### See also
| | |
| --- | --- |
| [signal](signal "c/program/signal") | sets a signal handler for particular signal (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/sig_atomic_t "cpp/utility/program/sig atomic t") for `sig_atomic_t` |
c raise raise
=====
| Defined in header `<signal.h>` | | |
| --- | --- | --- |
|
```
int raise( int sig );
```
| | |
Sends signal sig to the program. The signal handler, specified using `[signal()](signal "c/program/signal")`, is invoked.
If the user-defined signal handling strategy is not set using `[signal()](signal "c/program/signal")` yet, it is implementation-defined whether the signal will be ignored or default handler will be invoked.
### Parameters
| | | | | |
| --- | --- | --- | --- | --- |
| sig | - | the signal to be sent. It can be an implementation-defined value or one of the following values:
| | |
| --- | --- |
| [SIGABRTSIGFPESIGILLSIGINTSIGSEGVSIGTERM](sig_types "c/program/SIG types") | defines signal types (macro constant) |
|
### Return value
`0` upon success, non-zero value on failure.
### Example
```
#include <signal.h>
#include <stdio.h>
void signal_handler(int signal)
{
printf("Received signal %d\n", signal);
}
int main(void)
{
// Install a signal handler.
signal(SIGTERM, signal_handler);
printf("Sending signal %d\n", SIGTERM);
raise(SIGTERM);
printf("Exit main()\n");
}
```
Output:
```
Sending signal 15
Received signal 15
Exit main()
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.14.2.1 The raise function (p: 194-195)
* C11 standard (ISO/IEC 9899:2011):
+ 7.14.2.1 The raise function (p: 267)
* C99 standard (ISO/IEC 9899:1999):
+ 7.14.2.1 The raise function (p: 248)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.7.2.1 The raise function
### See also
| | |
| --- | --- |
| [signal](signal "c/program/signal") | sets a signal handler for particular signal (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/raise "cpp/utility/program/raise") for `raise` |
c unreachable unreachable
===========
| Defined in header `<stddef.h>` | | |
| --- | --- | --- |
|
```
#define unreachable() /* see below */
```
| | (since C23) |
The function-like macro `unreachable` expands to a `void` expression. Executing `unreachable()` results in [undefined behavior](../language/behavior "c/language/behavior").
An implementation may use this to optimize impossible code branches away (typically, in optimized builds) or to trap them to prevent further execution (typically, in debug builds).
### Possible implementation
| |
| --- |
|
```
// Uses compiler specific extensions if possible.
#ifdef __GNUC__ // GCC, Clang, ICC
#define unreachable() (__builtin_unreachable())
#elifdef _MSC_VER // MSVC
#define unreachable() (__assume(false))
#else
// Even if no extension is used, undefined behavior is still raised by
// the empty function body and the noreturn attribute.
// The external definition of unreachable_impl must be emitted in a separated TU
// due to the rule for inline functions in C.
[[noreturn]] inline void unreachable_impl() {}
#define unreachable() (unreachable_impl())
#endif
```
|
### Example
```
#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
struct Color { uint8_t r, g, b, a; };
struct ColorSpan { struct Color* data; size_t size; };
// Assume that only restricted set of texture caps is supported.
struct ColorSpan allocate_texture(size_t xy)
{
switch (xy) {
case 128: [[fallthrough]];
case 256: [[fallthrough]];
case 512:
{
/* ... */
struct ColorSpan result = {
.data = malloc(xy * xy * sizeof(struct Color)),
.size = xy * xy
};
if (!result.data)
result.size = 0;
return result;
}
default:
unreachable();
}
}
int main(void)
{
struct ColorSpan tex = allocate_texture(128); // OK
assert(tex.size == 128 * 128);
struct ColorSpan badtex = allocate_texture(32); // Undefined behavior
free(badtex.data);
free(tex.data);
}
```
Possible output:
```
Segmentation fault
```
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/unreachable "cpp/utility/unreachable") for `unreachable` |
### External Links
* [GCC docs: `__builtin_unreachable`](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-_005f_005fbuiltin_005funreachable)
* [Clang docs: `__builtin_unreachable`](https://clang.llvm.org/docs/LanguageExtensions.html#builtin-unreachable)
* [MSVC docs: `__assume`](https://docs.microsoft.com/en-us/cpp/intrinsics/assume)
c jmp_buf jmp\_buf
========
| Defined in header `<setjmp.h>` | | |
| --- | --- | --- |
|
```
typedef /* unspecified */ jmp_buf;
```
| | |
The `jmp_buf` type is an array type suitable for storing information to restore a calling environment. The stored information is sufficient to restore execution at the correct block of the program and invocation of that block. The state of floating-point status flags, or open files, or any other data is not stored in an object of type `jmp_buf`.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.13/2 Nonlocal jumps <setjmp.h> (p: 191)
* C11 standard (ISO/IEC 9899:2011):
+ 7.13/2 Nonlocal jumps <setjmp.h> (p: 262)
* C99 standard (ISO/IEC 9899:1999):
+ 7.13/2 Nonlocal jumps <setjmp.h> (p: 243)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.6 NON-LOCAL JUMPS <setjmp.h>
### See also
| | |
| --- | --- |
| [setjmp](setjmp "c/program/setjmp") | saves the context (function macro) |
| [longjmp](longjmp "c/program/longjmp") | jumps to specified location (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/jmp_buf "cpp/utility/program/jmp buf") for `jmp_buf` |
c exit exit
====
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
void exit( int exit_code );
```
| | (until C11) |
|
```
_Noreturn void exit( int exit_code );
```
| | (since C11) |
Causes normal program termination to occur.
Several cleanup steps are performed:
* functions passed to `[atexit](atexit "c/program/atexit")` are called, in reverse order of registration
* all C streams are flushed and closed
* files created by `[tmpfile](../io/tmpfile "c/io/tmpfile")` are removed
* control is returned to the host environment. If `exit_code` is zero or `[EXIT\_SUCCESS](exit_status "c/program/EXIT status")`, an implementation-defined status, indicating successful termination is returned. If `exit_code` is `[EXIT\_FAILURE](exit_status "c/program/EXIT status")`, an implementation-defined status, indicating unsuccessful termination is returned. In other cases implementation-defined status value is returned.
### Notes
The functions registered with `[at\_quick\_exit](at_quick_exit "c/program/at quick exit")` are not called.
The behavior is undefined if a program calls `exit` more than once, or if it calls `exit` and `[quick\_exit](quick_exit "c/program/quick exit")`.
The behavior is undefined if during a call to a function registered with `[atexit](atexit "c/program/atexit")`, the function exits with `[longjmp](longjmp "c/program/longjmp")`.
Returning from the [the main function](../language/main_function "c/language/main function"), either by a `return` statement or by reaching the end of the function, executes `exit()`, passing the argument of the return statement (or `0` if implicit return was used) as `exit_code`.
### Parameters
| | | |
| --- | --- | --- |
| exit\_code | - | exit status of the program |
### Return value
(none).
### Example
```
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("data.txt","r");
if (fp == NULL) {
fprintf(stderr, "error opening file data.txt in function main()\n");
exit( EXIT_FAILURE );
}
fclose(fp);
printf("Normal Return\n");
return EXIT_SUCCESS ;
}
```
Possible output:
```
error opening file data.txt in function main()
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.4.4 The exit function (p: 256)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.4.4 The exit function (p: 351-352)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.4.3 The exit function (p: 315-316)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.4.3 The exit function
### See also
| | |
| --- | --- |
| [abort](abort "c/program/abort") | causes abnormal program termination (without cleaning up) (function) |
| [atexit](atexit "c/program/atexit") | registers a function to be called on `exit()` invocation (function) |
| [quick\_exit](quick_exit "c/program/quick exit")
(C11) | causes normal program termination without completely cleaning up (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/exit "cpp/utility/program/exit") for `exit` |
| programming_docs |
c getenv, getenv_s getenv, getenv\_s
=================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
char *getenv( const char *name );
```
| (1) | |
|
```
errno_t getenv_s( size_t *restrict len, char *restrict value,
rsize_t valuesz, const char *restrict name );
```
| (2) | (since C11) |
1) Searches for an environmental variable with name `name` in the host-specified environment list and returns a pointer to the string that is associated with the matched environment variable. The set of environmental variables and methods of altering it are implementation-defined.
This function is not required to be thread-safe. Another call to getenv, as well as a call to the POSIX functions [`setenv()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/setenv.html), [`unsetenv()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/unsetenv.html), and [`putenv()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/putenv.html) may invalidate the pointer returned by a previous call or modify the string obtained from a previous call.
Modifying the string returned by `getenv` invokes undefined behavior.
2) Same as (1), except that the values of the environment variable is written to the user-provided buffer `value` (unless null) and the number of bytes written is stored in the user-provided location `*len` (unless null). If the environment variable is not set in the environment, zero is written to `*len` (unless null) and `'\0'` is written to `value[0]` (unless null). In addition, the following errors are detected at runtime and call the currently installed [constraint handler](../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `name` is a null pointer
* `valuesz` is greater than `RSIZE_MAX`
* `value` is a null pointer and `valuesz` is not zero
As with all bounds-checked functions, `getenv_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<stdlib.h>`.
### Parameters
| | | |
| --- | --- | --- |
| name | - | null-terminated character string identifying the name of the environmental variable to look for |
| len | - | pointer to a user-provided location where `getenv_s` will store the length of the environment variable |
| value | - | pointer to a user-provided character array where `getenv_s` will store the contents of the environment variable |
| valuesz | - | maximum number of characters that `getenv_s` is allowed to write to `dest` (size of the buffer) |
### Return value
1) character string identifying the value of the environmental variable or null pointer if such variable is not found.
2) zero if the environment variable was found, non-zero if it was not found or if a runtime constraint violation occurred. On any error, writes zero to `*len` (unless `len` is a null pointer). ### Notes
On POSIX systems, the [environment variables](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08) are also accessible through the global variable `environ`, declared as `extern char **environ;` in `<unistd.h>`, and through the optional third argument, `envp`, of [the main function](../language/main_function "c/language/main function").
The call to `getenv_s` with a null pointer for `value` and zero for `valuesz` is used to determine the size of the buffer required to hold the entire result.
### Example
```
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *name = "PATH";
const char *env_p = getenv(name);
if (env_p)
printf("%s = %s\n", name, env_p);
}
```
Possible output:
```
PATH = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.4.6 The getenv function (p: 256-257)
+ K.3.6.2.1 The getenv\_s function (p: 440-441)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.4.6 The getenv function (p: 352-353)
+ K.3.6.2.1 The getenv\_s function (p: 606-607)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.4.5 The getenv function (p: 317)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.4.4 The getenv function
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/getenv "cpp/utility/program/getenv") for `getenv` |
c signal signal
======
| Defined in header `<signal.h>` | | |
| --- | --- | --- |
|
```
void (*signal( int sig, void (*handler) (int))) (int);
```
| | |
Sets the error handler for signal `sig`. The signal handler can be set so that default handling will occur, signal is ignored, or a user-defined function is called.
When signal handler is set to a function and a signal occurs, it is implementation defined whether `signal(sig, [SIG\_DFL](http://en.cppreference.com/w/c/program/SIG_strategies))` will be executed immediately before the start of signal handler. Also, the implementation can prevent some implementation-defined set of signals from occurring while the signal handler runs.
### Parameters
| | | | | |
| --- | --- | --- | --- | --- |
| sig | - | the signal to set the signal handler to. It can be an implementation-defined value or one of the following values:
| | |
| --- | --- |
| [SIGABRTSIGFPESIGILLSIGINTSIGSEGVSIGTERM](sig_types "c/program/SIG types") | defines signal types (macro constant) |
|
| handler | - | the signal handler. This must be one of the following: * `[SIG\_DFL](sig_strategies "c/program/SIG strategies")` macro. The signal handler is set to default signal handler.
* `[SIG\_IGN](sig_strategies "c/program/SIG strategies")` macro. The signal is ignored.
* pointer to a function. The signature of the function must be equivalent to the following:
| | | |
| --- | --- | --- |
|
```
void fun(int sig);
```
| | |
|
### Return value
Previous signal handler on success or `[SIG\_ERR](sig_err "c/program/SIG ERR")` on failure (setting a signal handler can be disabled on some implementations).
### Signal handler
The following limitations are imposed on the user-defined function that is installed as a signal handler.
If the user defined function returns when handling `[SIGFPE](sig_types "c/program/SIG types")`, `[SIGILL](sig_types "c/program/SIG types")` or `[SIGSEGV](sig_types "c/program/SIG types")`, the behavior is undefined.
If the signal handler is called as a result of `[abort](abort "c/program/abort")` or `[raise](raise "c/program/raise")`, the behavior is undefined if the signal handler calls `[raise](raise "c/program/raise")`.
If the signal handler is called NOT as a result of `[abort](abort "c/program/abort")` or `[raise](raise "c/program/raise")` (in other words, the signal handler is *asynchronous*), the behavior is undefined if.
* the signal handler calls any function within the standard library, except
+ `[abort](abort "c/program/abort")`
+ `[\_Exit](_exit "c/program/ Exit")`
+ `[quick\_exit](quick_exit "c/program/quick exit")`
+ `signal` with the first argument being the number of the signal currently handled (async handler can re-register itself, but not other signals).
+ atomic functions from [`<stdatomic.h>`](../thread#Atomic_operations "c/thread") if the atomic arguments are lock-free
+ `[atomic\_is\_lock\_free](../atomic/atomic_is_lock_free "c/atomic/atomic is lock free")` (with any kind of atomic arguments)
* the signal handler refers to any object with static or thread-local (since C11) [storage duration](../language/storage_duration "c/language/storage duration") that is not a lock-free [atomic](../language/atomic "c/language/atomic") (since C11) other than by assigning to a static `volatile [sig\_atomic\_t](http://en.cppreference.com/w/c/program/sig_atomic_t)`.
On entry to the signal handler, the state of the floating-point environment and the values of all objects is unspecified, except for.
* objects of type `volatile [sig\_atomic\_t](http://en.cppreference.com/w/c/program/sig_atomic_t)`
* objects of lock-free atomic types (since C11)
* side effects made visible through `[atomic\_signal\_fence](../atomic/atomic_signal_fence "c/atomic/atomic signal fence")` (since C11)
On return from a signal handler, the value of any object modified by the signal handler that is not `volatile [sig\_atomic\_t](http://en.cppreference.com/w/c/program/sig_atomic_t)` or lock-free atomic(since C11) is undefined.
The behavior is undefined if `signal` is used in a multithreaded program. It is not required to be thread-safe.
### Notes
POSIX requires that `signal` is thread-safe, and [specifies a list of async-signal-safe library functions](http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04) that may be called from any signal handler.
Besides `abort` and `raise`, POSIX specifies that `kill`, `pthread_kill`, and `sigqueue` generate synchronous signals.
POSIX recommends [`sigaction`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html) instead of `signal`, due to its underspecified behavior and significant implementation variations, regarding signal delivery while a signal handler is executed.
### Example
```
#include <signal.h>
#include <stdio.h>
volatile sig_atomic_t gSignalStatus;
void signal_handler(int signal)
{
gSignalStatus = signal;
}
int main(void)
{
signal(SIGINT, signal_handler);
printf("SignalValue: %d\n", gSignalStatus);
printf("Sending signal: %d\n", SIGINT);
raise(SIGINT);
printf("SignalValue: %d\n", gSignalStatus);
}
```
Output:
```
SignalValue: 0
Sending signal: 2
SignalValue: 2
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.14.1.1 The signal function (p: 193-194)
* C11 standard (ISO/IEC 9899:2011):
+ 7.14.1.1 The signal function (p: 266-267)
* C99 standard (ISO/IEC 9899:1999):
+ 7.14.1.1 The signal function (p: 247-248)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.7.1.1 The signal function
### See also
| | |
| --- | --- |
| [raise](raise "c/program/raise") | runs the signal handler for particular signal (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program/signal "cpp/utility/program/signal") for `signal` |
c Null-terminated byte strings Null-terminated byte strings
============================
A null-terminated byte string (NTBS) is a sequence of nonzero bytes followed by a byte with value zero (the terminating null character). Each byte in a byte string encodes one character of some character set. For example, the character array `{'\x63','\x61','\x74','\0'`} is an NTBS holding the string `"cat"` in ASCII encoding.
### Functions
| |
| --- |
| Character classification |
| Defined in header `<ctype.h>` |
| [isalnum](byte/isalnum "c/string/byte/isalnum") | checks if a character is alphanumeric (function) |
| [isalpha](byte/isalpha "c/string/byte/isalpha") | checks if a character is alphabetic (function) |
| [islower](byte/islower "c/string/byte/islower") | checks if a character is lowercase (function) |
| [isupper](byte/isupper "c/string/byte/isupper") | checks if a character is an uppercase character (function) |
| [isdigit](byte/isdigit "c/string/byte/isdigit") | checks if a character is a digit (function) |
| [isxdigit](byte/isxdigit "c/string/byte/isxdigit") | checks if a character is a hexadecimal character (function) |
| [iscntrl](byte/iscntrl "c/string/byte/iscntrl") | checks if a character is a control character (function) |
| [isgraph](byte/isgraph "c/string/byte/isgraph") | checks if a character is a graphical character (function) |
| [isspace](byte/isspace "c/string/byte/isspace") | checks if a character is a space character (function) |
| [isblank](byte/isblank "c/string/byte/isblank")
(C99) | checks if a character is a blank character (function) |
| [isprint](byte/isprint "c/string/byte/isprint") | checks if a character is a printing character (function) |
| [ispunct](byte/ispunct "c/string/byte/ispunct") | checks if a character is a punctuation character (function) |
| Character manipulation |
| [tolower](byte/tolower "c/string/byte/tolower") | converts a character to lowercase (function) |
| [toupper](byte/toupper "c/string/byte/toupper") | converts a character to uppercase (function) |
Note: additional functions whose names begin with either `to` or `is`, followed by a lowercase letter, may be added to the header `ctype.h` in future and should not be defined by programs that include that header.
| ASCII values | characters | [`iscntrl`](byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](byte/isprint "c/string/byte/isprint") [`iswprint`](wide/iswprint "c/string/wide/iswprint"). | [`isspace`](byte/isspace "c/string/byte/isspace") [`iswspace`](wide/iswspace "c/string/wide/iswspace"). | [`isblank`](byte/isblank "c/string/byte/isblank") [`iswblank`](wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](byte/isgraph "c/string/byte/isgraph") [`iswgraph`](wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](byte/ispunct "c/string/byte/ispunct") [`iswpunct`](wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](byte/isalnum "c/string/byte/isalnum") [`iswalnum`](wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](byte/isalpha "c/string/byte/isalpha") [`iswalpha`](wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](byte/isupper "c/string/byte/isupper") [`iswupper`](wide/iswupper "c/string/wide/iswupper"). | [`islower`](byte/islower "c/string/byte/islower") [`iswlower`](wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](byte/isdigit "c/string/byte/isdigit") [`iswdigit`](wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| |
| --- |
| Conversions to numeric formats |
| Defined in header `<stdlib.h>` |
| [atof](byte/atof "c/string/byte/atof") | converts a byte string to a floating-point value (function) |
| [atoiatolatoll](byte/atoi "c/string/byte/atoi")
(C99) | converts a byte string to an integer value (function) |
| [strtolstrtoll](byte/strtol "c/string/byte/strtol")
(C99) | converts a byte string to an integer value (function) |
| [strtoul strtoull](byte/strtoul "c/string/byte/strtoul")
(C99) | converts a byte string to an unsigned integer value (function) |
| [strtofstrtodstrtold](byte/strtof "c/string/byte/strtof")
(C99)(C99) | converts a byte string to a floating point value (function) |
| Defined in header `<inttypes.h>` |
| [strtoimaxstrtoumax](byte/strtoimax "c/string/byte/strtoimax")
(C99)(C99) | converts a byte string to `[intmax\_t](http://en.cppreference.com/w/c/types/integer)` or `[uintmax\_t](http://en.cppreference.com/w/c/types/integer)` (function) |
| String manipulation |
| Defined in header `<string.h>` |
| [strcpystrcpy\_s](byte/strcpy "c/string/byte/strcpy")
(C11) | copies one string to another (function) |
| [strncpystrncpy\_s](byte/strncpy "c/string/byte/strncpy")
(C11) | copies a certain amount of characters from one string to another (function) |
| [strcatstrcat\_s](byte/strcat "c/string/byte/strcat")
(C11) | concatenates two strings (function) |
| [strncatstrncat\_s](byte/strncat "c/string/byte/strncat")
(C11) | concatenates a certain amount of characters of two strings (function) |
| [strxfrm](byte/strxfrm "c/string/byte/strxfrm") | transform a string so that strcmp would produce the same result as strcoll (function) |
| [strdup](byte/strdup "c/string/byte/strdup")
(C23) | allocates a copy of a string (function) |
| [strndup](byte/strndup "c/string/byte/strndup")
(C23) | allocates a copy of a string of specified size (function) |
| String examination |
| Defined in header `<string.h>` |
| [strlenstrnlen\_s](byte/strlen "c/string/byte/strlen")
(C11) | returns the length of a given string (function) |
| [strcmp](byte/strcmp "c/string/byte/strcmp") | compares two strings (function) |
| [strncmp](byte/strncmp "c/string/byte/strncmp") | compares a certain amount of characters of two strings (function) |
| [strcoll](byte/strcoll "c/string/byte/strcoll") | compares two strings in accordance to the current locale (function) |
| [strchr](byte/strchr "c/string/byte/strchr") | finds the first occurrence of a character (function) |
| [strrchr](byte/strrchr "c/string/byte/strrchr") | finds the last occurrence of a character (function) |
| [strspn](byte/strspn "c/string/byte/strspn") | returns the length of the maximum initial segment that consists of only the characters found in another byte string (function) |
| [strcspn](byte/strcspn "c/string/byte/strcspn") | returns the length of the maximum initial segment that consists of only the characters not found in another byte string (function) |
| [strpbrk](byte/strpbrk "c/string/byte/strpbrk") | finds the first location of any character in one string, in another string (function) |
| [strstr](byte/strstr "c/string/byte/strstr") | finds the first occurrence of a substring of characters (function) |
| [strtokstrtok\_s](byte/strtok "c/string/byte/strtok")
(C11) | finds the next token in a byte string (function) |
| Character array manipulation |
| Defined in header `<string.h>` |
| [memchr](byte/memchr "c/string/byte/memchr") | searches an array for the first occurrence of a character (function) |
| [memcmp](byte/memcmp "c/string/byte/memcmp") | compares two buffers (function) |
| [memsetmemset\_s](byte/memset "c/string/byte/memset")
(C11) | fills a buffer with a character (function) |
| [memcpymemcpy\_s](byte/memcpy "c/string/byte/memcpy")
(C11) | copies one buffer to another (function) |
| [memmovememmove\_s](byte/memmove "c/string/byte/memmove")
(C11) | moves one buffer to another (function) |
| [memccpy](byte/memccpy "c/string/byte/memccpy")
(C23) | copies one buffer to another, stopping after the specified delimiter (function) |
| Miscellaneous |
| Defined in header `<string.h>` |
| [strerrorstrerror\_sstrerrorlen\_s](byte/strerror "c/string/byte/strerror")
(C11)(C11) | returns a text version of a given error code (function) |
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.4 Character handling <ctype.h> (p: 200-204)
+ 7.8 Format conversion of integer types <inttypes.h> (p: 217-220)
+ 7.22 General utilities <stdlib.h> (p: 340-360)
+ 7.24 String handling <string.h> (p: 362-372)
+ 7.31.2 Character handling <ctype.h> (p: 455)
+ 7.31.5 Format conversion of integer types <inttypes.h> (p: 455)
+ 7.31.12 General utilities <stdlib.h> (p: 456)
+ 7.31.13 String handling <string.h> (p: 456)
+ K.3.6 General utilities <stdlib.h> (p: 604-613)
+ K.3.7 String handling <string.h> (p: 614-623)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4 Character handling <ctype.h> (p: 181-185)
+ 7.8 Format conversion of integer types <inttypes.h> (p: 198-201)
+ 7.20 General utilities <stdlib.h> (p: 306-324)
+ 7.21 String handling <string.h> (p: 325-334)
+ 7.26.2 Character handling <ctype.h> (p: 401)
+ 7.26.4 Format conversion of integer types <inttypes.h> (p: 401)
+ 7.26.10 General utilities <stdlib.h> (p: 402)
+ 7.26.11 String handling <string.h> (p: 402)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3 CHARACTER HANDLING <ctype.h>
+ 4.10 GENERAL UTILITIES <stdlib.h>
+ 4.11 STRING HANDLING <string.h>
+ 4.13.2 Character handling <ctype.h>
+ 4.13.7 General utilities <stdlib.h>
+ 4.13.8 String handling <string.h>
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte "cpp/string/byte") for `Null`-terminated byte strings |
| programming_docs |
c Null-terminated wide strings Null-terminated wide strings
============================
A null-terminated wide string is a sequence of valid wide characters, ending with a null-character.
### Functions
| |
| --- |
| Character classification |
| Defined in header `<wctype.h>` |
| [iswalnum](wide/iswalnum "c/string/wide/iswalnum")
(C95) | checks if a wide character is alphanumeric (function) |
| [iswalpha](wide/iswalpha "c/string/wide/iswalpha")
(C95) | checks if a wide character is alphabetic (function) |
| [iswlower](wide/iswlower "c/string/wide/iswlower")
(C95) | checks if a wide character is an lowercase character (function) |
| [iswupper](wide/iswupper "c/string/wide/iswupper")
(C95) | checks if a wide character is an uppercase character (function) |
| [iswdigit](wide/iswdigit "c/string/wide/iswdigit")
(C95) | checks if a wide character is a digit (function) |
| [iswxdigit](wide/iswxdigit "c/string/wide/iswxdigit")
(C95) | checks if a wide character is a hexadecimal character (function) |
| [iswcntrl](wide/iswcntrl "c/string/wide/iswcntrl")
(C95) | checks if a wide character is a control character (function) |
| [iswgraph](wide/iswgraph "c/string/wide/iswgraph")
(C95) | checks if a wide character is a graphical character (function) |
| [iswspace](wide/iswspace "c/string/wide/iswspace")
(C95) | checks if a wide character is a space character (function) |
| [iswblank](wide/iswblank "c/string/wide/iswblank")
(C99) | checks if a wide character is a blank character (function) |
| [iswprint](wide/iswprint "c/string/wide/iswprint")
(C95) | checks if a wide character is a printing character (function) |
| [iswpunct](wide/iswpunct "c/string/wide/iswpunct")
(C95) | checks if a wide character is a punctuation character (function) |
| [iswctype](wide/iswctype "c/string/wide/iswctype")
(C95) | classifies a wide character according to the specified LC\_CTYPE category (function) |
| [wctype](wide/wctype "c/string/wide/wctype")
(C95) | looks up a character classification category in the current C locale (function) |
| Character manipulation |
| Defined in header `<wctype.h>` |
| [towlower](wide/towlower "c/string/wide/towlower")
(C95) | converts a wide character to lowercase (function) |
| [towupper](wide/towupper "c/string/wide/towupper")
(C95) | converts a wide character to uppercase (function) |
| [towctrans](wide/towctrans "c/string/wide/towctrans")
(C95) | performs character mapping according to the specified LC\_CTYPE mapping category (function) |
| [wctrans](wide/wctrans "c/string/wide/wctrans")
(C95) | looks up a character mapping category in the current C locale (function) |
| ASCII values | characters | [`iscntrl`](byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](byte/isprint "c/string/byte/isprint") [`iswprint`](wide/iswprint "c/string/wide/iswprint"). | [`isspace`](byte/isspace "c/string/byte/isspace") [`iswspace`](wide/iswspace "c/string/wide/iswspace"). | [`isblank`](byte/isblank "c/string/byte/isblank") [`iswblank`](wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](byte/isgraph "c/string/byte/isgraph") [`iswgraph`](wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](byte/ispunct "c/string/byte/ispunct") [`iswpunct`](wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](byte/isalnum "c/string/byte/isalnum") [`iswalnum`](wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](byte/isalpha "c/string/byte/isalpha") [`iswalpha`](wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](byte/isupper "c/string/byte/isupper") [`iswupper`](wide/iswupper "c/string/wide/iswupper"). | [`islower`](byte/islower "c/string/byte/islower") [`iswlower`](wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](byte/isdigit "c/string/byte/isdigit") [`iswdigit`](wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| |
| --- |
| Conversions to numeric formats |
| Defined in header `<wchar.h>` |
| [wcstolwcstoll](wide/wcstol "c/string/wide/wcstol")
(C95)(C99) | converts a wide string to an integer value (function) |
| [wcstoulwcstoull](wide/wcstoul "c/string/wide/wcstoul")
(C95)(C99) | converts a wide string to an unsigned integer value (function) |
| [wcstofwcstodwcstold](wide/wcstof "c/string/wide/wcstof")
(C99)(C95)(C99) | converts a wide string to a floating-point value (function) |
| Defined in header `<inttypes.h>` |
| [wcstoimaxwcstoumax](wide/wcstoimax "c/string/wide/wcstoimax")
(C99)(C99) | converts a wide string to `[intmax\_t](http://en.cppreference.com/w/c/types/integer)` or `[uintmax\_t](http://en.cppreference.com/w/c/types/integer)` (function) |
| |
| --- |
| String manipulation |
| Defined in header `<wchar.h>` |
| [wcscpywcscpy\_s](wide/wcscpy "c/string/wide/wcscpy")
(C95)(C11) | copies one wide string to another (function) |
| [wcsncpywcsncpy\_s](wide/wcsncpy "c/string/wide/wcsncpy")
(C95)(C11) | copies a certain amount of wide characters from one string to another (function) |
| [wcscatwcscat\_s](wide/wcscat "c/string/wide/wcscat")
(C95)(C11) | appends a copy of one wide string to another (function) |
| [wcsncatwcsncat\_s](wide/wcsncat "c/string/wide/wcsncat")
(C95)(C11) | appends a certain amount of wide characters from one wide string to another (function) |
| [wcsxfrm](wide/wcsxfrm "c/string/wide/wcsxfrm")
(C95) | transform a wide string so that wcscmp would produce the same result as wcscoll (function) |
| String examination |
| Defined in header `<wchar.h>` |
| [wcslenwcsnlen\_s](wide/wcslen "c/string/wide/wcslen")
(C95)(C11) | returns the length of a wide string (function) |
| [wcscmp](wide/wcscmp "c/string/wide/wcscmp")
(C95) | compares two wide strings (function) |
| [wcsncmp](wide/wcsncmp "c/string/wide/wcsncmp")
(C95) | compares a certain amount of characters from two wide strings (function) |
| [wcscoll](wide/wcscoll "c/string/wide/wcscoll")
(C95) | compares two wide strings in accordance to the current locale (function) |
| [wcschr](wide/wcschr "c/string/wide/wcschr")
(C95) | finds the first occurrence of a wide character in a wide string (function) |
| [wcsrchr](wide/wcsrchr "c/string/wide/wcsrchr")
(C95) | finds the last occurrence of a wide character in a wide string (function) |
| [wcsspn](wide/wcsspn "c/string/wide/wcsspn")
(C95) | returns the length of the maximum initial segment that consists of only the wide characters found in another wide string (function) |
| [wcscspn](wide/wcscspn "c/string/wide/wcscspn")
(C95) | returns the length of the maximum initial segment that consists of only the wide chars *not* found in another wide string (function) |
| [wcspbrk](wide/wcspbrk "c/string/wide/wcspbrk")
(C95) | finds the first location of any wide character in one wide string, in another wide string (function) |
| [wcsstr](wide/wcsstr "c/string/wide/wcsstr")
(C95) | finds the first occurrence of a wide string within another wide string (function) |
| [wcstokwcstok\_s](wide/wcstok "c/string/wide/wcstok")
(C95)(C11) | finds the next token in a wide string (function) |
| |
| --- |
| Wide character array manipulation |
| Defined in header `<wchar.h>` |
| [wmemcpywmemcpy\_s](wide/wmemcpy "c/string/wide/wmemcpy")
(C95)(C11) | copies a certain amount of wide characters between two non-overlapping arrays (function) |
| [wmemmovewmemmove\_s](wide/wmemmove "c/string/wide/wmemmove")
(C95)(C11) | copies a certain amount of wide characters between two, possibly overlapping, arrays (function) |
| [wmemcmp](wide/wmemcmp "c/string/wide/wmemcmp")
(C95) | compares a certain amount of wide characters from two arrays (function) |
| [wmemchr](wide/wmemchr "c/string/wide/wmemchr")
(C95) | finds the first occurrence of a wide character in a wide character array (function) |
| [wmemset](wide/wmemset "c/string/wide/wmemset")
(C95) | copies the given wide character to every position in a wide character array (function) |
### Types
| Defined in header `<stddef.h>` |
| --- |
| Defined in header `<stdlib.h>` |
| Defined in header `<wchar.h>` |
| wchar\_t | integer type that can hold any valid wide character (typedef) |
| Defined in header `<wchar.h>` |
| Defined in header `<wctype.h>` |
| wint\_t
(C95) | integer type that can hold any valid wide character and at least one more value (typedef) |
| Defined in header `<wctype.h>` |
| wctrans\_t
(C95) | scalar type that holds locale-specific character mapping (typedef) |
| wctype\_t
(C95) | iscalar type that holds locale-specific character classification (typedef) |
### Macros
| Defined in header `<wchar.h>` |
| --- |
| Defined in header `<wctype.h>` |
| WEOF
(C95) | a non-character value of type wint\_t used to indicate errors (macro constant) |
| Defined in header `<wchar.h>` |
| Defined in header `<stdint.h>` |
| WCHAR\_MIN
(C95) | the smallest valid value of wchar\_t (macro constant) |
| WCHAR\_MAX
(C95) | the largest valid value of wchar\_t (macro constant) |
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.19 Common definitions <stddef.h> (p: 288)
+ 7.29 Extended multibyte and wide character utilities <wchar.h> (p: 402-446)
+ 7.30 Wide character classification and mapping utilities <wctype.h> (p: 447-454)
+ 7.31.16 Extended multibyte and wide character utilities <wchar.h> (p: 456)
+ 7.31.17 Wide character classification and mapping utilities <wctype.h> (p: 457)
+ K.3.3 Common definitions <stddef.h> (p: 585)
+ K.3.9 Extended multibyte and wide character utilities <wchar.h> (p: 627-651)
* C99 standard (ISO/IEC 9899:1999):
+ 7.17 Common definitions <stddef.h> (p: 254)
+ 7.24 Extended multibyte and wide character utilities <wchar.h> (p: 348-392)
+ 7.25 Wide character classification and mapping utilities <wctype.h> (p: 393-400)
+ 7.26.12 Extended multibyte and wide character utilities <wchar.h> (p: 402)
+ 7.26.13 Wide character classification and mapping utilities <wctype.h> (p: 402)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.1.5 Common definitions <stddef.h>
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide "cpp/string/wide") for `Null`-terminated wide strings |
c Null-terminated multibyte strings Null-terminated multibyte strings
=================================
A null-terminated multibyte string (NTMBS), or "multibyte string", is a sequence of nonzero bytes followed by a byte with value zero (the terminating null character).
Each character stored in the string may occupy more than one byte. The encoding used to represent characters in a multibyte character string is locale-specific: it may be UTF-8, GB18030, EUC-JP, Shift-JIS, etc. For example, the char array `{'\xe4','\xbd','\xa0','\xe5','\xa5','\xbd','\0'`} is an NTMBS holding the string `"你好"` in UTF-8 multibyte encoding: the first three bytes encode the character 你, the next three bytes encode the character 好. The same string encoded in GB18030 is the char array `{'\xc4', '\xe3', '\xba', '\xc3', '\0'`}, where each of the two characters is encoded as a two-byte sequence.
In some multibyte encodings, any given multibyte character sequence may represent different characters depending on the previous byte sequences, known as "shift sequences". Such encodings are known as state-dependent: knowledge of the current shift state is required to interpret each character. An NTMBS is only valid if it begins and ends in the initial shift state: if a shift sequence was used, the corresponding unshift sequence has to be present before the terminating null character. Examples of such encodings are BOCU-1 and [SCSU](http://www.unicode.org/reports/tr6).
A multibyte character string is layout-compatible with [null-terminated byte string](byte "c/string/byte") (NTBS), that is, can be stored, copied, and examined using the same facilities, except for calculating the number of characters. If the correct locale is in effect, I/O functions also handle multibyte strings. Multibyte strings can be converted to and from wide strings using the following locale-dependent conversion functions:
### Multibyte/wide character conversions
| Defined in header `<stdlib.h>` |
| --- |
| [mblen](multibyte/mblen "c/string/multibyte/mblen") | returns the number of bytes in the next multibyte character (function) |
| [mbtowc](multibyte/mbtowc "c/string/multibyte/mbtowc") | converts the next multibyte character to wide character (function) |
| [wctombwctomb\_s](multibyte/wctomb "c/string/multibyte/wctomb")
(C11) | converts a wide character to its multibyte representation (function) |
| [mbstowcsmbstowcs\_s](multibyte/mbstowcs "c/string/multibyte/mbstowcs")
(C11) | converts a narrow multibyte character string to wide string (function) |
| [wcstombswcstombs\_s](multibyte/wcstombs "c/string/multibyte/wcstombs")
(C11) | converts a wide string to narrow multibyte character string (function) |
| Defined in header `<wchar.h>` |
| [mbsinit](multibyte/mbsinit "c/string/multibyte/mbsinit")
(C95) | checks if the mbstate\_t object represents initial shift state (function) |
| [btowc](multibyte/btowc "c/string/multibyte/btowc")
(C95) | widens a single-byte narrow character to wide character, if possible (function) |
| [wctob](multibyte/wctob "c/string/multibyte/wctob")
(C95) | narrows a wide character to a single-byte narrow character, if possible (function) |
| [mbrlen](multibyte/mbrlen "c/string/multibyte/mbrlen")
(C95) | returns the number of bytes in the next multibyte character, given state (function) |
| [mbrtowc](multibyte/mbrtowc "c/string/multibyte/mbrtowc")
(C95) | converts the next multibyte character to wide character, given state (function) |
| [wcrtombwcrtomb\_s](multibyte/wcrtomb "c/string/multibyte/wcrtomb")
(C95)(C11) | converts a wide character to its multibyte representation, given state (function) |
| [mbsrtowcsmbsrtowcs\_s](multibyte/mbsrtowcs "c/string/multibyte/mbsrtowcs")
(C95)(C11) | converts a narrow multibyte character string to wide string, given state (function) |
| [wcsrtombswcsrtombs\_s](multibyte/wcsrtombs "c/string/multibyte/wcsrtombs")
(C95)(C11) | converts a wide string to narrow multibyte character string, given state (function) |
| Defined in header `<uchar.h>` |
| [mbrtoc8](multibyte/mbrtoc8 "c/string/multibyte/mbrtoc8")
(C23) | converts a narrow multibyte character to UTF-8 encoding (function) |
| [c8rtomb](multibyte/c8rtomb "c/string/multibyte/c8rtomb")
(C23) | converts UTF-8 string to narrow multibyte encoding (function) |
| [mbrtoc16](multibyte/mbrtoc16 "c/string/multibyte/mbrtoc16")
(C11) | generates the next 16-bit wide character from a narrow multibyte string (function) |
| [c16rtomb](multibyte/c16rtomb "c/string/multibyte/c16rtomb")
(C11) | converts a 16-bit wide character to narrow multibyte string (function) |
| [mbrtoc32](multibyte/mbrtoc32 "c/string/multibyte/mbrtoc32")
(C11) | generates the next 32-bit wide character from a narrow multibyte string (function) |
| [c32rtomb](multibyte/c32rtomb "c/string/multibyte/c32rtomb")
(C11) | converts a 32-bit wide character to narrow multibyte string (function) |
### Types
| Defined in header `<wchar.h>` |
| --- |
| [mbstate\_t](multibyte/mbstate_t "c/string/multibyte/mbstate t")
(C95) | conversion state information necessary to iterate multibyte character strings (class) |
| Defined in header `<uchar.h>` |
| char8\_t
(C23) | UTF-8 character type, an alias for `unsigned char` (typedef) |
| [char16\_t](multibyte/char16_t "c/string/multibyte/char16 t")
(C11) | 16-bit wide character type (typedef) |
| [char32\_t](multibyte/char32_t "c/string/multibyte/char32 t")
(C11) | 32-bit wide character type (typedef) |
### Macros
| Defined in header `<limits.h>` |
| --- |
| MB\_LEN\_MAX | maximum number of bytes in a multibyte character, for any supported locale (macro constant) |
| Defined in header `<stdlib.h>` |
| MB\_CUR\_MAX | maximum number of bytes in a multibyte character, in the current locale(macro variable) |
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.10 Sizes of integer types <limits.h> (p: 222)
+ 7.22 General utilities <stdlib.h> (p: 340-360)
+ 7.28 Unicode utilities <uchar.h> (p: 398-401)
+ 7.29 Extended multibyte and wide character utilities <wchar.h> (p: 402-446)
+ 7.31.12 General utilities <stdlib.h> (p: 456)
+ 7.31.16 Extended multibyte and wide character utilities <wchar.h> (p: 456)
+ K.3.6 General utilities <stdlib.h> (p: 604-614)
+ K.3.9 Extended multibyte and wide character utilities <wchar.h> (p: 627-651)
* C99 standard (ISO/IEC 9899:1999):
+ 7.10 Sizes of integer types <limits.h> (p: 203)
+ 7.20 General utilities <stdlib.h> (p: 306-324)
+ 7.24 Extended multibyte and wide character utilities <wchar.h> (p: 348-392)
+ 7.26.10 General utilities <stdlib.h> (p: 402)
+ 7.26.12 Extended multibyte and wide character utilities <wchar.h> (p: 402)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.1.4 Limits <float.h> and <limits.h>
+ 4.10 GENERAL UTILITIES <stdlib.h>
+ 4.13.7 General utilities <stdlib.h>
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte "cpp/string/multibyte") for `Null-terminated multibyte strings` |
| programming_docs |
c wcschr wcschr
======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
wchar_t* wcschr( const wchar_t* str, wchar_t ch );
```
| | (since C95) |
Finds the first occurrence of the wide character `ch` in the wide string pointed to by `str`.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated wide string to be analyzed |
| ch | - | wide character to search for |
### Return value
Pointer to the found character in `str`, or a null pointer if no such character is found.
### Example
```
#include <wchar.h>
#include <stdio.h>
#include <locale.h>
int main(void)
{
wchar_t arr[] = L"白猫 黒猫 кошки";
wchar_t *cat = wcschr(arr, L'猫');
wchar_t *dog = wcschr(arr, L'犬');
setlocale(LC_ALL, "en_US.utf8");
if(cat)
printf("The character 猫 found at position %td\n", cat-arr);
else
puts("The character 猫 not found");
if(dog)
printf("The character 犬 found at position %td\n", dog-arr);
else
puts("The character 犬 not found");
}
```
Output:
```
The character 猫 found at position 1
The character 犬 not found
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.5.1 The wcschr function (p: 435)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.5.1 The wcschr function (p: 381)
### See also
| | |
| --- | --- |
| [wcsrchr](wcsrchr "c/string/wide/wcsrchr")
(C95) | finds the last occurrence of a wide character in a wide string (function) |
| [wcspbrk](wcspbrk "c/string/wide/wcspbrk")
(C95) | finds the first location of any wide character in one wide string, in another wide string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcschr "cpp/string/wide/wcschr") for `wcschr` |
c iswctype iswctype
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswctype( wint_t wc, wctype_t desc );
```
| | (since C95) |
Classifies the wide character `wc` using the current C locale's LC\_CTYPE category identified by `desc`.
### Parameters
| | | |
| --- | --- | --- |
| wc | - | the wide character to classify |
| desc | - | the LC\_CTYPE category, obtained from a call to `[wctype](wctype "c/string/wide/wctype")` |
### Return value
Non-zero if the character `wc` has the property identified by `desc` in LC\_CTYPE facet of the current C locale, zero otherwise.
### Example
```
#include <locale.h>
#include <wchar.h>
#include <wctype.h>
#include <stdio.h>
const char* classify(wchar_t wc, const char* cat)
{
return iswctype(wc, wctype(cat)) ? "true" : "false";
}
int main(void)
{
setlocale(LC_ALL, "ja_JP.UTF-8");
puts("The character \u6c34 is...");
const char* cats[] = {"digit", "alpha", "space", "cntrl", "jkanji"};
for(int n = 0; n < 5; ++n)
printf("%s? %s\n", cats[n], classify(L'\u6c34', cats[n]));
}
```
Output:
```
The character 水 is...
digit? false
alpha? true
space? false
cntrl? false
jkanji? true
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.2.1 The iswctype function (p: 451-452)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.2.1 The iswctype function (p: 397-398)
### See also
| | |
| --- | --- |
| [wctype](wctype "c/string/wide/wctype")
(C95) | looks up a character classification category in the current C locale (function) |
c wcsstr wcsstr
======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
wchar_t* wcsstr( const wchar_t* dest, const wchar_t* src );
```
| | (since C95) |
Finds the first occurrence of the wide string `src` in the wide string pointed to by `dest`. The terminating null characters are not compared.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated wide string to examine |
| src | - | pointer to the null-terminated wide string to search for |
### Return value
Pointer to the first character of the found substring in `dest`, or a null pointer if no such substring is found. If `src` points to an empty string, `dest` is returned.
### Example
```
#include <stdio.h>
#include <locale.h>
#include <wchar.h>
int main(void)
{
setlocale(LC_ALL, "ru_RU.UTF-8");
wchar_t str[5][64] = {
L"Строка, где есть подстрока 'но'.",
L"Строка, где такой подстроки нет.",
L"Он здесь.",
L"Здесь он.",
L"Его нет."
};
for (size_t i = 0; i < 5; ++i) {
if (wcsstr(str[i], L"но")) {
wprintf(L"%ls\n", str[i]);
}
}
}
```
Output:
```
Строка, где есть подстрока 'но'.
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.5.6 The wcsstr function (p: 437)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.5.6 The wcsstr function (p: 383)
### See also
| | |
| --- | --- |
| [wcschr](wcschr "c/string/wide/wcschr")
(C95) | finds the first occurrence of a wide character in a wide string (function) |
| [wcsrchr](wcsrchr "c/string/wide/wcsrchr")
(C95) | finds the last occurrence of a wide character in a wide string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcsstr "cpp/string/wide/wcsstr") for `wcsstr` |
c wcsncat, wcsncat_s wcsncat, wcsncat\_s
===================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
wchar_t *wcsncat( wchar_t *dest, const wchar_t *src, size_t count );
```
| (since C95) (until C99) |
|
```
wchar_t *wcsncat( wchar_t *restrict dest,
const wchar_t *restrict src, size_t count );
```
| (since C99) |
|
```
errno_t wcsncat_s( wchar_t *restrict dest, rsize_t destsz,
const wchar_t *restrict src, rsize_t count );
```
| (2) | (since C11) |
1) Appends at most `count` wide characters from the wide string pointed to by `src`, stopping if the null terminator is copied, to the end of the character string pointed to by `dest`. The wide character `src[0]` replaces the null terminator at the end of `dest`. The null terminator is always appended in the end (so the maximum number of wide characters the function may write is `count+1`).
The behavior is undefined if the destination array is not large enough for the contents of both `str` and `dest` and the terminating null wide character.
The behavior is undefined if the strings overlap.
2) Same as (1), except that this function may clobber the remainder of the destination array (from the last wide character written to `destsz`) and that the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `src` or `dest` is a null pointer
* `destsz` or `count` is zero or greater than `RSIZE_MAX/sizeof(wchar_t)`
* there is no null wide character in the first `destsz` wide characters of `dest`
* truncation would occur: `count` or the length of `src`, whichever is less, exceeds the space available between the null terminator of `dest` and `destsz`.
* overlap would occur between the source and the destination strings
As with all bounds-checked functions, `wcsncat_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<wchar.h>`.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated wide string to append to |
| src | - | pointer to the null-terminated wide string to copy from |
| count | - | maximum number of wide characters to copy |
| destsz | - | the size of the destination buffer |
### Return value
1) returns a copy of `dest`
2) returns zero on success, returns non-zero on error. Also, on error, writes `L'\0'` to `dest[0]` (unless `dest` is a null pointer or `destsz` is zero or greater than `RSIZE_MAX/sizeof(wchar_t)`). ### Notes
Although truncation to fit the destination buffer is a security risk and therefore a runtime constraints violation for `wcsncat_s`, it is possible to get the truncating behavior by specifying `count` equal to the size of the destination array minus one: it will copy the first `count` wide characters and append the null terminator as always: `wcsncat_s(dst, sizeof dst/sizeof *dst, src, (sizeof dst/sizeof *dst)-wcsnlen_s(dst, sizeof dst/sizeof *dst)-1);`
### Example
```
#include <wchar.h>
#include <stdio.h>
#include <locale.h>
int main(void)
{
wchar_t str[50] = L"Земля, прощай.";
wcsncat(str, L" ", 1);
wcsncat(str, L"В добрый путь.", 8); // only append the first 8 wide chars
setlocale(LC_ALL, "en_US.utf8");
printf("%ls", str);
}
```
Possible output:
```
Земля, прощай. В добрый
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.29.4.3.2 The wcsncat function (p: 315)
+ K.3.9.2.2.2 The wcsncat\_s function (p: 466-467)
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.3.2 The wcsncat function (p: 432-433)
+ K.3.9.2.2.2 The wcsncat\_s function (p: 643-644)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.3.2 The wcsncat function (p: 378-379)
### See also
| | |
| --- | --- |
| [wcscatwcscat\_s](wcscat "c/string/wide/wcscat")
(C95)(C11) | appends a copy of one wide string to another (function) |
| [strncatstrncat\_s](../byte/strncat "c/string/byte/strncat")
(C11) | concatenates a certain amount of characters of two strings (function) |
| [wcscpywcscpy\_s](wcscpy "c/string/wide/wcscpy")
(C95)(C11) | copies one wide string to another (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcsncat "cpp/string/wide/wcsncat") for `wcsncat` |
c towupper towupper
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
wint_t towupper( wint_t wc );
```
| | (since C95) |
Converts the given wide character to uppercase, if possible.
### Parameters
| | | |
| --- | --- | --- |
| wc | - | wide character to be converted |
### Return value
Uppercase version of `wc` or unmodified `wc` if no uppercase version is listed in the current C locale.
### Notes
Only 1:1 character mapping can be performed by this function, e.g. the uppercase form of 'ß' is (with some exceptions) the two-character string "SS", which cannot be obtained by `towupper`.
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which pairs of Unicode characters are included in this mapping.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t wc = L'\u017f'; // Latin small letter Long S ('ſ')
printf("in the default locale, towupper(%#x) = %#x\n", wc, towupper(wc));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, towupper(%#x) = %#x\n", wc, towupper(wc));
}
```
Output:
```
in the default locale, towupper(0x17f) = 0x17f
in Unicode locale, towupper(0x17f) = 0x53
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.3.1.2 The towupper function (p: 453)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.3.1.2 The towupper function (p: 399)
### See also
| | |
| --- | --- |
| [towlower](towlower "c/string/wide/towlower")
(C95) | converts a wide character to lowercase (function) |
| [toupper](../byte/toupper "c/string/byte/toupper") | converts a character to uppercase (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/towupper "cpp/string/wide/towupper") for `towupper` |
c wctype wctype
======
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
wctype_t wctype( const char* str );
```
| | (since C95) |
Constructs a value of type `wctype_t` that describes a LC\_CTYPE category of wide character classification. It may be one of the standard classification categories, or a locale-specific category, such as `"jkanji"`.
### Parameters
| | | |
| --- | --- | --- |
| str | - | C string holding the name of the desired category |
The following values of `str` are supported in all C locales:
| value of `str` | effect |
| --- | --- |
| `"alnum"` | identifies the category used by `[iswalnum](iswalnum "c/string/wide/iswalnum")` |
| `"alpha"` | identifies the category used by `[iswalpha](iswalpha "c/string/wide/iswalpha")` |
| `"blank"` | identifies the category used by `[iswblank](iswblank "c/string/wide/iswblank")` (C99) |
| `"cntrl"` | identifies the category used by `[iswcntrl](iswcntrl "c/string/wide/iswcntrl")` |
| `"digit"` | identifies the category used by `[iswdigit](iswdigit "c/string/wide/iswdigit")` |
| `"graph"` | identifies the category used by `[iswgraph](iswgraph "c/string/wide/iswgraph")` |
| `"lower"` | identifies the category used by `[iswlower](iswlower "c/string/wide/iswlower")` |
| `"print"` | identifies the category used by `[iswprint](iswprint "c/string/wide/iswprint")` |
| `"space"` | identifies the category used by `[iswspace](iswspace "c/string/wide/iswspace")` |
| `"upper"` | identifies the category used by `[iswupper](iswupper "c/string/wide/iswupper")` |
| `"xdigit"` | identifies the category used by `[iswxdigit](iswxdigit "c/string/wide/iswxdigit")` |
### Return value
`wctype_t` object suitable for use with `[iswctype](iswctype "c/string/wide/iswctype")` to classify wide characters according to the named category of the current C locale or zero if `str` does not name a category supported by the current C locale.
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.2.2 The wctype function (p: 452)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.2.2 The wctype function (p: 398)
### See also
| | |
| --- | --- |
| [iswctype](iswctype "c/string/wide/iswctype")
(C95) | classifies a wide character according to the specified LC\_CTYPE category (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wctype "cpp/string/wide/wctype") for `wctype` |
c wcscpy, wcscpy_s wcscpy, wcscpy\_s
=================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
wchar_t *wcscpy( wchar_t *dest, const wchar_t *src );
```
| (since C95) (until C99) |
|
```
wchar_t *wcscpy( wchar_t *restrict dest, const wchar_t *restrict src );
```
| (since C99) |
|
```
errno_t wcscpy_s( wchar_t *restrict dest, rsize_t destsz,
const wchar_t *restrict src );
```
| (2) | (since C11) |
1) Copies the wide string pointed to by `src` (including the terminating null wide character) to wide character array pointed to by `dest`. The behavior is undefined if the `dest` array is not large enough. The behavior is undefined if the strings overlap.
2) Same as (1), except that it may clobber the rest of the destination array with unspecified values and that the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `src` or `dest` is a null pointer
* `destsz` is zero or greater than `RSIZE_MAX / sizeof(wchar_t)`
* `destsz` is less or equal `wcsnlen_s(src, destsz)`, in other words, truncation would occur
* overlap would occur between the source and the destination strings
As with all bounds-checked functions, `wcscpy_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<wchar.h>`.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the wide character array to copy to |
| src | - | pointer to the null-terminated wide string to copy from |
| destsz | - | maximum number of characters to write, typically the size of the destination buffer |
### Return value
1) returns a copy of `dest`
2) returns zero on success, returns non-zero on error. Also, on error, writes `L'\0'` to `dest[0]` (unless `dest` is a null pointer or `destsz` is zero or greater than `RMAX_SIZE / sizeof(wchar_t)`). ### Example
```
#include <wchar.h>
#include <stdio.h>
#include <locale.h>
int main(void)
{
wchar_t *src = L"犬 means dog";
// src[0] = L'狗' ; // this would be undefined behavior
wchar_t dst[wcslen(src) + 1]; // +1 to accommodate for the null terminator
wcscpy(dst, src);
dst[0] = L'狗'; // OK
setlocale(LC_ALL, "en_US.utf8");
printf("src = %ls\ndst = %ls\n", src, dst);
}
```
Output:
```
src = 犬 means dog
dst = 狗 means dog
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.1.2 The wcscpy function (p: 430)
+ K.3.9.2.1.1 The wcscpy\_s function (p: 639)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.1.2 The wcscpy function (p: 376)
### See also
| | |
| --- | --- |
| [wcsncpywcsncpy\_s](wcsncpy "c/string/wide/wcsncpy")
(C95)(C11) | copies a certain amount of wide characters from one string to another (function) |
| [wmemcpywmemcpy\_s](wmemcpy "c/string/wide/wmemcpy")
(C95)(C11) | copies a certain amount of wide characters between two non-overlapping arrays (function) |
| [strcpystrcpy\_s](../byte/strcpy "c/string/byte/strcpy")
(C11) | copies one string to another (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcscpy "cpp/string/wide/wcscpy") for `wcscpy` |
c wcstoul, wcstoull wcstoul, wcstoull
=================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
unsigned long wcstoul( const wchar_t* str, wchar_t** str_end, int base );
```
| | (since C95) (until C99) |
|
```
unsigned long wcstoul( const wchar_t * restrict str,
wchar_t ** restrict str_end, int base );
```
| | (since C99) |
|
```
unsigned long long wcstoull( const wchar_t * restrict str,
wchar_t ** restrict str_end, int base );
```
| | (since C99) |
Interprets an unsigned integer value in a wide string pointed to by `str`.
Discards any whitespace characters (as identified by calling [`iswspace`](iswspace "c/string/wide/iswspace")) until the first non-whitespace character is found, then takes as many characters as possible to form a valid *base-n* (where n=`base`) unsigned integer number representation and converts them to an integer value. The valid unsigned integer value consists of the following parts:
* (optional) plus or minus sign
* (optional) prefix (`0`) indicating octal base (applies only when the base is `8` or `0`)
* (optional) prefix (`0x` or `0X`) indicating hexadecimal base (applies only when the base is `16` or `0`)
* a sequence of digits
The set of valid values for base is `{0,2,3,...,36}.` The set of valid digits for base-`2` integers is `{0,1},` for base-`3` integers is `{0,1,2},` and so on. For bases larger than `10`, valid digits include alphabetic characters, starting from `Aa` for base-`11` integer, to `Zz` for base-`36` integer. The case of the characters is ignored.
Additional numeric formats may be accepted by the currently installed C [locale](../../locale/setlocale "c/locale/setlocale").
If the value of `base` is `0`, the numeric base is auto-detected: if the prefix is `0`, the base is octal, if the prefix is `0x` or `0X`, the base is hexadecimal, otherwise the base is decimal.
If the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by [unary minus](../../language/operator_arithmetic#Unary_arithmetic "c/language/operator arithmetic") in the result type, which applies unsigned integer wraparound rules.
The functions sets the pointer pointed to by `str_end` to point to the wide character past the last character interpreted. If `str_end` is a null pointer, it is ignored.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated wide string to be interpreted |
| str\_end | - | pointer to a pointer to a wide character. |
| base | - | *base* of the interpreted integer value |
### Return value
Integer value corresponding to the contents of `str` on success. If the converted value falls out of range of corresponding return type, range error occurs and `[ULONG\_MAX](../../types/limits "c/types/limits")` or `[ULLONG\_MAX](../../types/limits "c/types/limits")` is returned. If no conversion can be performed, `0` is returned.
### Example
```
#include <stdio.h>
#include <errno.h>
#include <wchar.h>
int main(void)
{
const wchar_t *p = L"10 200000000000000000000000000000 30 40";
printf("Parsing L'%ls':\n", p);
wchar_t *end;
for (unsigned long i = wcstoul(p, &end, 10);
p != end;
i = wcstoul(p, &end, 10))
{
printf("'%.*ls' -> ", (int)(end-p), p);
p = end;
if (errno == ERANGE){
printf("range error, got ");
errno = 0;
}
printf("%lu\n", i);
}
}
```
Output:
```
Parsing '10 200000000000000000000000000000 30 40':
'10' -> 10
' 200000000000000000000000000000' -> range error, got 18446744073709551615
' 30' -> 30
' 40' -> 40
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.1.2 The wcstol, wcstoll, wcstoul, and wcstoull functions (p: 429-430)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.1.2 The wcstol, wcstoll, wcstoul, and wcstoull functions (p: 375-376)
### See also
| | |
| --- | --- |
| [strtoul strtoull](../byte/strtoul "c/string/byte/strtoul")
(C99) | converts a byte string to an unsigned integer value (function) |
| [wcstolwcstoll](wcstol "c/string/wide/wcstol")
(C95)(C99) | converts a wide string to an integer value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcstoul "cpp/string/wide/wcstoul") for `wcstoul, wcstoull` |
| programming_docs |
c iswalnum iswalnum
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswalnum( wint_t ch );
```
| | (since C95) |
Checks if the given wide character is an alphanumeric character, i.e. either a number (`0123456789`), an uppercase letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`), a lowercase letter (`abcdefghijklmnopqrstuvwxyz`) or any alphanumeric character specific to the current locale.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is a alphanumeric character, zero otherwise.
### Notes
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are include in POSIX alnum category.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t c = L'\u13ad'; // the Cherokee letter HA ('Ꭽ')
printf("in the default locale, iswalnum(%#x) = %d\n", c, !!iswalnum(c));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, iswalnum(%#x) = %d\n", c, !!iswalnum(c));
}
```
Output:
```
in the default locale, iswalnum(0x13ad) = 0
in Unicode locale, iswalnum(0x13ad) = 1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.1.1 The iswalnum function (p: 448)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.1.1 The iswalnum function (p: 394)
### See also
| | |
| --- | --- |
| [isalnum](../byte/isalnum "c/string/byte/isalnum") | checks if a character is alphanumeric (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/iswalnum "cpp/string/wide/iswalnum") for `iswalnum` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "c/string/byte/isprint") [`iswprint`](iswprint "c/string/wide/iswprint"). | [`isspace`](../byte/isspace "c/string/byte/isspace") [`iswspace`](iswspace "c/string/wide/iswspace"). | [`isblank`](../byte/isblank "c/string/byte/isblank") [`iswblank`](iswblank "c/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "c/string/byte/isgraph") [`iswgraph`](iswgraph "c/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "c/string/byte/ispunct") [`iswpunct`](iswpunct "c/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "c/string/byte/isalnum") **`iswalnum`**. | [`isalpha`](../byte/isalpha "c/string/byte/isalpha") [`iswalpha`](iswalpha "c/string/wide/iswalpha"). | [`isupper`](../byte/isupper "c/string/byte/isupper") [`iswupper`](iswupper "c/string/wide/iswupper"). | [`islower`](../byte/islower "c/string/byte/islower") [`iswlower`](iswlower "c/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "c/string/byte/isdigit") [`iswdigit`](iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c wcscoll wcscoll
=======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
int wcscoll( const wchar_t *lhs, const wchar_t *rhs );
```
| | (since C95) |
Compares two null-terminated wide strings according to the collation order defined by the `[LC\_COLLATE](../../locale/lc_categories "c/locale/LC categories")` category of the currently installed locale.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | pointers to the null-terminated wide strings to compare |
### Return value
Negative value if `lhs` is *less than* (precedes) `rhs`.
`0` if `lhs` is *equal to* `rhs`.
Positive value if `lhs` is *greater than* (follows) `rhs`.
### Notes
Collation order is the dictionary order: the position of the letter in the national alphabet (its *equivalence class*) has higher priority than its case or variant. Within an equivalence class, lowercase characters collate before their uppercase equivalents and locale-specific order may apply to the characters with diacritics. In some locales, groups of characters compare as single *collation units*. For example, `"ch"` in Czech follows `"h"` and precedes `"i"`, and `"dzs"` in Hungarian follows `"dz"` and precedes `"g"`.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
void try_compare(const wchar_t* p1, const wchar_t* p2)
{
if(wcscoll(p1, p2) < 0)
printf("%ls before %ls\n", p1, p2);
else
printf("%ls before %ls\n", p2, p1);
}
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
printf("In the American locale: ");
try_compare(L"hrnec", L"chrt");
setlocale(LC_COLLATE, "cs_CZ.utf8");
printf("In the Czech locale: ");
try_compare(L"hrnec", L"chrt");
setlocale(LC_COLLATE, "en_US.utf8");
printf("In the American locale: ");
try_compare(L"år", L"ängel");
setlocale(LC_COLLATE, "sv_SE.utf8");
printf("In the Swedish locale: ");
try_compare(L"år", L"ängel");
}
```
Possible output:
```
In the American locale: chrt before hrnec
In the Czech locale: hrnec before chrt
In the American locale: ängel before år
In the Swedish locale: år before ängel
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.4.2 The wcscoll function (p: 433-434)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.4.2 The wcscoll function (p: 379-380)
### See also
| | |
| --- | --- |
| [strcoll](../byte/strcoll "c/string/byte/strcoll") | compares two strings in accordance to the current locale (function) |
| [wcsxfrm](wcsxfrm "c/string/wide/wcsxfrm")
(C95) | transform a wide string so that wcscmp would produce the same result as wcscoll (function) |
| [wcscmp](wcscmp "c/string/wide/wcscmp")
(C95) | compares two wide strings (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcscoll "cpp/string/wide/wcscoll") for `wcscoll` |
c iswlower iswlower
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswlower( wint_t ch );
```
| | (since C95) |
Checks if the given wide character is a lowercase letter, i.e. one of `abcdefghijklmnopqrstuvwxyz` or any lowercase letter specific to the current locale.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is an lowercase letter, zero otherwise.
### Notes
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are include in POSIX lower category.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t c = L'\u0444'; // Cyrillic small letter ef ('ф')
printf("in the default locale, iswlower(%#x) = %d\n", c, !!iswlower(c));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, iswlower(%#x) = %d\n", c, !!iswlower(c));
}
```
Output:
```
in the default locale, iswlower(0x444) = 0
in Unicode locale, iswlower(0x444) = 1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.1.7 The iswlower function (p: 450)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.1.7 The iswlower function (p: 396)
### See also
| | |
| --- | --- |
| [islower](../byte/islower "c/string/byte/islower") | checks if a character is lowercase (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/iswlower "cpp/string/wide/iswlower") for `iswlower` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "c/string/byte/isprint") [`iswprint`](iswprint "c/string/wide/iswprint"). | [`isspace`](../byte/isspace "c/string/byte/isspace") [`iswspace`](iswspace "c/string/wide/iswspace"). | [`isblank`](../byte/isblank "c/string/byte/isblank") [`iswblank`](iswblank "c/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "c/string/byte/isgraph") [`iswgraph`](iswgraph "c/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "c/string/byte/ispunct") [`iswpunct`](iswpunct "c/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "c/string/byte/isalnum") [`iswalnum`](iswalnum "c/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "c/string/byte/isalpha") [`iswalpha`](iswalpha "c/string/wide/iswalpha"). | [`isupper`](../byte/isupper "c/string/byte/isupper") [`iswupper`](iswupper "c/string/wide/iswupper"). | [`islower`](../byte/islower "c/string/byte/islower") **`iswlower`**. | [`isdigit`](../byte/isdigit "c/string/byte/isdigit") [`iswdigit`](iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c iswgraph iswgraph
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswgraph( wint_t ch );
```
| | (since C95) |
Checks if the given wide character has a graphical representation, i.e. it is either a number (`0123456789`), an uppercase letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`), a lowercase letter (`abcdefghijklmnopqrstuvwxyz`), a punctuation character(`!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`) or any graphical character specific to the current C locale.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character has a graphical representation character, zero otherwise.
### Notes
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are include in POSIX graph category.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t c = L'\u2602'; // the Unicode character Umbrella ('☂')
printf("in the default locale, iswgraph(%#x) = %d\n", c, !!iswgraph(c));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, iswgraph(%#x) = %d\n", c, !!iswgraph(c));
}
```
Output:
```
in the default locale, iswgraph(0x2602) = 0
in Unicode locale, iswgraph(0x2602) = 1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.1.6 The iswgraph function (p: 449-450)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.1.6 The iswgraph function (p: 395-396)
### See also
| | |
| --- | --- |
| [isgraph](../byte/isgraph "c/string/byte/isgraph") | checks if a character is a graphical character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/iswgraph "cpp/string/wide/iswgraph") for `iswgraph` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "c/string/byte/isprint") [`iswprint`](iswprint "c/string/wide/iswprint"). | [`isspace`](../byte/isspace "c/string/byte/isspace") [`iswspace`](iswspace "c/string/wide/iswspace"). | [`isblank`](../byte/isblank "c/string/byte/isblank") [`iswblank`](iswblank "c/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "c/string/byte/isgraph") **`iswgraph`**. | [`ispunct`](../byte/ispunct "c/string/byte/ispunct") [`iswpunct`](iswpunct "c/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "c/string/byte/isalnum") [`iswalnum`](iswalnum "c/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "c/string/byte/isalpha") [`iswalpha`](iswalpha "c/string/wide/iswalpha"). | [`isupper`](../byte/isupper "c/string/byte/isupper") [`iswupper`](iswupper "c/string/wide/iswupper"). | [`islower`](../byte/islower "c/string/byte/islower") [`iswlower`](iswlower "c/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "c/string/byte/isdigit") [`iswdigit`](iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| programming_docs |
c iswalpha iswalpha
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswalpha( wint_t ch );
```
| | (since C95) |
Checks if the given wide character is an alphabetic character, i.e. either an uppercase letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`), a lowercase letter (`abcdefghijklmnopqrstuvwxyz`) or any alphabetic character specific to the current locale.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is a alphabetic character, zero otherwise.
### Notes
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are include in POSIX alpha category.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t c = L'\u0b83'; // Tamil sign Visarga ('ஃ')
printf("in the default locale, iswalpha(%#x) = %d\n", c, !!iswalpha(c));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, iswalpha(%#x) = %d\n", c, !!iswalpha(c));
}
```
Output:
```
in the default locale, iswalpha(0xb83) = 0
in Unicode locale, iswalpha(0xb83) = 1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.1.2 The iswalpha function (p: 448-449)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.1.2 The iswalpha function (p: 394-395)
### See also
| | |
| --- | --- |
| [isalpha](../byte/isalpha "c/string/byte/isalpha") | checks if a character is alphabetic (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/iswalpha "cpp/string/wide/iswalpha") for `iswalpha` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "c/string/byte/isprint") [`iswprint`](iswprint "c/string/wide/iswprint"). | [`isspace`](../byte/isspace "c/string/byte/isspace") [`iswspace`](iswspace "c/string/wide/iswspace"). | [`isblank`](../byte/isblank "c/string/byte/isblank") [`iswblank`](iswblank "c/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "c/string/byte/isgraph") [`iswgraph`](iswgraph "c/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "c/string/byte/ispunct") [`iswpunct`](iswpunct "c/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "c/string/byte/isalnum") [`iswalnum`](iswalnum "c/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "c/string/byte/isalpha") **`iswalpha`**. | [`isupper`](../byte/isupper "c/string/byte/isupper") [`iswupper`](iswupper "c/string/wide/iswupper"). | [`islower`](../byte/islower "c/string/byte/islower") [`iswlower`](iswlower "c/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "c/string/byte/isdigit") [`iswdigit`](iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c wmemset wmemset
=======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
wchar_t *wmemset( wchar_t *dest, wchar_t ch, size_t count );
```
| | (since C95) |
Copies the wide character `ch` into each of the first `count` wide characters of the wide character array (or integer array of compatible type) pointed to by `dest`.
If overflow occurs, the behavior is undefined.
If `count` is zero, the function does nothing.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the wide character array to fill |
| ch | - | fill wide character |
| count | - | number of wide characters to fill |
### Return value
Returns a copy of `dest`.
### Notes
This function is not locale-sensitive and pays no attention to the values of the `wchar_t` objects it writes: nulls as well as invalid wide characters are written too.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main(void)
{
wchar_t ar[10] = L"1234567890"; // no trailing null in the array
wmemset(ar, L'\U0001f34c', 5); // replaces [12345] with the 🍌 bananas
wmemset(ar+5, L'蕉', 5); // replaces [67890] with the 蕉 bananas
setlocale(LC_ALL, "en_US.utf8");
for(size_t n = 0; n < sizeof ar/sizeof *ar; ++n)
putwchar(ar[n]);
putwchar(L'\n');
}
```
Output:
```
🍌🍌🍌🍌🍌蕉蕉蕉蕉蕉
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.6.2 The wmemset function (p: 439)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.6.2 The wmemset function (p: 385)
### See also
| | |
| --- | --- |
| [memsetmemset\_s](../byte/memset "c/string/byte/memset")
(C11) | fills a buffer with a character (function) |
| [wmemcpywmemcpy\_s](wmemcpy "c/string/wide/wmemcpy")
(C95)(C11) | copies a certain amount of wide characters between two non-overlapping arrays (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wmemset "cpp/string/wide/wmemset") for `wmemset` |
c wmemcmp wmemcmp
=======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
int wmemcmp( const wchar_t *lhs, const wchar_t *rhs, size_t count );
```
| | (since C95) |
Compares the first `count` wide characters of the wide character (or compatible integer type) arrays pointed to by `lhs` and `rhs`. The comparison is done lexicographically.
The sign of the result is the sign of the difference between the values of the first pair of wide characters that differ in the arrays being compared.
If `count` is zero, the function does nothing.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | pointers to the wide character arrays to compare |
| count | - | number of wide characters to examine |
### Return value
Negative value if the value of the first differing wide character in `lhs` is less than the value of the corresponding wide character in `rhs`: `lhs` precedes `rhs` in lexicographical order.
`0` if all `count` wide characters of `lhs` and `rhs` are equal.
Positive value if the value of the first differing wide character in `lhs` is greater than the value of the corresponding wide character in `rhs`: `rhs` precedes `lhs` in lexicographical order.
### Notes
This function is not locale-sensitive and pays no attention to the values of the `wchar_t` objects it examines: nulls as well as invalid wide characters are compared too.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
void demo(const wchar_t* lhs, const wchar_t* rhs, size_t sz)
{
for(size_t n = 0; n < sz; ++n) putwchar(lhs[n]);
int rc = wmemcmp(lhs, rhs, sz);
if(rc == 0)
wprintf(L" compares equal to ");
else if(rc < 0)
wprintf(L" precedes ");
else if(rc > 0)
wprintf(L" follows ");
for(size_t n = 0; n < sz; ++n) putwchar(rhs[n]);
wprintf(L" in lexicographical order\n");
}
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
wchar_t a1[] = {L'α',L'β',L'γ'};
wchar_t a2[] = {L'α',L'β',L'δ'};
size_t sz = sizeof a1 / sizeof *a1;
demo(a1, a2, sz);
demo(a2, a1, sz);
demo(a1, a1, sz);
}
```
Output:
```
αβγ precedes αβδ in lexicographical order
αβδ follows αβγ in lexicographical order
αβγ compares equal to αβγ in lexicographical order
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.4.5 The wmemcmp function (p: 435)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.4.5 The wmemcmp function (p: 381)
### See also
| | |
| --- | --- |
| [wcscmp](wcscmp "c/string/wide/wcscmp")
(C95) | compares two wide strings (function) |
| [memcmp](../byte/memcmp "c/string/byte/memcmp") | compares two buffers (function) |
| [wcsncmp](wcsncmp "c/string/wide/wcsncmp")
(C95) | compares a certain amount of characters from two wide strings (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wmemcmp "cpp/string/wide/wmemcmp") for `wmemcmp` |
c wcsxfrm wcsxfrm
=======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
size_t wcsxfrm( wchar_t* dest, const wchar_t* src, size_t count );
```
| | (until C99) (since C95) |
|
```
size_t wcsxfrm( wchar_t* restrict dest, const wchar_t* restrict src, size_t count );
```
| | (since C99) |
Transforms the null-terminated wide string pointed to by `src` into the implementation-defined form such that comparing two transformed strings with `[wcscmp](wcscmp "c/string/wide/wcscmp")` gives the same result as comparing the original strings with `[wcscoll](wcscoll "c/string/wide/wcscoll")`, in the current C locale.
The first `count` characters of the transformed string are written to destination, including the terminating null character, and the length of the full transformed string is returned, excluding the terminating null character.
If `count` is `0`, then `dest` is allowed to be a null pointer.
### Notes
The correct length of the buffer that can receive the entire transformed string is `1+wcsxfrm([NULL](http://en.cppreference.com/w/c/types/NULL), src, 0)`.
This function is used when making multiple locale-dependent comparisons using the same wide string or set of wide strings, because it is more efficient to use `wcsxfrm` to transform all the strings just once, and subsequently compare the transformed wide strings with `[wcscmp](wcscmp "c/string/wide/wcscmp")`.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the first element of a wide null-terminated string to write the transformed string to |
| src | - | pointer to the null-terminated wide character string to transform |
| count | - | maximum number of characters to output |
### Return value
The length of the transformed wide string, not including the terminating null-character.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main(void)
{
setlocale(LC_ALL, "sv_SE.utf8");
const wchar_t *in1 = L"\u00e5r";
wchar_t out1[1+wcsxfrm(NULL, in1, 0)];
wcsxfrm(out1, in1, sizeof out1/sizeof *out1);
const wchar_t *in2 = L"\u00e4ngel";
wchar_t out2[1+wcsxfrm(NULL, in2, 0)];
wcsxfrm(out2, in2, sizeof out2/sizeof *out2);
printf("In the Swedish locale: ");
if(wcscmp(out1, out2) < 0)
printf("%ls before %ls\n", in1, in2);
else
printf("%ls before %ls\n", in2, in1);
printf("In lexicographical comparison: ");
if(wcscmp(in1, in2) < 0)
printf("%ls before %ls\n", in1, in2);
else
printf("%ls before %ls\n", in2, in1);
}
```
Output:
```
In the Swedish locale: år before ängel
In lexicographical comparison: ängel before år
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.4.4 The wcsxfrm function (p: 434-435)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.4.4 The wcsxfrm function (p: 380-381)
### See also
| | |
| --- | --- |
| [strcoll](../byte/strcoll "c/string/byte/strcoll") | compares two strings in accordance to the current locale (function) |
| [wcscoll](wcscoll "c/string/wide/wcscoll")
(C95) | compares two wide strings in accordance to the current locale (function) |
| [wcscmp](wcscmp "c/string/wide/wcscmp")
(C95) | compares two wide strings (function) |
| [strxfrm](../byte/strxfrm "c/string/byte/strxfrm") | transform a string so that strcmp would produce the same result as strcoll (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcsxfrm "cpp/string/wide/wcsxfrm") for `wcsxfrm` |
c iswprint iswprint
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswprint( wint_t ch );
```
| | (since C95) |
Checks if the given wide character can be printed, i.e. it is either a number (`0123456789`), an uppercase letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`), a lowercase letter (`abcdefghijklmnopqrstuvwxyz`), a punctuation character(`!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`), space or any printable character specific to the current C locale.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character can be printed, zero otherwise.
### Notes
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are include in POSIX print category.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t c = L'\u2002'; // Unicode character 'EN SPACE'
printf("in the default locale, iswprint(%#x) = %d\n", c, !!iswprint(c));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, iswprint(%#x) = %d\n", c, !!iswprint(c));
wchar_t c2 = L'\x82'; // break permitted
printf("in Unicode locale, iswprint(%#x) = %d\n", c2, !!iswprint(c2));
}
```
Output:
```
in the default locale, iswprint(0x2002) = 0
in Unicode locale, iswprint(0x2002) = 1
in Unicode locale, iswprint(0x82) = 0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.1.8 The iswprint function (p: 450)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.1.8 The iswprint function (p: 396)
### See also
| | |
| --- | --- |
| [isprint](../byte/isprint "c/string/byte/isprint") | checks if a character is a printing character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/iswprint "cpp/string/wide/iswprint") for `iswprint` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "c/string/byte/isprint") **`iswprint`**. | [`isspace`](../byte/isspace "c/string/byte/isspace") [`iswspace`](iswspace "c/string/wide/iswspace"). | [`isblank`](../byte/isblank "c/string/byte/isblank") [`iswblank`](iswblank "c/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "c/string/byte/isgraph") [`iswgraph`](iswgraph "c/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "c/string/byte/ispunct") [`iswpunct`](iswpunct "c/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "c/string/byte/isalnum") [`iswalnum`](iswalnum "c/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "c/string/byte/isalpha") [`iswalpha`](iswalpha "c/string/wide/iswalpha"). | [`isupper`](../byte/isupper "c/string/byte/isupper") [`iswupper`](iswupper "c/string/wide/iswupper"). | [`islower`](../byte/islower "c/string/byte/islower") [`iswlower`](iswlower "c/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "c/string/byte/isdigit") [`iswdigit`](iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| programming_docs |
c wcspbrk wcspbrk
=======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
wchar_t* wcspbrk( const wchar_t* dest, const wchar_t* str );
```
| | (since C95) |
Finds the first character in wide string pointed to by `dest`, that is also in wide string pointed to by `str`.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated wide string to be analyzed |
| src | - | pointer to the null-terminated wide string that contains the characters to search for |
### Return value
Pointer to the first character in `dest`, that is also in `str`, or a null pointer if no such character exists.
### Notes
The name stands for "wide character string pointer break", because it returns a pointer to the first of the separator ("break") characters.
### Example
```
#include <stdio.h>
#include <wchar.h>
int main(void)
{
const wchar_t* str = L"Hello world, friend of mine!";
const wchar_t* sep = L" ,!";
unsigned int cnt = 0;
do {
str = wcspbrk(str, sep); // find separator
if (str) str += wcsspn(str, sep); // skip separator
++cnt; // increment word count
} while (str && *str);
wprintf(L"There are %u words.\n", cnt);
}
```
Output:
```
There are 5 words.
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.5.3 The wcspbrk function (p: 436)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.5.3 The wcspbrk function (p: 382)
### See also
| | |
| --- | --- |
| [wcscspn](wcscspn "c/string/wide/wcscspn")
(C95) | returns the length of the maximum initial segment that consists of only the wide chars *not* found in another wide string (function) |
| [wcschr](wcschr "c/string/wide/wcschr")
(C95) | finds the first occurrence of a wide character in a wide string (function) |
| [strpbrk](../byte/strpbrk "c/string/byte/strpbrk") | finds the first location of any character in one string, in another string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcspbrk "cpp/string/wide/wcspbrk") for `wcspbrk` |
c wcsncmp wcsncmp
=======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
int wcsncmp( const wchar_t* lhs, const wchar_t* rhs, size_t count );
```
| | (since C95) |
Compares at most `count` wide characters of two null-terminated wide strings. The comparison is done lexicographically.
The sign of the result is the sign of the difference between the values of the first pair of wide characters that differ in the strings being compared.
The behavior is undefined if `lhs` or `rhs` are not pointers to null-terminated strings.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | pointers to the null-terminated wide strings to compare |
| count | - | maximum number of characters to compare |
### Return value
Negative value if `lhs` appears before `rhs` in lexicographical order.
Zero if `lhs` and `rhs` compare equal.
Positive value if `lhs` appears after `rhs` in lexicographical order.
### Notes
This function is not locale-sensitive, unlike `[wcscoll](wcscoll "c/string/wide/wcscoll")` and `[wcsxfrm](wcsxfrm "c/string/wide/wcsxfrm")`.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
void demo(const wchar_t *lhs, const wchar_t *rhs, int sz)
{
int rc = wcsncmp(lhs, rhs, sz);
if(rc == 0)
printf("First %d characters of [%ls] equal [%ls]\n", sz, lhs, rhs);
else if(rc < 0)
printf("First %d characters of [%ls] precede [%ls]\n", sz, lhs, rhs);
else if(rc > 0)
printf("First %d characters of [%ls] follow [%ls]\n", sz, lhs, rhs);
}
int main(void)
{
const wchar_t *str1 = L"안녕하세요";
const wchar_t *str2 = L"안녕히 가십시오";
setlocale(LC_ALL, "en_US.utf8");
demo(str1, str2, 5);
demo(str2, str1, 8);
demo(str1, str2, 2);
}
```
Output:
```
First 5 characters of [안녕하세요] precede [안녕히 가십시오]
First 8 characters of [안녕히 가십시오] follow [안녕하세요]
First 2 characters of [안녕하세요] equal [안녕히 가십시오]
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.4.3 The wcsncmp function (p: 434)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.4.3 The wcsncmp function (p: 380)
### See also
| | |
| --- | --- |
| [wcscmp](wcscmp "c/string/wide/wcscmp")
(C95) | compares two wide strings (function) |
| [wmemcmp](wmemcmp "c/string/wide/wmemcmp")
(C95) | compares a certain amount of wide characters from two arrays (function) |
| [wcscoll](wcscoll "c/string/wide/wcscoll")
(C95) | compares two wide strings in accordance to the current locale (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcsncmp "cpp/string/wide/wcsncmp") for `wcsncmp` |
c iswblank iswblank
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswblank( wint_t ch );
```
| | (since C99) |
Checks if the given wide character is classified as blank character (that is, a whitespace character used to separate words in a sentence) by the current C locale. In the default C locale, only space (`0x20`) and horizontal tab (`0x09`) are blank characters.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is a blank character, zero otherwise.
### Notes
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) defines POSIX blank characters as Unicode characters U+0009, U+0020, U+1680, U+180E, U+2000..U+2006, U+2008, U+200A, U+205F, and U+3000.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t c = L'\u3000'; // Ideographic space (' ')
printf("in the default locale, iswblank(%#x) = %d\n", c, !!iswblank(c));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, iswblank(%#x) = %d\n", c, !!iswblank(c));
}
```
Output:
```
in the default locale, iswblank(0x3000) = 0
in Unicode locale, iswblank(0x3000) = 1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.1.3 The iswblank function (p: 449)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.1.3 The iswblank function (p: 395)
### See also
| | |
| --- | --- |
| [isblank](../byte/isblank "c/string/byte/isblank")
(C99) | checks if a character is a blank character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/iswblank "cpp/string/wide/iswblank") for `iswblank` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "c/string/byte/isprint") [`iswprint`](iswprint "c/string/wide/iswprint"). | [`isspace`](../byte/isspace "c/string/byte/isspace") [`iswspace`](iswspace "c/string/wide/iswspace"). | [`isblank`](../byte/isblank "c/string/byte/isblank") **`iswblank`**. | [`isgraph`](../byte/isgraph "c/string/byte/isgraph") [`iswgraph`](iswgraph "c/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "c/string/byte/ispunct") [`iswpunct`](iswpunct "c/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "c/string/byte/isalnum") [`iswalnum`](iswalnum "c/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "c/string/byte/isalpha") [`iswalpha`](iswalpha "c/string/wide/iswalpha"). | [`isupper`](../byte/isupper "c/string/byte/isupper") [`iswupper`](iswupper "c/string/wide/iswupper"). | [`islower`](../byte/islower "c/string/byte/islower") [`iswlower`](iswlower "c/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "c/string/byte/isdigit") [`iswdigit`](iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c wctrans wctrans
=======
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
wctrans_t wctrans( const char* str );
```
| | (since C95) |
Constructs a value of type `wctrans_t` that describes a LC\_CTYPE category of wide character mapping. It may be one of the standard mappings, or a locale-specific mapping, such as `"tojhira"` or `"tojkata"`.
### Parameters
| | | | | | | | | |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| str | - | C string holding the name of the desired mapping. The following values of `str` are supported in all C locales:
| Value of `str` | Effect |
| --- | --- |
| `"toupper"` | identifies the mapping used by `[towupper](towupper "c/string/wide/towupper")` |
| `"tolower"` | identifies the mapping used by `[towlower](towlower "c/string/wide/towlower")` |
|
### Return value
`wctrans_t` object suitable for use with `[towctrans](towctrans "c/string/wide/towctrans")` to map wide characters according to the named mapping of the current C locale or zero if `str` does not name a mapping supported by the current C locale.
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.3.2.2 The wctrans function (p: 454)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.3.2,2 The wctrans function (p: 400)
### See also
| | |
| --- | --- |
| [towctrans](towctrans "c/string/wide/towctrans")
(C95) | performs character mapping according to the specified LC\_CTYPE mapping category (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wctrans "cpp/string/wide/wctrans") for `wctrans` |
c iswdigit iswdigit
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswdigit( wint_t ch );
```
| | (since C95) |
Checks if the given wide character corresponds (if narrowed) to one of the ten decimal digit characters 0123456789.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is an numeric character, zero otherwise.
### Notes
`iswdigit` and `[iswxdigit](iswxdigit "c/string/wide/iswxdigit")` are the only standard wide character classification functions that are not affected by the currently installed C locale.
### Example
Some locales offer additional character classes that detect non-ASCII digits.
```
#include <stdio.h>
#include <wctype.h>
#include <wchar.h>
#include <locale.h>
void test(wchar_t a3, wchar_t u3, wchar_t j3)
{
printf(" '%lc' '%lc' '%lc'\n", a3, u3, j3);
printf("iswdigit %d %d %d\n",
!!iswdigit(a3), !!iswdigit(u3), !!iswdigit(j3));
printf("jdigit: %d %d %d\n", !!iswctype(a3, wctype("jdigit")),
!!iswctype(u3, wctype("jdigit")),
!!iswctype(j3, wctype("jdigit")));
}
int main(void)
{
wchar_t a3 = L'3'; // the ASCII digit 3
wchar_t u3 = L'三'; // the CJK numeral 3
wchar_t j3 = L'3'; // the fullwidth digit 3
setlocale(LC_ALL, "en_US.utf8");
puts("In American locale:");
test(a3, u3, j3);
setlocale(LC_ALL, "ja_JP.utf8");
puts("\nIn Japanese locale:");
test(a3, u3, j3);
}
```
Output:
```
In American locale:
'3' '三' '3'
iswdigit 1 0 0
jdigit: 0 0 0
In Japanese locale:
'3' '三' '3'
iswdigit 1 0 0
jdigit: 0 0 1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.1.5 The iswdigit function (p: 449)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.1.5 The iswdigit function (p: 395)
### See also
| | |
| --- | --- |
| [isdigit](../byte/isdigit "c/string/byte/isdigit") | checks if a character is a digit (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/iswdigit "cpp/string/wide/iswdigit") for `iswdigit` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "c/string/byte/isprint") [`iswprint`](iswprint "c/string/wide/iswprint"). | [`isspace`](../byte/isspace "c/string/byte/isspace") [`iswspace`](iswspace "c/string/wide/iswspace"). | [`isblank`](../byte/isblank "c/string/byte/isblank") [`iswblank`](iswblank "c/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "c/string/byte/isgraph") [`iswgraph`](iswgraph "c/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "c/string/byte/ispunct") [`iswpunct`](iswpunct "c/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "c/string/byte/isalnum") [`iswalnum`](iswalnum "c/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "c/string/byte/isalpha") [`iswalpha`](iswalpha "c/string/wide/iswalpha"). | [`isupper`](../byte/isupper "c/string/byte/isupper") [`iswupper`](iswupper "c/string/wide/iswupper"). | [`islower`](../byte/islower "c/string/byte/islower") [`iswlower`](iswlower "c/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "c/string/byte/isdigit") **`iswdigit`**. | [`isxdigit`](../byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c wcsspn wcsspn
======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
size_t wcsspn( const wchar_t* dest, const wchar_t* src );
```
| | (since C95) |
Returns the length of the maximum initial segment of the wide string pointed to by `dest`, that consists of only the characters found in wide string pointed to by `src`.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated wide string to be analyzed |
| src | - | pointer to the null-terminated wide string that contains the characters to search for |
### Return value
The length of the maximum initial segment that contains only characters from wide string pointed to by `src`.
### Example
```
#include <locale.h>
#include <wchar.h>
int main(void)
{
wchar_t dest[] = L"白猫 黑狗 甲虫";
const wchar_t src[] = L" 狗猫 白黑 ";
const size_t len = wcsspn(dest, src);
dest[len] = L'\0'; /* terminates the segment to print it out */
setlocale(LC_ALL, "en_US.utf8");
wprintf(L"The length of maximum initial segment is %td.\n"
L"The segment is \"%ls\".\n", len, dest);
}
```
Output:
```
The length of maximum initial segment is 6.
The segment is "白猫 黑狗 ".
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.5.5 The wcsspn function (p: 436)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.5.5 The wcsspn function (p: 382)
### See also
| | |
| --- | --- |
| [wcscspn](wcscspn "c/string/wide/wcscspn")
(C95) | returns the length of the maximum initial segment that consists of only the wide chars *not* found in another wide string (function) |
| [wcspbrk](wcspbrk "c/string/wide/wcspbrk")
(C95) | finds the first location of any wide character in one wide string, in another wide string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcsspn "cpp/string/wide/wcsspn") for `wcsspn` |
| programming_docs |
c iswupper iswupper
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswupper( wint_t ch );
```
| | (since C95) |
Checks if the given wide character is an uppercase letter, i.e. one of `ABCDEFGHIJKLMNOPQRSTUVWXYZ` or any uppercase letter specific to the current locale.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is an uppercase letter, zero otherwise.
### Notes
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are include in POSIX upper category.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t c = L'\u053d'; // Armenian capital letter xeh ('Խ')
printf("in the default locale, iswupper(%#x) = %d\n", c, !!iswupper(c));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, iswupper(%#x) = %d\n", c, !!iswupper(c));
}
```
Output:
```
in the default locale, iswupper(0x53d) = 0
in Unicode locale, iswupper(0x53d) = 1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.1.11 The iswupper function (p: 451)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.1.11 The iswupper function (p: 397)
### See also
| | |
| --- | --- |
| [isupper](../byte/isupper "c/string/byte/isupper") | checks if a character is an uppercase character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/iswupper "cpp/string/wide/iswupper") for `iswupper` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "c/string/byte/isprint") [`iswprint`](iswprint "c/string/wide/iswprint"). | [`isspace`](../byte/isspace "c/string/byte/isspace") [`iswspace`](iswspace "c/string/wide/iswspace"). | [`isblank`](../byte/isblank "c/string/byte/isblank") [`iswblank`](iswblank "c/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "c/string/byte/isgraph") [`iswgraph`](iswgraph "c/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "c/string/byte/ispunct") [`iswpunct`](iswpunct "c/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "c/string/byte/isalnum") [`iswalnum`](iswalnum "c/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "c/string/byte/isalpha") [`iswalpha`](iswalpha "c/string/wide/iswalpha"). | [`isupper`](../byte/isupper "c/string/byte/isupper") **`iswupper`**. | [`islower`](../byte/islower "c/string/byte/islower") [`iswlower`](iswlower "c/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "c/string/byte/isdigit") [`iswdigit`](iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c wcscspn wcscspn
=======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
size_t wcscspn( const wchar_t* dest, const wchar_t* src );
```
| | (since C95) |
Returns the length of the maximum initial segment of the wide string pointed to by `dest`, that consists of only the characters *not* found in wide string pointed to by `src`.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated wide string to be analyzed |
| src | - | pointer to the null-terminated wide string that contains the characters to search for |
### Return value
The length of the maximum initial segment that contains only characters not found in the character string pointed to by `src`.
### Example
```
#include <locale.h>
#include <wchar.h>
int main(void)
{
wchar_t dest[] = L"白猫 黑狗 甲虫";
/* └───┐ */
const wchar_t *src = L"甲虫,黑狗";
const size_t len = wcscspn(dest, src);
dest[len] = L'\0'; /* terminates the segment to print it out */
setlocale(LC_ALL, "en_US.utf8");
wprintf(L"The length of maximum initial segment is %td.\n"
L"The segment is \"%ls\".\n", len, dest);
}
```
Output:
```
The length of maximum initial segment is 3.
The segment is "白猫 ".
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.5.2 The wcscspn function (p: 435-436)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.5.2 The wcscspn function (p: 381-382)
### See also
| | |
| --- | --- |
| [wcsspn](wcsspn "c/string/wide/wcsspn")
(C95) | returns the length of the maximum initial segment that consists of only the wide characters found in another wide string (function) |
| [wcspbrk](wcspbrk "c/string/wide/wcspbrk")
(C95) | finds the first location of any wide character in one wide string, in another wide string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcscspn "cpp/string/wide/wcscspn") for `wcscspn` |
c iswcntrl iswcntrl
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswcntrl( wint_t ch );
```
| | (since C95) |
Checks if the given wide character is a control character, i.e. codes `0x00-0x1F` and `0x7F` and any control characters specific to the current locale.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is a control character, zero otherwise.
### Notes
ISO 30112 defines POSIX control characters as Unicode characters U+0000..U+001F, U+007F..U+009F, U+2028, and U+2029 (Unicode classes Cc, Zl, and Zp).
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t c = L'\u2028'; // the Unicode character "line separator"
printf("in the default locale, iswcntrl(%#x) = %d\n", c, !!iswcntrl(c));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, iswcntrl(%#x) = %d\n", c, !!iswcntrl(c));
}
```
Output:
```
in the default locale, iswcntrl(0x2028) = 0
in Unicode locale, iswcntrl(0x2028) = 1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.1.4 The iswcntrl function (p: 449)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.1.4 The iswcntrl function (p: 395)
### See also
| | |
| --- | --- |
| [iscntrl](../byte/iscntrl "c/string/byte/iscntrl") | checks if a character is a control character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/iswcntrl "cpp/string/wide/iswcntrl") for `iswcntrl` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "c/string/byte/iscntrl") **`iswcntrl`**. | [`isprint`](../byte/isprint "c/string/byte/isprint") [`iswprint`](iswprint "c/string/wide/iswprint"). | [`isspace`](../byte/isspace "c/string/byte/isspace") [`iswspace`](iswspace "c/string/wide/iswspace"). | [`isblank`](../byte/isblank "c/string/byte/isblank") [`iswblank`](iswblank "c/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "c/string/byte/isgraph") [`iswgraph`](iswgraph "c/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "c/string/byte/ispunct") [`iswpunct`](iswpunct "c/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "c/string/byte/isalnum") [`iswalnum`](iswalnum "c/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "c/string/byte/isalpha") [`iswalpha`](iswalpha "c/string/wide/iswalpha"). | [`isupper`](../byte/isupper "c/string/byte/isupper") [`iswupper`](iswupper "c/string/wide/iswupper"). | [`islower`](../byte/islower "c/string/byte/islower") [`iswlower`](iswlower "c/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "c/string/byte/isdigit") [`iswdigit`](iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c iswpunct iswpunct
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswpunct( wint_t ch );
```
| | (since C95) |
Checks if the given wide character is a punctuation character, i.e. it is one of `!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~` or any punctuation character specific to the current locale.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is a punctuation character, zero otherwise.
### Notes
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are include in POSIX punct category.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t c = L'\u2051'; // Two asterisks ('⁑')
printf("in the default locale, iswpunct(%#x) = %d\n", c, !!iswpunct(c));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, iswpunct(%#x) = %d\n", c, !!iswpunct(c));
}
```
Output:
```
in the default locale, iswpunct(0x2051) = 0
in Unicode locale, iswpunct(0x2051) = 1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.1.9 The iswpunct function (p: 450)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.1.9 The iswpunct function (p: 396)
### See also
| | |
| --- | --- |
| [ispunct](../byte/ispunct "c/string/byte/ispunct") | checks if a character is a punctuation character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/iswpunct "cpp/string/wide/iswpunct") for `iswpunct` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "c/string/byte/isprint") [`iswprint`](iswprint "c/string/wide/iswprint"). | [`isspace`](../byte/isspace "c/string/byte/isspace") [`iswspace`](iswspace "c/string/wide/iswspace"). | [`isblank`](../byte/isblank "c/string/byte/isblank") [`iswblank`](iswblank "c/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "c/string/byte/isgraph") [`iswgraph`](iswgraph "c/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "c/string/byte/ispunct") **`iswpunct`**. | [`isalnum`](../byte/isalnum "c/string/byte/isalnum") [`iswalnum`](iswalnum "c/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "c/string/byte/isalpha") [`iswalpha`](iswalpha "c/string/wide/iswalpha"). | [`isupper`](../byte/isupper "c/string/byte/isupper") [`iswupper`](iswupper "c/string/wide/iswupper"). | [`islower`](../byte/islower "c/string/byte/islower") [`iswlower`](iswlower "c/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "c/string/byte/isdigit") [`iswdigit`](iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c wcstol, wcstoll wcstol, wcstoll
===============
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
long wcstol( const wchar_t * str, wchar_t ** str_end, int base );
```
| | (since C95) (until C99) |
|
```
long wcstol( const wchar_t * restrict str, wchar_t ** restrict str_end,
int base );
```
| | (since C99) |
|
```
long long wcstoll( const wchar_t * restrict str, wchar_t ** restrict str_end,
int base );
```
| | (since C99) |
Interprets an integer value in a wide string pointed to by `str`.
Discards any whitespace characters (as identified by calling [`iswspace`](iswspace "c/string/wide/iswspace")) until the first non-whitespace character is found, then takes as many characters as possible to form a valid *base-n* (where n=`base`) integer number representation and converts them to an integer value. The valid integer value consists of the following parts:
* (optional) plus or minus sign
* (optional) prefix (`0`) indicating octal base (applies only when the base is `8` or `0`)
* (optional) prefix (`0x` or `0X`) indicating hexadecimal base (applies only when the base is `16` or `0`)
* a sequence of digits
The set of valid values for base is `{0,2,3,...,36}.` The set of valid digits for base-`2` integers is `{0,1},` for base-`3` integers is `{0,1,2},` and so on. For bases larger than `10`, valid digits include alphabetic characters, starting from `Aa` for base-`11` integer, to `Zz` for base-`36` integer. The case of the characters is ignored.
Additional numeric formats may be accepted by the currently installed C [locale](../../locale/setlocale "c/locale/setlocale").
If the value of `base` is `0`, the numeric base is auto-detected: if the prefix is `0`, the base is octal, if the prefix is `0x` or `0X`, the base is hexadecimal, otherwise the base is decimal.
If the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by [unary minus](../../language/operator_arithmetic#Unary_arithmetic "c/language/operator arithmetic") in the result type.
The functions sets the pointer pointed to by `str_end` to point to the wide character past the last character interpreted. If `str_end` is a null pointer, it is ignored.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated wide string to be interpreted |
| str\_end | - | pointer to a pointer to wide character |
| base | - | *base* of the interpreted integer value |
### Return value
Integer value corresponding to the contents of `str` on success. If the converted value falls out of range of corresponding return type, range error occurs and `[LONG\_MAX](../../types/limits "c/types/limits")`, `[LONG\_MIN](../../types/limits "c/types/limits")`, `[LLONG\_MAX](../../types/limits "c/types/limits")` or `[LLONG\_MIN](../../types/limits "c/types/limits")` is returned. If no conversion can be performed, `0` is returned.
### Example
```
#include <stdio.h>
#include <errno.h>
#include <wchar.h>
int main(void)
{
const wchar_t *p = L"10 200000000000000000000000000000 30 -40";
printf("Parsing L'%ls':\n", p);
wchar_t *end;
for (long i = wcstol(p, &end, 10);
p != end;
i = wcstol(p, &end, 10))
{
printf("'%.*ls' -> ", (int)(end-p), p);
p = end;
if (errno == ERANGE){
printf("range error, got ");
errno = 0;
}
printf("%ld\n", i);
}
}
```
Output:
```
Parsing L'10 200000000000000000000000000000 30 -40':
'10' -> 10
' 200000000000000000000000000000' -> range error, got 9223372036854775807
' 30' -> 30
' -40' -> -40
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.1.2 The wcstol, wcstoll, wcstoul, and wcstoull functions (p: 429-430)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.1.2 The wcstol, wcstoll, wcstoul, and wcstoull functions (p: 375-376)
### See also
| | |
| --- | --- |
| [strtolstrtoll](../byte/strtol "c/string/byte/strtol")
(C99) | converts a byte string to an integer value (function) |
| [wcstoulwcstoull](wcstoul "c/string/wide/wcstoul")
(C95)(C99) | converts a wide string to an unsigned integer value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcstol "cpp/string/wide/wcstol") for `wcstol, wcstoll` |
| programming_docs |
c wcscmp wcscmp
======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
int wcscmp( const wchar_t *lhs, const wchar_t *rhs );
```
| | (since C95) |
Compares two null-terminated wide strings lexicographically.
The sign of the result is the sign of the difference between the values of the first pair of wide characters that differ in the strings being compared.
The behavior is undefined if `lhs` or `rhs` are not pointers to null-terminated wide strings.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | pointers to the null-terminated wide strings to compare |
### Return value
Negative value if `lhs` appears before `rhs` in lexicographical order.
Zero if `lhs` and `rhs` compare equal.
Positive value if `lhs` appears after `rhs` in lexicographical order.
### Notes
This function is not locale-sensitive, unlike `[wcscoll](wcscoll "c/string/wide/wcscoll")`, and the order may not be meaningful when characters from different Unicode blocks are used together or when the order of code units does not match any collation order.
### Example
```
#include <wchar.h>
#include <stdio.h>
#include <locale.h>
void demo(const wchar_t* lhs, const wchar_t* rhs)
{
int rc = wcscmp(lhs, rhs);
const char *rel = rc < 0 ? "precedes" : rc > 0 ? "follows" : "equals";
setlocale(LC_ALL, "en_US.utf8");
printf("[%ls] %s [%ls]\n", lhs, rel, rhs);
}
int main(void)
{
const wchar_t* string = L"どうもありがとうございます";
demo(string, L"どうも");
demo(string, L"助かった");
demo(string + 9, L"ありがとうございます" + 6);
}
```
Possible output:
```
[どうもありがとうございます] follows [どうも]
[どうもありがとうございます] precedes [助かった]
[ざいます] equals [ざいます]
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.4.1 The wcscmp function (p: 433)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.4.1 The wcscmp function (p: 379)
### See also
| | |
| --- | --- |
| [wcsncmp](wcsncmp "c/string/wide/wcsncmp")
(C95) | compares a certain amount of characters from two wide strings (function) |
| [wmemcmp](wmemcmp "c/string/wide/wmemcmp")
(C95) | compares a certain amount of wide characters from two arrays (function) |
| [strcmp](../byte/strcmp "c/string/byte/strcmp") | compares two strings (function) |
| [wcscoll](wcscoll "c/string/wide/wcscoll")
(C95) | compares two wide strings in accordance to the current locale (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcscmp "cpp/string/wide/wcscmp") for `wcscmp` |
c towctrans towctrans
=========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
wint_t towctrans( wint_t wc, wctrans_t desc );
```
| | (since C95) |
Maps the wide character `wc` using the current C locale's LC\_CTYPE mapping category identified by `desc`.
### Parameters
| | | |
| --- | --- | --- |
| wc | - | the wide character to map |
| desc | - | the LC\_CTYPE mapping, obtained from a call to `[wctrans](wctrans "c/string/wide/wctrans")` |
### Return value
The mapped value of `wc` using the mapping identified by `desc` in LC\_CTYPE facet of the current C locale.
### Example
```
#include <locale.h>
#include <wctype.h>
#include <wchar.h>
#include <stdio.h>
int main(void)
{
setlocale(LC_ALL, "ja_JP.UTF-8");
wchar_t kana[] = L"ヒラガナ";
size_t sz = sizeof kana / sizeof *kana;
wchar_t hira[sz];
for(size_t n = 0; n < sz; ++n)
hira[n] = towctrans(kana[n], wctrans("tojhira"));
printf("katakana characters %ls are %ls in hiragana\n", kana, hira);
}
```
Output:
```
katakana characters ヒラガナ are ひらがな in hiragana
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.3.2.1 The towctrans function (p: 454)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.3.2,1 The towctrans function (p: 400)
### See also
| | |
| --- | --- |
| [wctrans](wctrans "c/string/wide/wctrans")
(C95) | looks up a character mapping category in the current C locale (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/towctrans "cpp/string/wide/towctrans") for `towctrans` |
c wcslen, wcsnlen_s wcslen, wcsnlen\_s
==================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
size_t wcslen( const wchar_t *str );
```
| (1) | (since C95) |
|
```
size_t wcsnlen_s(const wchar_t *str, size_t strsz);
```
| (2) | (since C11) |
1) Returns the length of a wide string, that is the number of non-null wide characters that precede the terminating null wide character.
2) Same as (1), except that the function returns zero if `str` is a null pointer and returns `strsz` if the null wide character was not found in the first `strsz` wide characters of `src` As with all bounds-checked functions, `wcslen_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<stdio.h>`.. ### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated wide string to be examined |
| strsz | - | maximum number of wide characters to examine |
### Return value
1) The length of the null-terminated wide string `str`.
2) The length of the null-terminated wide string `str` on success, zero if `str` is a null pointer, `strsz` if the null wide character was not found. ### Notes
`strnlen_s` and `wcsnlen_s` are the only [bounds-checked functions](../../error "c/error") that do not invoke the runtime constraints handler. They are pure utility functions used to provide limited support for non-null terminated strings.
### Example
```
#include <wchar.h>
#include <stdio.h>
int main(void)
{
wchar_t str[] = L"How many wide characters does this string contain?";
printf("without null character: %zu\n", wcslen(str));
printf("with null character: %zu\n", sizeof str / sizeof *str);
}
```
Output:
```
without null character: 50
with null character: 51
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.6.1 The wcslen function (p: 439)
+ K.3.9.2.4.1 The wcsnlen\_s function (p: 646-647)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.6.1 The wcslen function (p: 385)
### See also
| | |
| --- | --- |
| [strlenstrnlen\_s](../byte/strlen "c/string/byte/strlen")
(C11) | returns the length of a given string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcslen "cpp/string/wide/wcslen") for `wcslen` |
c wmemchr wmemchr
=======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
wchar_t *wmemchr( const wchar_t *ptr, wchar_t ch, size_t count );
```
| | (since C95) |
Locates the first occurrence of wide character `ch` in the initial `count` wide characters of the wide character array or integer array of compatible type, pointed to by `ptr`.
If `count` is zero, the function returns a null pointer.
### Parameters
| | | |
| --- | --- | --- |
| ptr | - | pointer to the wide character array to be examined |
| ch | - | wide character to search for |
| count | - | number of wide characters to examine |
### Return value
Pointer to the location of the wide character, or a null pointer if no such character is found.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main(void)
{
wchar_t str[] = L"诺不轻信,故人不负我\0诺不轻许,故我不负人。";
size_t sz = sizeof str / sizeof *str;
wchar_t target = L'许';
wchar_t* result = wmemchr(str, target, sz);
if (result) {
setlocale(LC_ALL, "en_US.utf8");
printf("Found '%lc' at position %td\n",target, result - str);
}
}
```
Possible output:
```
Found '许' at position 14
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.5.8 The wmemchr function (p: 438)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.5.8 The wmemchr function (p: 384)
### See also
| | |
| --- | --- |
| [memchr](../byte/memchr "c/string/byte/memchr") | searches an array for the first occurrence of a character (function) |
| [wcschr](wcschr "c/string/wide/wcschr")
(C95) | finds the first occurrence of a wide character in a wide string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wmemchr "cpp/string/wide/wmemchr") for `wmemchr` |
c towlower towlower
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
wint_t towlower( wint_t wc );
```
| | (since C95) |
Converts the given wide character to lowercase, if possible.
### Parameters
| | | |
| --- | --- | --- |
| wc | - | wide character to be converted |
### Return value
Lowercase version of `wc` or unmodified `wc` if no lowercase version is listed in the current C locale.
### Notes
Only 1:1 character mapping can be performed by this function, e.g. the Greek uppercase letter 'Σ' has two lowercase forms, depending on the position in a word: 'σ' and 'ς'. A call to `towlower` cannot be used to obtain the correct lowercase form in this case.
[ISO 30112](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which pairs of Unicode characters are included in this mapping.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t wc = L'\u0190'; // Latin capital open E ('Ɛ')
printf("in the default locale, towlower(%#x) = %#x\n", wc, towlower(wc));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, towlower(%#x) = %#x\n", wc, towlower(wc));
}
```
Output:
```
in the default locale, towlower(0x190) = 0x190
in Unicode locale, towlower(0x190) = 0x25b
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.3.1.1 The towlower function (p: 453)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.3.1.1 The towlower function (p: 399)
### See also
| | |
| --- | --- |
| [towupper](towupper "c/string/wide/towupper")
(C95) | converts a wide character to uppercase (function) |
| [tolower](../byte/tolower "c/string/byte/tolower") | converts a character to lowercase (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/towlower "cpp/string/wide/towlower") for `towlower` |
c wcsrchr wcsrchr
=======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
wchar_t* wcsrchr( const wchar_t* str, wchar_t ch );
```
| | (since C95) |
Finds the last occurrence of the wide character `ch` in the wide string pointed to by `str`.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated wide string to be analyzed |
| ch | - | wide character to search for |
### Return value
Pointer to the found character in `str`, or a null pointer if no such character is found.
### Example
```
#include <wchar.h>
#include <stdio.h>
#include <locale.h>
int main(void)
{
wchar_t arr[] = L"白猫 黒猫 кошки";
wchar_t *cat = wcsrchr(arr, L'猫');
wchar_t *dog = wcsrchr(arr, L'犬');
setlocale(LC_ALL, "en_US.utf8");
if(cat)
printf("The character 猫 found at position %td\n", cat-arr);
else
puts("The character 猫 not found");
if(dog)
printf("The character 犬 found at position %td\n", dog-arr);
else
puts("The character 犬 not found");
}
```
Output:
```
The character 猫 found at position 4
The character 犬 not found
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.5.4 The wcsrchr function (p: 436)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.5.4 The wcsrchr function (p: 382)
### See also
| | |
| --- | --- |
| [wcschr](wcschr "c/string/wide/wcschr")
(C95) | finds the first occurrence of a wide character in a wide string (function) |
| [wcspbrk](wcspbrk "c/string/wide/wcspbrk")
(C95) | finds the first location of any wide character in one wide string, in another wide string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcsrchr "cpp/string/wide/wcsrchr") for `wcsrchr` |
c wcscat, wcscat_s wcscat, wcscat\_s
=================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
wchar_t *wcscat( wchar_t *dest, const wchar_t *src );
```
| (since C95) (until C99) |
|
```
wchar_t *wcscat( wchar_t *restrict dest, const wchar_t *restrict src );
```
| (since C99) |
|
```
errno_t wcscat_s( wchar_t *restrict dest, rsize_t destsz,
const wchar_t *restrict src );
```
| (2) | (since C11) |
1) Appends a copy of the wide string pointed to by `src` to the end of the wide string pointed to by `dest`. The wide character `src[0]` replaces the null terminator at the end of `dest`. The resulting wide string is null-terminated. The behavior is undefined if the destination array is not large enough for the contents of both `str` and `dest` and the terminating null wide character. The behavior is undefined if the strings overlap.
2) Same as (1), except that it may clobber the rest of the destination array (from the last character written to `destsz`) with unspecified values and that the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `src` or `dest` is a null pointer
* `destsz` is zero or greater than `RSIZE_MAX/sizeof(wchar_t)`
* there is no null terminator in the first `destsz` wide characters of `dest`
* truncation would occur (the available space at the end of `dest` would not fit every wide character, including the null terminator, of `src`)
* overlap would occur between the source and the destination strings
As with all bounds-checked functions, `wcscat_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<wchar.h>`.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated wide string to append to |
| src | - | pointer to the null-terminated wide string to copy from |
| destsz | - | maximum number of characters to write, typically the size of the destination buffer |
### Return value
1) returns a copy of `dest`
2) returns zero on success, returns non-zero on error. Also, on error, writes `L'\0'` to `dest[0]` (unless `dest` is a null pointer or `destsz` is zero or greater than `RSIZE_MAX/sizeof(wchar_t)`). ### Example
```
#include <wchar.h>
#include <stdio.h>
#include <locale.h>
int main(void)
{
wchar_t str[50] = L"Земля, прощай.";
wcscat(str, L" ");
wcscat(str, L"В добрый путь.");
setlocale(LC_ALL, "en_US.utf8");
printf("%ls", str);
}
```
Output:
```
Земля, прощай. В добрый путь.
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.29.4.3.1 The wcscat function (p: 315)
+ K.3.9.2.2.1 The wcscat\_s function (p: 466)
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.3.1 The wcscat function (p: 432)
+ K.3.9.2.2.1 The wcscat\_s function (p: 642-643)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.3.1 The wcscat function (p: 378)
### See also
| | |
| --- | --- |
| [wcsncatwcsncat\_s](wcsncat "c/string/wide/wcsncat")
(C95)(C11) | appends a certain amount of wide characters from one wide string to another (function) |
| [strcatstrcat\_s](../byte/strcat "c/string/byte/strcat")
(C11) | concatenates two strings (function) |
| [wcscpywcscpy\_s](wcscpy "c/string/wide/wcscpy")
(C95)(C11) | copies one wide string to another (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcscat "cpp/string/wide/wcscat") for `wcscat` |
c wcstok, wcstok_s wcstok, wcstok\_s
=================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
wchar_t* wcstok( wchar_t* str, const wchar_t* delim, wchar_t **ptr );
```
| (since C95) (until C99) |
|
```
wchar_t *wcstok(wchar_t * restrict str, const wchar_t * restrict delim,
wchar_t **restrict ptr);
```
| (since C99) |
|
```
wchar_t *wcstok_s( wchar_t *restrict str, rsize_t *restrict strmax,
const wchar_t *restrict delim, wchar_t **restrict ptr);
```
| (2) | (since C11) |
1) Finds the next token in a null-terminated wide string pointed to by `str`. The separator characters are identified by null-terminated wide string pointed to by `delim`.
This function is designed to be called multiples times to obtain successive tokens from the same string. * If `str != [NULL](http://en.cppreference.com/w/c/types/NULL)`, the call is treated as the first call to `wcstok` for this particular wide string. The function searches for the first wide character which is *not* contained in `delim`.
* If no such wide character was found, there are no tokens in `str` at all, and the function returns a null pointer.
* If such wide character was found, it is the *beginning of the token*. The function then searches from that point on for the first wide character that *is* contained in `delim`.
+ If no such wide character was found, `str` has only one token, and future calls to `wcstok` will return a null pointer
+ If such wide character was found, it is *replaced* by the null wide character `L'\0'` and the parser state (typically a pointer to the following wide character) is stored in the user-provided location `*ptr`.
* The function then returns the pointer to the beginning of the token
* If `str == [NULL](http://en.cppreference.com/w/c/types/NULL)`, the call is treated as a subsequent call to `wcstok`: the function continues from where it left in the previous invocation with the same `*ptr`. The behavior is the same as if the pointer to the wide character that follows the last detected token is passed as `str`.
2) Same as (1), except that on every step, writes the number of characters left to see in `str` into `*strmax`. Repeat calls (with null `str`) must pass both `strmax` and `ptr` with the values stored by the previous call. Also, the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function, without storing anything in the object pointed to by `ptr`
* `strmax`, `delim`, or `ptr` is a null pointer
* on a non-initial call (with null `str`), `*ptr` is a null pointer
* on the first call, `*strmax` is zero or greater than `RSIZE_MAX/sizeof(wchar_t)`
* search for the end of a token reaches the end of the source string (as measured by the initial value of `*strmax`)) without encountering the null terminator
As all bounds-checked functions, `wcstok_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `wchar.h`.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated wide string to tokenize |
| delim | - | pointer to the null-terminated wide string identifying delimiters |
| ptr | - | pointer to an object of type `wchar_t*`, which is used by both `wcstok` and `wcstok_s` to store the internal state of the parser |
| strmax | - | pointer to an object which initially holds the size of `str`: wcstok\_s stores the number of characters that remain to be examined |
### Return value
Returns pointer to the beginning of the next token or null pointer if there are no more tokens.
### Note
This function is destructive: it writes the `L'\0'` characters in the elements of the string `str`. In particular, a wide string literal cannot be used as the first argument of `wcstok`.
Unlike `[strtok](../byte/strtok "c/string/byte/strtok")`, `wcstok` does not update static storage: it stores the parser state in the user-provided location.
Unlike most other tokenizers, the delimiters in `wcstok` can be different for each subsequent token, and can even depend on the contents of the previous tokens.
### Example
```
#include <wchar.h>
#include <stdio.h>
int main(void)
{
wchar_t input[] = L"A bird came down the walk";
printf("Parsing the input string '%ls'\n", input);
wchar_t *buffer;
wchar_t *token = wcstok(input, L" ", &buffer);
while(token) {
printf("%ls\n", token);
token = wcstok(NULL, L" ", &buffer);
}
printf("Contents of the input string now: '");
for(size_t n = 0; n < sizeof input / sizeof *input; ++n)
input[n] ? printf("%lc", input[n]) : printf("\\0");
puts("'");
}
```
Output:
```
Parsing the input string 'A bird came down the walk'
A
bird
came
down
the
walk
Contents of the input string now: 'A\0bird\0came\0down\0the\0walk\0'
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.5.7 The wcstok function (p: 437-438)
+ K.3.9.2.3.1 The wcstok\_s function (p: 645-646)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.5.7 The wcstok function (p: 383-384)
### See also
| | |
| --- | --- |
| [strtokstrtok\_s](../byte/strtok "c/string/byte/strtok")
(C11) | finds the next token in a byte string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcstok "cpp/string/wide/wcstok") for `wcstok` |
| programming_docs |
c iswxdigit iswxdigit
=========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswxdigit( wint_t ch );
```
| | (since C95) |
Checks if the given wide character corresponds (if narrowed) to a hexadecimal numeric character, i.e. one of `0123456789abcdefABCDEF`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is a hexadecimal numeric character, zero otherwise.
### Notes
`[iswdigit](iswdigit "c/string/wide/iswdigit")` and `iswxdigit` are the only standard wide character classification functions that are not affected by the currently installed C locale.
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.1.12 The iswxdigit function (p: 451)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.1.12 The iswxdigit function (p: 397)
### See also
| | |
| --- | --- |
| [isxdigit](../byte/isxdigit "c/string/byte/isxdigit") | checks if a character is a hexadecimal character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/iswxdigit "cpp/string/wide/iswxdigit") for `iswxdigit` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "c/string/byte/isprint") [`iswprint`](iswprint "c/string/wide/iswprint"). | [`isspace`](../byte/isspace "c/string/byte/isspace") [`iswspace`](iswspace "c/string/wide/iswspace"). | [`isblank`](../byte/isblank "c/string/byte/isblank") [`iswblank`](iswblank "c/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "c/string/byte/isgraph") [`iswgraph`](iswgraph "c/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "c/string/byte/ispunct") [`iswpunct`](iswpunct "c/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "c/string/byte/isalnum") [`iswalnum`](iswalnum "c/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "c/string/byte/isalpha") [`iswalpha`](iswalpha "c/string/wide/iswalpha"). | [`isupper`](../byte/isupper "c/string/byte/isupper") [`iswupper`](iswupper "c/string/wide/iswupper"). | [`islower`](../byte/islower "c/string/byte/islower") [`iswlower`](iswlower "c/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "c/string/byte/isdigit") [`iswdigit`](iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "c/string/byte/isxdigit") **`iswxdigit`**. |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c wcsncpy, wcsncpy_s wcsncpy, wcsncpy\_s
===================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
wchar_t* wcsncpy( wchar_t* dest, const wchar_t* src, size_t count );
```
| (since C95) (until C99) |
|
```
wchar_t *wcsncpy( wchar_t *restrict dest, const wchar_t *restrict src, size_t count );
```
| (since C99) |
|
```
errno_t wcsncpy_s( wchar_t *restrict dest, rsize_t destsz,
const wchar_t *restrict src, rsize_t count);
```
| (2) | (since C11) |
1) Copies at most `count` characters of the wide string pointed to by `src` (including the terminating null wide character) to wide character array pointed to by `dest`.
If `count` is reached before the entire string `src` was copied, the resulting wide character array is not null-terminated.
If, after copying the terminating null wide character from `src`, `count` is not reached, additional null wide characters are written to `dest` until the total of `count` characters have been written.
If the strings overlap, the behavior is undefined.
2) Same as (1), except that the function does not continue writing zeroes into the destination array to pad up to `count`, it stops after writing the terminating null character (if there was no null in the source, it writes one at `dest[count]` and then stops). Also, the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `src` or `dest` is a null pointer
* `destsz` or `count` is zero or greater than `RSIZE_MAX/sizeof(wchar_t)`
* `count` is greater or equal `destsz`, but `destsz` is less or equal `wcsnlen_s(src, count)`, in other words, truncation would occur
* overlap would occur between the source and the destination strings
As with all bounds-checked functions, `wcsncpy_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<wchar.h>`.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the wide character array to copy to |
| src | - | pointer to the wide string to copy from |
| count | - | maximum number of wide characters to copy |
| destsz | - | the size of the destination buffer |
### Return value
1) returns a copy of `dest`
2) returns zero on success, returns non-zero on error. Also, on error, writes `L'\0'` to `dest[0]` (unless `dest` is a null pointer or `destsz` is zero or greater than `RSIZE_MAX/sizeof(wchar_t)`) and may clobber the rest of the destination array with unspecified values. ### Notes
In typical usage, `count` is the number of elements in the destination array.
Although truncation to fit the destination buffer is a security risk and therefore a runtime constraints violation for `wcsncpy_s`, it is possible to get the truncating behavior by specifying `count` equal to the size of the destination array minus one: it will copy the first `count` wide characters and append the null wide terminator as always: `wcsncpy_s(dst, sizeof dst / sizeof *dst, src, (sizeof dst / sizeof *dst)-1);`
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main(void)
{
const wchar_t src[] = L"わゐ";
wchar_t dest[6] = {L'あ', L'い', L'う', L'え', L'お'};
wcsncpy(dest, src, 4); // this will copy わゐ and repeat L'\0' two times
puts("The contents of dest are: ");
setlocale(LC_ALL, "en_US.utf8");
const long dest_size = sizeof dest / sizeof *dest;
for(wchar_t* p = dest; p-dest != dest_size; ++p) {
*p ? printf("%lc ", *p)
: printf("\\0 ");
}
}
```
Possible output:
```
The contents of dest are:
わ ゐ \0 \0 お \0
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.29.4.2.2 The wcsncpy function (p: 314)
+ K.3.9.2.1.2 The wcsncpy\_s function (p: 464)
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.2.2 The wcsncpy function (p: 431)
+ K.3.9.2.1.2 The wcsncpy\_s function (p: 640-641)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.2.2 The wcsncpy function (p: 377)
### See also
| | |
| --- | --- |
| [wcscpywcscpy\_s](wcscpy "c/string/wide/wcscpy")
(C95)(C11) | copies one wide string to another (function) |
| [wmemcpywmemcpy\_s](wmemcpy "c/string/wide/wmemcpy")
(C95)(C11) | copies a certain amount of wide characters between two non-overlapping arrays (function) |
| [strncpystrncpy\_s](../byte/strncpy "c/string/byte/strncpy")
(C11) | copies a certain amount of characters from one string to another (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcsncpy "cpp/string/wide/wcsncpy") for `wcsncpy` |
c wcstof, wcstod, wcstold wcstof, wcstod, wcstold
=======================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
float wcstof( const wchar_t * restrict str, wchar_t ** restrict str_end );
```
| | (since C99) |
|
```
double wcstod( const wchar_t * str, wchar_t ** str_end );
```
| | (since C95) (until C99) |
|
```
double wcstod( const wchar_t * restrict str, wchar_t ** restrict str_end );
```
| | (since C99) |
|
```
long double wcstold( const wchar_t * restrict str, wchar_t ** restrict str_end );
```
| | (since C99) |
Interprets a floating point value in a wide string pointed to by `str`.
Function discards any whitespace characters (as determined by `std::[iswspace](http://en.cppreference.com/w/c/string/wide/iswspace)()`) until first non-whitespace character is found. Then it takes as many characters as possible to form a valid floating-point representation and converts them to a floating-point value. The valid floating-point value can be one of the following:
* decimal floating-point expression. It consists of the following parts:
+ (optional) plus or minus sign
+ nonempty sequence of decimal digits optionally containing decimal-point character (as determined by the current C [locale](../../locale/setlocale "c/locale/setlocale")) (defines significand)
+ (optional) `e` or `E` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 10)
| | |
| --- | --- |
| * hexadecimal floating-point expression. It consists of the following parts:
+ (optional) plus or minus sign
+ `0x` or `0X`
+ nonempty sequence of hexadecimal digits optionally containing a decimal-point character (as determined by the current C [locale](../../locale/setlocale "c/locale/setlocale")) (defines significand)
+ (optional) `p` or `P` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 2)
* infinity expression. It consists of the following parts:
+ (optional) plus or minus sign
+ `INF` or `INFINITY` ignoring case
* not-a-number expression. It consists of the following parts:
+ (optional) plus or minus sign
+ `NAN` or `NAN(`*char\_sequence*`)` ignoring case of the `NAN` part. *char\_sequence* can only contain digits, Latin letters, and underscores. The result is a quiet NaN floating-point value.
| (since C99) |
* any other expression that may be accepted by the currently installed C [locale](../../locale/setlocale "c/locale/setlocale")
The functions sets the pointer pointed to by `str_end` to point to the wide character past the last character interpreted. If `str_end` is a null pointer, it is ignored.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated wide string to be interpreted |
| str\_end | - | pointer to a pointer to a wide character. |
### Return value
Floating point value corresponding to the contents of `str` on success. If the converted value falls out of range of corresponding return type, range error occurs and `[HUGE\_VAL](../../numeric/math/huge_val "c/numeric/math/HUGE VAL")`, `[HUGE\_VALF](../../numeric/math/huge_val "c/numeric/math/HUGE VAL")` or `[HUGE\_VALL](../../numeric/math/huge_val "c/numeric/math/HUGE VAL")` is returned. If no conversion can be performed, `0` is returned.
### Example
```
#include <stdio.h>
#include <errno.h>
#include <wchar.h>
int main(void)
{
const wchar_t *p = L"111.11 -2.22 0X1.BC70A3D70A3D7P+6 1.18973e+4932zzz";
printf("Parsing L\"%ls\":\n", p);
wchar_t *end;
for (double f = wcstod(p, &end); p != end; f = wcstod(p, &end))
{
printf("'%.*ls' -> ", (int)(end-p), p);
p = end;
if (errno == ERANGE){
printf("range error, got ");
errno = 0;
}
printf("%f\n", f);
}
}
```
Output:
```
Parsing L"111.11 -2.22 0X1.BC70A3D70A3D7P+6 1.18973e+4932zzz":
'111.11' -> 111.110000
' -2.22' -> -2.220000
' 0X1.BC70A3D70A3D7P+6' -> 111.110000
' 1.18973e+4932' -> range error, got inf
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.1.1 The wcstod, wcstof, and wcstold functions (p: 426-428)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.1.1 The wcstod, wcstof, and wcstold functions (p: 372-374)
### See also
| | |
| --- | --- |
| [strtofstrtodstrtold](../byte/strtof "c/string/byte/strtof")
(C99)(C99) | converts a byte string to a floating point value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcstof "cpp/string/wide/wcstof") for `wcstof, wcstod, wcstold` |
c wcstoimax, wcstoumax wcstoimax, wcstoumax
====================
| Defined in header `<inttypes.h>` | | |
| --- | --- | --- |
|
```
intmax_t wcstoimax( const wchar_t *restrict nptr,
wchar_t **restrict endptr, int base );
```
| | (since C99) |
|
```
uintmax_t wcstoumax( const wchar_t *restrict nptr,
wchar_t **restrict endptr, int base );
```
| | (since C99) |
Interprets an unsigned integer value in a wide string pointed to by `nptr`.
Discards any whitespace characters (as identified by calling [`iswspace`](iswspace "c/string/wide/iswspace")) until the first non-whitespace character is found, then takes as many characters as possible to form a valid *base-n* (where n=`base`) unsigned integer number representation and converts them to an integer value. The valid unsigned integer value consists of the following parts:
* (optional) plus or minus sign
* (optional) prefix (`0`) indicating octal base (applies only when the base is `8` or `0`)
* (optional) prefix (`0x` or `0X`) indicating hexadecimal base (applies only when the base is `16` or `0`)
* a sequence of digits
The set of valid values for base is `{0,2,3,...,36}.` The set of valid digits for base-`2` integers is `{0,1},` for base-`3` integers is `{0,1,2},` and so on. For bases larger than `10`, valid digits include alphabetic characters, starting from `Aa` for base-`11` integer, to `Zz` for base-`36` integer. The case of the characters is ignored.
Additional numeric formats may be accepted by the currently installed C [locale](../../locale/setlocale "c/locale/setlocale").
If the value of `base` is `0`, the numeric base is auto-detected: if the prefix is `0`, the base is octal, if the prefix is `0x` or `0X`, the base is hexadecimal, otherwise the base is decimal.
If the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by [unary minus](../../language/operator_arithmetic#Unary_arithmetic "c/language/operator arithmetic") in the result type, which applies unsigned integer wraparound rules.
The functions sets the pointer pointed to by `endptr` to point to the wide character past the last character interpreted. If `endptr` is a null pointer, it is ignored.
### Parameters
| | | |
| --- | --- | --- |
| nptr | - | pointer to the null-terminated wide string to be interpreted |
| endptr | - | pointer to a pointer to a wide character. |
| base | - | *base* of the interpreted integer value |
### Return value
Integer value corresponding to the contents of `str` on success. If the converted value falls out of range of corresponding return type, range error occurs and `[INTMAX\_MAX](../../types/integer "c/types/integer")`, `[INTMAX\_MIN](../../types/integer "c/types/integer")`, `[UINTMAX\_MAX](../../types/integer "c/types/integer")`, or `0` is returned, as appropriate. If no conversion can be performed, `0` is returned.
### Example
```
#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>
int main(void)
{
wchar_t* endptr;
wprintf(L"%ld\n", wcstoimax(L" -123junk", &endptr, 10)); /* base 10 */
wprintf(L"%ld\n", wcstoimax(L"11111111", &endptr, 2)); /* base 2 */
wprintf(L"%ld\n", wcstoimax(L"XyZ", &endptr, 36)); /* base 36 */
wprintf(L"%ld\n", wcstoimax(L"010", &endptr, 0)); /* octal auto-detection */
wprintf(L"%ld\n", wcstoimax(L"10", &endptr, 0)); /* decimal auto-detection */
wprintf(L"%ld\n", wcstoimax(L"0x10", &endptr, 0)); /* hexadecimal auto-detection */
/* range error */
/* LONG_MAX+1 --> LONG_MAX */
errno = 0;
wprintf(L"%ld\n", wcstoimax(L"9223372036854775808", &endptr, 10));
wprintf(L"%s\n", strerror(errno));
}
```
Output:
```
-123
255
44027
8
10
16
9223372036854775807
Numerical result out of range
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.8.2.4 The wcstoimax and wcstoumax functions (p: 220)
* C99 standard (ISO/IEC 9899:1999):
+ 7.8.2.4 The wcstoimax and wcstoumax functions (p: 201)
### See also
| | |
| --- | --- |
| [strtoimaxstrtoumax](../byte/strtoimax "c/string/byte/strtoimax")
(C99)(C99) | converts a byte string to `[intmax\_t](http://en.cppreference.com/w/c/types/integer)` or `[uintmax\_t](http://en.cppreference.com/w/c/types/integer)` (function) |
| [wcstolwcstoll](wcstol "c/string/wide/wcstol")
(C95)(C99) | converts a wide string to an integer value (function) |
| [wcstoulwcstoull](wcstoul "c/string/wide/wcstoul")
(C95)(C99) | converts a wide string to an unsigned integer value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wcstoimax "cpp/string/wide/wcstoimax") for `wcstoimax, wcstoumax` |
c iswspace iswspace
========
| Defined in header `<wctype.h>` | | |
| --- | --- | --- |
|
```
int iswspace( wint_t ch );
```
| | (since C95) |
Checks if the given wide character is a whitespace character, i.e. either space (`0x20`), form feed (`0x0c`), line feed (`0x0a`), carriage return (`0x0d`), horizontal tab (`0x09`), vertical tab (`0x0b`) or any whitespace character specific to the current locale.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | wide character |
### Return value
Non-zero value if the wide character is a whitespace character, zero otherwise.
### Notes
ISO 30112 defines POSIX space characters as Unicode characters U+0009..U+000D, U+0020, U+1680, U+180E, U+2000..U+2006, U+2008..U+200A, U+2028, U+2029, U+205F, and U+3000.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
int main(void)
{
wchar_t c = L'\u2003'; // Unicode character 'EM SPACE'
printf("in the default locale, iswspace(%#x) = %d\n", c, !!iswspace(c));
setlocale(LC_ALL, "en_US.utf8");
printf("in Unicode locale, iswspace(%#x) = %d\n", c, !!iswspace(c));
}
```
Output:
```
in the default locale, iswspace(0x2003) = 0
in Unicode locale, iswspace(0x2003) = 1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.30.2.1.10 The iswspace function (p: 450-451)
* C99 standard (ISO/IEC 9899:1999):
+ 7.25.2.1.10 The iswspace function (p: 396-397)
### See also
| | |
| --- | --- |
| [isspace](../byte/isspace "c/string/byte/isspace") | checks if a character is a space character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/iswspace "cpp/string/wide/iswspace") for `iswspace` |
| ASCII values | characters | [`iscntrl`](../byte/iscntrl "c/string/byte/iscntrl") [`iswcntrl`](iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](../byte/isprint "c/string/byte/isprint") [`iswprint`](iswprint "c/string/wide/iswprint"). | [`isspace`](../byte/isspace "c/string/byte/isspace") **`iswspace`**. | [`isblank`](../byte/isblank "c/string/byte/isblank") [`iswblank`](iswblank "c/string/wide/iswblank"). | [`isgraph`](../byte/isgraph "c/string/byte/isgraph") [`iswgraph`](iswgraph "c/string/wide/iswgraph"). | [`ispunct`](../byte/ispunct "c/string/byte/ispunct") [`iswpunct`](iswpunct "c/string/wide/iswpunct"). | [`isalnum`](../byte/isalnum "c/string/byte/isalnum") [`iswalnum`](iswalnum "c/string/wide/iswalnum"). | [`isalpha`](../byte/isalpha "c/string/byte/isalpha") [`iswalpha`](iswalpha "c/string/wide/iswalpha"). | [`isupper`](../byte/isupper "c/string/byte/isupper") [`iswupper`](iswupper "c/string/wide/iswupper"). | [`islower`](../byte/islower "c/string/byte/islower") [`iswlower`](iswlower "c/string/wide/iswlower"). | [`isdigit`](../byte/isdigit "c/string/byte/isdigit") [`iswdigit`](iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](../byte/isxdigit "c/string/byte/isxdigit") [`iswxdigit`](iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| programming_docs |
c wmemcpy, wmemcpy_s wmemcpy, wmemcpy\_s
===================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
wchar_t* wmemcpy( wchar_t* dest, const wchar_t* src, size_t count );
```
| (since C95) (until C99) |
|
```
wchar_t *wmemcpy(wchar_t *restrict dest, const wchar_t *restrict src,
size_t count );
```
| (since C99) |
|
```
errno_t wmemcpy_s( wchar_t *restrict dest, rsize_t destsz,
const wchar_t *restrict src, rsize_t count );
```
| (2) | (since C11) |
1) Copies exactly `count` successive wide characters from the wide character array pointed to by `src` to the wide character array pointed to by `dest`. If the objects overlap, the behavior is undefined. If `count` is zero, the function does nothing.
2) Same as (1), except that the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `src` or `dest` is a null pointer
* `destsz` or `count` is greater than `RSIZE_MAX/sizeof(wchar_t)`
* `count` is greater than `destsz` (overflow would occur)
* overlap would occur between the source and the destination arrays
As with all bounds-checked functions, `wmemcpy_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<wchar.h>`.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the wide character array to copy to |
| src | - | pointer to the wide character array to copy from |
| count | - | number of wide characters to copy |
| destsz | - | max number of wide characters to write (the size of the destination buffer) |
### Return value
1) returns a copy of `dest`
2) returns zero on success, returns non-zero on error. Also, on error, fills the entire `dst` up to and not including `dst+dstsz` with null wide characters, `L'\0'` (unless `dest` is null or `destsz` is greater than `RSIZE_MAX/sizeof(wchar_t)`) ### Notes
This function's analog for byte strings is `[strncpy](../byte/strncpy "c/string/byte/strncpy")`, not `[strcpy](../byte/strcpy "c/string/byte/strcpy")`.
This function is not locale-sensitive and pays no attention to the values of the `wchar_t` objects it copies: nulls as well as invalid characters are copied too.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main(void)
{
wchar_t from1[] = L"नमस्ते";
size_t sz1 = sizeof from1 / sizeof *from1;
wchar_t from2[] = L"Բարև";
size_t sz2 = sizeof from2 / sizeof *from2;
wchar_t to[sz1 + sz2];
wmemcpy(to, from1, sz1); // copy from1, along with its null terminator
wmemcpy(to + sz1, from2, sz2); // append from2, along with its null terminator
setlocale(LC_ALL, "en_US.utf8");
printf("Wide array contains: ");
for(size_t n = 0; n < sizeof to / sizeof *to; ++n)
if(to[n])
printf("%lc", to[n]);
else
printf("\\0");
printf("\n");
}
```
Possible output:
```
Wide array contains: नमस्ते\0Բարև\0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.2.3 The wmemcpy function (p: 431)
+ K.3.9.2.1.3 The wmemcpy\_s function (p: 641)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.2.3 The wmemcpy function (p: 377)
### See also
| | |
| --- | --- |
| [wmemmovewmemmove\_s](wmemmove "c/string/wide/wmemmove")
(C95)(C11) | copies a certain amount of wide characters between two, possibly overlapping, arrays (function) |
| [strncpystrncpy\_s](../byte/strncpy "c/string/byte/strncpy")
(C11) | copies a certain amount of characters from one string to another (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wmemcpy "cpp/string/wide/wmemcpy") for `wmemcpy` |
c wmemmove, wmemmove_s wmemmove, wmemmove\_s
=====================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
wchar_t* wmemmove( wchar_t* dest, const wchar_t* src, size_t count );
```
| (1) | (since C95) |
|
```
errno_t wmemmove_s( wchar_t *dest, rsize_t destsz,
const wchar_t *src, rsize_t count);
```
| (2) | (since C11) |
1) Copies exactly `count` successive wide characters from the wide character array pointed to by `src` to the wide character array pointed to by `dest`. If `count` is zero, the function does nothing. The arrays may overlap: copying takes place as if the wide characters were copied to a temporary wide character array and then copied from the temporary array to `dest`.
2) Same as (1), except that the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `src` or `dest` is a null pointer
* `destsz` or `count` is greater than `RSIZE_MAX/sizeof(wchar_t)`
* `count` is greater than `destsz` (overflow would occur)
As with all bounds-checked functions, `wmemcpy_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<wchar.h>`.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the wide character array to copy to |
| src | - | pointer to the wide character array to copy from |
| destsz | - | max number of wide characters to write (the size of the destination buffer) |
| count | - | number of wide characters to copy |
### Return value
1) Returns a copy of `dest`
2) Returns zero on success, returns non-zero on error. Also, on error, fills the entire `dst` up to and not including `dst+dstsz` with null wide characters, `L'\0'` (unless `dest` is null or `destsz` is greater than `RSIZE_MAX/sizeof(wchar_t)`) ### Notes
This function is not locale-sensitive and pays no attention to the values of the `wchar_t` objects it copies: nulls as well as invalid characters are copied too.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
wchar_t str[] = L"αβγδεζηθικλμνξοπρστυφχψω";
printf("%ls\n", str);
wmemmove(str+4, str+3, 3); // copy from [δεζ] to [εζη]
printf("%ls\n", str);
}
```
Output:
```
αβγδεζηθικλμνξοπρστυφχψω
αβγδδεζθικλμνξοπρστυφχψω
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.4.2.4 The wmemmove function (p: 432)
+ K.3.9.2.1.4 The wmemmove\_s function (p: 642)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.4.2.4 The wmemmove function (p: 378)
### See also
| | |
| --- | --- |
| [memmovememmove\_s](../byte/memmove "c/string/byte/memmove")
(C11) | moves one buffer to another (function) |
| [wmemcpywmemcpy\_s](wmemcpy "c/string/wide/wmemcpy")
(C95)(C11) | copies a certain amount of wide characters between two non-overlapping arrays (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wmemmove "cpp/string/wide/wmemmove") for `wmemmove` |
c strncat, strncat_s strncat, strncat\_s
===================
| Defined in header `<string.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
char *strncat( char *dest, const char *src, size_t count );
```
| (until C99) |
|
```
char *strncat( char *restrict dest, const char *restrict src, size_t count );
```
| (since C99) |
|
```
errno_t strncat_s(char *restrict dest, rsize_t destsz,
const char *restrict src, rsize_t count);
```
| (2) | (since C11) |
1) Appends at most `count` characters from the character array pointed to by `src`, stopping if the null character is found, to the end of the null-terminated byte string pointed to by `dest`. The character `src[0]` replaces the null terminator at the end of `dest`. The terminating null character is always appended in the end (so the maximum number of bytes the function may write is `count+1`).
The behavior is undefined if the destination array does not have enough space for the contents of both `dest` and the first `count` characters of `src`, plus the terminating null character. The behavior is undefined if the source and destination objects overlap. The behavior is undefined if either `dest` is not a pointer to a null-terminated byte string or `src` is not a pointer to a character array,
2) Same as (1), except that this function may clobber the remainder of the destination array (from the last byte written to `destsz`) and that the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function: * `src` or `dest` is a null pointer
* `destsz` or `count` is zero or greater than `RSIZE_MAX`
* there is no null character in the first `destsz` bytes of `dest`
* truncation would occur: `count` or the length of `src`, whichever is less, exceeds the space available between the null terminator of `dest` and `destsz`.
* overlap would occur between the source and the destination strings
The behavior is undefined if the size of the character array pointed to by `dest` < `strnlen(dest,destsz)+strnlen(src,count)+1` < `destsz`; in other words, an erroneous value of `destsz` does not expose the impending buffer overflow. The behavior is undefined if the size of the character array pointed to by `src` < `strnlen(src,count)` < `destsz`; in other words, an erroneous value of `count` does not expose the impending buffer overflow. As with all bounds-checked functions, `strncat_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<string.h>`. ### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated byte string to append to |
| src | - | pointer to the character array to copy from |
| count | - | maximum number of characters to copy |
| destsz | - | the size of the destination buffer |
### Return value
1) returns a copy of `dest`
2) returns zero on success, returns non-zero on error. Also, on error, writes zero to `dest[0]` (unless `dest` is a null pointer or `destsz` is zero or greater than `RSIZE_MAX`). ### Notes
Because `strncat` needs to seek to the end of `dest` on each call, it is inefficient to concatenate many strings into one using `strncat`.
Although truncation to fit the destination buffer is a security risk and therefore a runtime constraints violation for `strncat_s`, it is possible to get the truncating behavior by specifying `count` equal to the size of the destination array minus one: it will copy the first `count` bytes and append the null terminator as always: `strncat_s(dst, sizeof dst, src, (sizeof dst)-strnlen_s(dst, sizeof dst)-1);`
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[50] = "Hello ";
char str2[50] = "World!";
strcat(str, str2);
strncat(str, " Goodbye World!", 3);
puts(str);
#ifdef __STDC_LIB_EXT1__
set_constraint_handler_s(ignore_handler_s);
char s1[100] = "good";
char s5[1000] = "bye";
int r1 = strncat_s(s1, 100, s5, 1000); // r1 is 0, s1 holds "goodbye\0"
printf("s1 = %s, r1 = %d\n", s1, r1);
char s2[6] = "hello";
int r2 = strncat_s(s2, 6, "", 1); // r2 is 0, s2 holds "hello\0"
printf("s2 = %s, r2 = %d\n", s2, r2);
char s3[6] = "hello";
int r3 = strncat_s(s3, 6, "X", 2); // r3 is non-zero, s3 holds "\0"
printf("s3 = %s, r3 = %d\n", s3, r3);
// the strncat_s truncation idiom:
char s4[7] = "abc";
int r4 = strncat_s(s4, 7, "defghijklmn", 3); // r is 0, s4 holds "abcdef\0"
printf("s4 = %s, r4 = %d\n", s4, r4);
#endif
}
```
Possible output:
```
Hello World! Go
s1 = goodbye, r1 = 0
s2 = hello, r2 = 0
s3 = , r3 = 22
s4 = abcdef, r4 = 0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.3.2 The strncat function (p: 364-365)
+ K.3.7.2.2 The strncat\_s function (p: 618-620)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.3.2 The strncat function (p: 327-328)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.3.2 The strncat function
### See also
| | |
| --- | --- |
| [strcatstrcat\_s](strcat "c/string/byte/strcat")
(C11) | concatenates two strings (function) |
| [strcpystrcpy\_s](strcpy "c/string/byte/strcpy")
(C11) | copies one string to another (function) |
| [memccpy](memccpy "c/string/byte/memccpy")
(C23) | copies one buffer to another, stopping after the specified delimiter (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strncat "cpp/string/byte/strncat") for `strncat` |
c strchr strchr
======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
char *strchr( const char *str, int ch );
```
| | |
Finds the first occurrence of `ch` (after conversion to `char` as if by `(char)ch`) in the null-terminated byte string pointed to by `str` (each character interpreted as `unsigned char`). The terminating null character is considered to be a part of the string and can be found when searching for `'\0'`.
The behavior is undefined if `str` is not a pointer to a null-terminated byte string.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated byte string to be analyzed |
| ch | - | character to search for |
### Return value
Pointer to the found character in `str`, or null pointer if no such character is found.
### Example
```
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *str = "Try not. Do, or do not. There is no try.";
char target = 'T';
const char *result = str;
while((result = strchr(result, target)) != NULL) {
printf("Found '%c' starting at '%s'\n", target, result);
++result; // Increment result, otherwise we'll find target at the same location
}
}
```
Output:
```
Found 'T' starting at 'Try not. Do, or do not. There is no try.'
Found 'T' starting at 'There is no try.'
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.5.2 The strchr function (p: 367-368)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.5.2 The strchr function (p: 330)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.5.2 The strchr function
### See also
| | |
| --- | --- |
| [memchr](memchr "c/string/byte/memchr") | searches an array for the first occurrence of a character (function) |
| [strrchr](strrchr "c/string/byte/strrchr") | finds the last occurrence of a character (function) |
| [strpbrk](strpbrk "c/string/byte/strpbrk") | finds the first location of any character in one string, in another string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strchr "cpp/string/byte/strchr") for `strchr` |
c isxdigit isxdigit
========
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int isxdigit( int ch );
```
| | |
Checks if the given character is a hexadecimal numeric character (`0123456789abcdefABCDEF`) or is classified as a hexadecimal character.
The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/c/io)`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to classify |
### Return value
Non-zero value if the character is an hexadecimal numeric character, zero otherwise.
### Notes
`isdigit` and `isxdigit` are the only standard narrow character classification functions that are not affected by the currently installed C locale, although some implementations (e.g. Microsoft in 1252 codepage) may classify additional single-byte characters as digits.
### Example
```
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
int main(void)
{
for (int ndx=0; ndx<=UCHAR_MAX; ndx++)
if (isxdigit(ndx)) printf("%c", ndx);
printf("\n");
}
```
Output:
```
0123456789ABCDEFabcdef
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.1.12 The isxdigit function (p: 147)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.1.12 The isxdigit function (p: 203)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.1.12 The isxdigit function (p: 184)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.1.11 The isxdigit function
### See also
| | |
| --- | --- |
| [iswxdigit](../wide/iswxdigit "c/string/wide/iswxdigit")
(C95) | checks if a wide character is a hexadecimal character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/isxdigit "cpp/string/byte/isxdigit") for `isxdigit` |
| ASCII values | characters | [`iscntrl`](iscntrl "c/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](isprint "c/string/byte/isprint") [`iswprint`](../wide/iswprint "c/string/wide/iswprint"). | [`isspace`](isspace "c/string/byte/isspace") [`iswspace`](../wide/iswspace "c/string/wide/iswspace"). | [`isblank`](isblank "c/string/byte/isblank") [`iswblank`](../wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](isgraph "c/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](ispunct "c/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](isalnum "c/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](isalpha "c/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](isupper "c/string/byte/isupper") [`iswupper`](../wide/iswupper "c/string/wide/iswupper"). | [`islower`](islower "c/string/byte/islower") [`iswlower`](../wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](isdigit "c/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "c/string/wide/iswdigit"). | **`isxdigit`** [`iswxdigit`](../wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| programming_docs |
c toupper toupper
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int toupper( int ch );
```
| | |
Converts the given character to uppercase according to the character conversion rules defined by the currently installed C locale.
In the default "C" locale, the following lowercase letters `abcdefghijklmnopqrstuvwxyz` are replaced with respective uppercase letters `ABCDEFGHIJKLMNOPQRSTUVWXYZ`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to be converted. If the value of `ch` is not representable as `unsigned char` and does not equal `[EOF](http://en.cppreference.com/w/c/io)`, the behavior is undefined. |
### Return value
Uppercase version of `ch` or unmodified `ch` if no uppercase version is listed in the current C locale.
### Example
```
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
#include <limits.h>
int main(void)
{
/* In the default locale: */
for (unsigned char l = 0; l < UCHAR_MAX; l++) {
unsigned char u = toupper(l);
if (u != l) printf("%c%c ", l, u);
}
printf("\n\n");
unsigned char c = '\xb8'; // the character Ž in ISO-8859-15
// but ´ (acute accent) in ISO-8859-1
setlocale(LC_ALL, "en_US.iso88591");
printf("in iso8859-1, toupper('0x%x') gives 0x%x\n", c, toupper(c));
setlocale(LC_ALL, "en_US.iso885915");
printf("in iso8859-15, toupper('0x%x') gives 0x%x\n", c, toupper(c));
}
```
Possible output:
```
aA bB cC dD eE fF gG hH iI jJ kK lL mM nN oO pP qQ rR sS tT uU vV wW xX yY zZ
in iso8859-1, toupper('0xb8') gives 0xb8
in iso8859-15, toupper('0xb8') gives 0xb4
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.2.2 The toupper function (p: 147-148)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.2.2 The toupper function (p: 204)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.2.2 The toupper function (p: 185)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.2.2 The toupper function
### See also
| | |
| --- | --- |
| [tolower](tolower "c/string/byte/tolower") | converts a character to lowercase (function) |
| [towupper](../wide/towupper "c/string/wide/towupper")
(C95) | converts a wide character to uppercase (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/toupper "cpp/string/byte/toupper") for `toupper` |
c strstr strstr
======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
char *strstr( const char* str, const char* substr );
```
| | |
Finds the first occurrence of the null-terminated byte string pointed to by `substr` in the null-terminated byte string pointed to by `str`. The terminating null characters are not compared.
The behavior is undefined if either `str` or `substr` is not a pointer to a null-terminated byte string.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated byte string to examine |
| substr | - | pointer to the null-terminated byte string to search for |
### Return value
Pointer to the first character of the found substring in `str`, or a null pointer if such substring is not found. If `substr` points to an empty string, `str` is returned.
### Example
```
#include <string.h>
#include <stdio.h>
void find_str(char const* str, char const* substr)
{
char* pos = strstr(str, substr);
pos ? printf("found the string '%s' in '%s' at position %td\n",
substr, str, pos - str)
: printf("the string '%s' was not found in '%s'\n",
substr, str);
}
int main(void)
{
char* str = "one two three";
find_str(str, "two");
find_str(str, "");
find_str(str, "nine");
find_str(str, "n");
return 0;
}
```
Output:
```
found the string 'two' in 'one two three' at position 4
found the string '' in 'one two three' at position 0
the string 'nine' was not found in 'one two three'
found the string 'n' in 'one two three' at position 1
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.24.5.7 The strstr function (p: 269)
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.5.7 The strstr function (p: 369)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.5.7 The strstr function (p: 332)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.5.7 The strstr function
### See also
| | |
| --- | --- |
| [strchr](strchr "c/string/byte/strchr") | finds the first occurrence of a character (function) |
| [strrchr](strrchr "c/string/byte/strrchr") | finds the last occurrence of a character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strstr "cpp/string/byte/strstr") for `strstr` |
c memset, memset_s memset, memset\_s
=================
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
void *memset( void *dest, int ch, size_t count );
```
| (1) | |
|
```
errno_t memset_s( void *dest, rsize_t destsz, int ch, rsize_t count );
```
| (2) | (since C11) |
1) Copies the value `(unsigned char)ch` into each of the first `count` characters of the object pointed to by `dest`.
The behavior is undefined if access occurs beyond the end of the dest array. The behavior is undefined if `dest` is a null pointer.
2) Same as (1), except that the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function after storing `ch` in every location of the destination range `[dest, dest+destsz)` if `dest` and `destsz` are themselves valid: * `dest` is a null pointer
* `destsz` or `count` is greater than `RSIZE_MAX`
* `count` is greater than `destsz` (buffer overflow would occur)
The behavior is undefined if the size of the character array pointed to by `dest` < `count` <= `destsz`; in other words, an erroneous value of `destsz` does not expose the impending buffer overflow. As with all bounds-checked functions, `memset_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<string.h>`. ### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the object to fill |
| ch | - | fill byte |
| count | - | number of bytes to fill |
| destsz | - | size of the destination array |
### Return value
1) A copy of `dest`
2) zero on success, non-zero on error. Also on error, if `dest` is not a null pointer and `destsz` is valid, writes `destsz` fill bytes `ch` to the destination array. ### Notes
`memset` may be optimized away (under the [as-if](../../language/as_if "c/language/as if") rules) if the object modified by this function is not accessed again for the rest of its lifetime (e.g., [gcc bug 8537](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8537)). For that reason, this function cannot be used to scrub memory (e.g., to fill an array that stored a password with zeroes). This optimization is prohibited for `memset_s`: it is guaranteed to perform the memory write. Third-party solutions for that include FreeBSD [`explicit_bzero`](https://www.freebsd.org/cgi/man.cgi?query=explicit_bzero) or Microsoft [`SecureZeroMemory`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa366877.aspx).
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char str[] = "ghghghghghghghghghghgh";
puts(str);
memset(str,'a',5);
puts(str);
#ifdef __STDC_LIB_EXT1__
set_constraint_handler_s(ignore_handler_s);
int r = memset_s(str, sizeof str, 'b', 5);
printf("str = \"%s\", r = %d\n", str, r);
r = memset_s(str, 5, 'c', 10); // count is greater than destsz
printf("str = \"%s\", r = %d\n", str, r);
#endif
}
```
Possible output:
```
ghghghghghghghghghghgh
aaaaahghghghghghghghgh
str = "bbbbbhghghghghghghghgh", r = 0
str = "ccccchghghghghghghghgh", r = 22
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.24.6.1 The memset function (p: 270)
+ K.3.7.4.1 The memset\_s function (p: 451)
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.6.1 The memset function (p: 371)
+ K.3.7.4.1 The memset\_s function (p: 621-622)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.6.1 The memset function (p: 333)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.6.1 The memset function
### See also
| | |
| --- | --- |
| [memcpymemcpy\_s](memcpy "c/string/byte/memcpy")
(C11) | copies one buffer to another (function) |
| [wmemset](../wide/wmemset "c/string/wide/wmemset")
(C95) | copies the given wide character to every position in a wide character array (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/memset "cpp/string/byte/memset") for `memset` |
c memcmp memcmp
======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
int memcmp( const void* lhs, const void* rhs, size_t count );
```
| | |
Compares the first `count` bytes of the objects pointed to by `lhs` and `rhs`. The comparison is done lexicographically.
The sign of the result is the sign of the difference between the values of the first pair of bytes (both interpreted as `unsigned char`) that differ in the objects being compared.
The behavior is undefined if access occurs beyond the end of either object pointed to by `lhs` and `rhs`. The behavior is undefined if either `lhs` or `rhs` is a null pointer.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | pointers to the objects to compare |
| count | - | number of bytes to examine |
### Return value
Negative value if `lhs` appears before `rhs` in lexicographical order.
Zero if `lhs` and `rhs` compare equal, or if count is zero.
Positive value if `lhs` appears after `rhs` in lexicographical order.
### Notes
This function reads [object representations](../../language/object "c/language/object"), not the object values, and is typically meaningful for byte arrays only: structs may have padding bytes whose values are indeterminate, the values of any bytes beyond the last stored member in a union are indeterminate, and a type may have two or more representations for the same value (different encodings for +0 and -0 or for +0.0 and –0.0, indeterminate padding bits within the type).
### Example
```
#include <stdio.h>
#include <string.h>
void demo(const char* lhs, const char* rhs, size_t sz)
{
for(size_t n = 0; n < sz; ++n)
putchar(lhs[n]);
int rc = memcmp(lhs, rhs, sz);
const char *rel = rc < 0 ? " precedes " : rc > 0 ? " follows " : " compares equal ";
fputs(rel, stdout);
for(size_t n = 0; n < sz; ++n)
putchar(rhs[n]);
puts(" in lexicographical order");
}
int main(void)
{
char a1[] = {'a','b','c'};
char a2[sizeof a1] = {'a','b','d'};
demo(a1, a2, sizeof a1);
demo(a2, a1, sizeof a1);
demo(a1, a1, sizeof a1);
}
```
Output:
```
abc precedes abd in lexicographical order
abd follows abc in lexicographical order
abc compares equal to abc in lexicographical order
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.24.4.1 The memcmp function (p: 266)
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.4.1 The memcmp function (p: 365)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.4.1 The memcmp function (p: 328)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.4.1 The memcmp function
### See also
| | |
| --- | --- |
| [strcmp](strcmp "c/string/byte/strcmp") | compares two strings (function) |
| [strncmp](strncmp "c/string/byte/strncmp") | compares a certain amount of characters of two strings (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/memcmp "cpp/string/byte/memcmp") for `memcmp` |
c strdup strdup
======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
char *strdup( const char *src );
```
| | (since C23) |
Returns a pointer to a null-terminated byte string, which is a duplicate of the string pointed to by `src`. The space for the new string is obtained as if the `[malloc](../../memory/malloc "c/memory/malloc")` was invoked. The returned pointer must be passed to `[free](../../memory/free "c/memory/free")` to avoid a memory leak.
If an error occurs, a null pointer is returned and `[errno](../../error/errno "c/error/errno")` might be set.
### Parameters
| | | |
| --- | --- | --- |
| src | - | pointer to the null-terminated byte string to duplicate |
### Return value
A pointer to the newly allocated string, or a null pointer if an error occurred.
### Notes
The function is identical to the [POSIX strdup](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strdup.html).
### Example
```
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *s1 = "Duplicate me!";
char *s2 = strdup(s1);
printf("s2 = \"%s\"\n", s2);
free(s2);
}
```
Output:
```
s2 = "Duplicate me!"
```
### See also
| | |
| --- | --- |
| [strndup](strndup "c/string/byte/strndup")
(C23) | allocates a copy of a string of specified size (function) |
| [strcpystrcpy\_s](strcpy "c/string/byte/strcpy")
(C11) | copies one string to another (function) |
| [malloc](../../memory/malloc "c/memory/malloc") | allocates memory (function) |
| [free](../../memory/free "c/memory/free") | deallocates previously allocated memory (function) |
c strtoimax, strtoumax strtoimax, strtoumax
====================
| Defined in header `<inttypes.h>` | | |
| --- | --- | --- |
|
```
intmax_t strtoimax( const char *restrict nptr,
char **restrict endptr, int base );
```
| | (since C99) |
|
```
uintmax_t strtoumax( const char *restrict nptr,
char **restrict endptr, int base );
```
| | (since C99) |
Interprets an integer value in a byte string pointed to by `nptr`.
Discards any whitespace characters (as identified by calling [`isspace`](isspace "c/string/byte/isspace")) until the first non-whitespace character is found, then takes as many characters as possible to form a valid *base-n* (where n=`base`) integer number representation and converts them to an integer value. The valid integer value consists of the following parts:
* (optional) plus or minus sign
* (optional) prefix (`0`) indicating octal base (applies only when the base is `8` or `0`)
* (optional) prefix (`0x` or `0X`) indicating hexadecimal base (applies only when the base is `16` or `0`)
* a sequence of digits
The set of valid values for base is `{0,2,3,...,36}.` The set of valid digits for base-`2` integers is `{0,1},` for base-`3` integers is `{0,1,2},` and so on. For bases larger than `10`, valid digits include alphabetic characters, starting from `Aa` for base-`11` integer, to `Zz` for base-`36` integer. The case of the characters is ignored.
Additional numeric formats may be accepted by the currently installed C [locale](../../locale/setlocale "c/locale/setlocale").
If the value of `base` is `0`, the numeric base is auto-detected: if the prefix is `0`, the base is octal, if the prefix is `0x` or `0X`, the base is hexadecimal, otherwise the base is decimal.
If the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by [unary minus](../../language/operator_arithmetic#Unary_arithmetic "c/language/operator arithmetic") in the result type.
The functions sets the pointer pointed to by `endptr` to point to the character past the last character interpreted. If `endptr` is a null pointer, it is ignored.
If the `nptr` is empty or does not have the expected form, no conversion is performed, and (if `enptr` is not a null pointer) the value of `nptr` is stored in the object pointed to by `endptr`.
### Parameters
| | | |
| --- | --- | --- |
| nptr | - | pointer to the null-terminated byte string to be interpreted |
| endptr | - | pointer to a pointer to character. |
| base | - | *base* of the interpreted integer value |
### Return value
* If successful, an integer value corresponding to the contents of `str` is returned.
* If the converted value falls out of range of corresponding return type, a range error occurs (setting `[errno](../../error/errno "c/error/errno")` to `[ERANGE](../../error/errno_macros "c/error/errno macros")`) and `[INTMAX\_MAX](../../types/integer "c/types/integer")`, `[INTMAX\_MIN](../../types/integer "c/types/integer")`, `[UINTMAX\_MAX](../../types/integer "c/types/integer")` or `0` is returned, as appropriate.
* If no conversion can be performed, `0` is returned.
### Example
```
#include <stdio.h>
#include <inttypes.h>
#include <errno.h>
#include <string.h>
int main(void)
{
char* endptr;
printf("%ld\n", strtoimax(" -123junk",&endptr,10)); /* base 10 */
printf("%ld\n", strtoimax("11111111",&endptr,2)); /* base 2 */
printf("%ld\n", strtoimax("XyZ",&endptr,36)); /* base 36 */
printf("%ld\n", strtoimax("010",&endptr,0)); /* octal auto-detection */
printf("%ld\n", strtoimax("10",&endptr,0)); /* decimal auto-detection */
printf("%ld\n", strtoimax("0x10",&endptr,0)); /* hexadecimal auto-detection */
/* range error */
/* LONG_MAX+1 --> LONG_MAX */
errno = 0;
printf("%ld\n", strtoimax("9223372036854775808",&endptr,10));
printf("%s\n", strerror(errno));
return 0;
}
```
Output:
```
-123
255
44027
8
10
16
9223372036854775807
Numerical result out of range
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.8.2.3 The strtoimax and strtoumax functions (p: 219)
* C99 standard (ISO/IEC 9899:1999):
+ 7.8.2.3 The strtoimax and strtoumax functions (p: 200)
### See also
| | |
| --- | --- |
| [wcstoimaxwcstoumax](../wide/wcstoimax "c/string/wide/wcstoimax")
(C99)(C99) | converts a wide string to `[intmax\_t](http://en.cppreference.com/w/c/types/integer)` or `[uintmax\_t](http://en.cppreference.com/w/c/types/integer)` (function) |
| [strtolstrtoll](strtol "c/string/byte/strtol")
(C99) | converts a byte string to an integer value (function) |
| [strtoul strtoull](strtoul "c/string/byte/strtoul")
(C99) | converts a byte string to an unsigned integer value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strtoimax "cpp/string/byte/strtoimax") for `strtoimax, strtoumax` |
c strtoul, strtoull strtoul, strtoull
=================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
unsigned long strtoul( const char *str, char **str_end,
int base );
```
| | (until C99) |
|
```
unsigned long strtoul( const char *restrict str, char **restrict str_end,
int base );
```
| | (since C99) |
|
```
unsigned long long strtoull( const char *restrict str, char **restrict str_end,
int base );
```
| | (since C99) |
Interprets an unsigned integer value in a byte string pointed to by `str`.
Discards any whitespace characters (as identified by calling [`isspace`](isspace "c/string/byte/isspace")) until the first non-whitespace character is found, then takes as many characters as possible to form a valid *base-n* (where n=`base`) unsigned integer number representation and converts them to an integer value. The valid unsigned integer value consists of the following parts:
* (optional) plus or minus sign
* (optional) prefix (`0`) indicating octal base (applies only when the base is `8` or `0`)
* (optional) prefix (`0x` or `0X`) indicating hexadecimal base (applies only when the base is `16` or `0`)
* a sequence of digits
The set of valid values for base is `{0,2,3,...,36}.` The set of valid digits for base-`2` integers is `{0,1},` for base-`3` integers is `{0,1,2},` and so on. For bases larger than `10`, valid digits include alphabetic characters, starting from `Aa` for base-`11` integer, to `Zz` for base-`36` integer. The case of the characters is ignored.
Additional numeric formats may be accepted by the currently installed C [locale](../../locale/setlocale "c/locale/setlocale").
If the value of `base` is `0`, the numeric base is auto-detected: if the prefix is `0`, the base is octal, if the prefix is `0x` or `0X`, the base is hexadecimal, otherwise the base is decimal.
If the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by [unary minus](../../language/operator_arithmetic#Unary_arithmetic "c/language/operator arithmetic") in the result type, which applies unsigned integer wraparound rules.
The functions sets the pointer pointed to by `str_end` to point to the character past the last character interpreted. If `str_end` is a null pointer, it is ignored.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated byte string to be interpreted |
| str\_end | - | pointer to a pointer to character. |
| base | - | *base* of the interpreted integer value |
### Return value
Integer value corresponding to the contents of `str` on success. If the converted value falls out of range of corresponding return type, range error occurs (`[errno](../../error/errno "c/error/errno")` is set to `ERANGE`) and `[ULONG\_MAX](../../types/limits "c/types/limits")` or `[ULLONG\_MAX](../../types/limits "c/types/limits")` is returned. If no conversion can be performed, `0` is returned.
### Example
```
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
int main(void)
{
const char *p = "10 200000000000000000000000000000 30 -40";
printf("Parsing '%s':\n", p);
char *end;
for (unsigned long i = strtoul(p, &end, 10);
p != end;
i = strtoul(p, &end, 10))
{
printf("'%.*s' -> ", (int)(end-p), p);
p = end;
if (errno == ERANGE){
printf("range error, got ");
errno = 0;
}
printf("%lu\n", i);
}
}
```
Output:
```
Parsing '10 200000000000000000000000000000 30 -40':
'10' -> 10
' 200000000000000000000000000000' -> range error, got 18446744073709551615
' 30' -> 30
' -40' -> 18446744073709551576
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions (p: 344-345)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.1.4 The strtol, strtoll, strtoul, and strtoull functions (p: 310-311)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.1.6 The strtoul function
### See also
| | |
| --- | --- |
| [wcstoulwcstoull](../wide/wcstoul "c/string/wide/wcstoul")
(C95)(C99) | converts a wide string to an unsigned integer value (function) |
| [atoiatolatoll](atoi "c/string/byte/atoi")
(C99) | converts a byte string to an integer value (function) |
| [strtolstrtoll](strtol "c/string/byte/strtol")
(C99) | converts a byte string to an integer value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strtoul "cpp/string/byte/strtoul") for `strtoul` |
| programming_docs |
c isspace isspace
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int isspace( int ch );
```
| | |
Checks if the given character is a whitespace character, i.e. either space (`0x20`), form feed (`0x0c`), line feed (`0x0a`), carriage return (`0x0d`), horizontal tab (`0x09`) or vertical tab (`0x0b`).
The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/c/io)`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to classify |
### Return value
Non-zero value if the character is a whitespace character, zero otherwise.
### Example
```
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
int main(void)
{
for (int ndx=0; ndx<=UCHAR_MAX; ndx++)
if (isspace(ndx)) printf("0x%02x ", ndx);
}
```
Output:
```
0x09 0x0a 0x0b 0x0c 0x0d 0x20
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.1.10 The isspace function (p: 147)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.1.10 The isspace function (p: 202-203)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.1.10 The isspace function (p: 183-184)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.1.9 The isspace function
### See also
| | |
| --- | --- |
| [iswspace](../wide/iswspace "c/string/wide/iswspace")
(C95) | checks if a wide character is a space character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/isspace "cpp/string/byte/isspace") for `isspace` |
| ASCII values | characters | [`iscntrl`](iscntrl "c/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](isprint "c/string/byte/isprint") [`iswprint`](../wide/iswprint "c/string/wide/iswprint"). | **`isspace`** [`iswspace`](../wide/iswspace "c/string/wide/iswspace"). | [`isblank`](isblank "c/string/byte/isblank") [`iswblank`](../wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](isgraph "c/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](ispunct "c/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](isalnum "c/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](isalpha "c/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](isupper "c/string/byte/isupper") [`iswupper`](../wide/iswupper "c/string/wide/iswupper"). | [`islower`](islower "c/string/byte/islower") [`iswlower`](../wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](isdigit "c/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](isxdigit "c/string/byte/isxdigit") [`iswxdigit`](../wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c strcpy, strcpy_s strcpy, strcpy\_s
=================
| Defined in header `<string.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
char *strcpy( char *dest, const char *src );
```
| (until C99) |
|
```
char *strcpy( char *restrict dest, const char *restrict src );
```
| (since C99) |
|
```
errno_t strcpy_s( char *restrict dest, rsize_t destsz, const char *restrict src );
```
| (2) | (since C11) |
1) Copies the null-terminated byte string pointed to by `src`, including the null terminator, to the character array whose first element is pointed to by `dest`.
The behavior is undefined if the `dest` array is not large enough. The behavior is undefined if the strings overlap. The behavior is undefined if either `dest` is not a pointer to a character array or `src` is not a pointer to a null-terminated byte string.
2) Same as (1), except that it may clobber the rest of the destination array with unspecified values and that the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function: * `src` or `dest` is a null pointer
* `destsz` is zero or greater than `RSIZE_MAX`
* `destsz` is less or equal `strnlen_s(src, destsz)`; in other words, truncation would occur
* overlap would occur between the source and the destination strings
The behavior is undefined if the size of the character array pointed to by `dest` <= `strnlen_s(src, destsz)` < `destsz`; in other words, an erroneous value of `destsz` does not expose the impending buffer overflow. As with all bounds-checked functions, `strcpy_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<string.h>`. ### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the character array to write to |
| src | - | pointer to the null-terminated byte string to copy from |
| destsz | - | maximum number of characters to write, typically the size of the destination buffer |
### Return value
1) returns a copy of `dest`
2) returns zero on success, returns non-zero on error. Also, on error, writes zero to `dest[0]` (unless `dest` is a null pointer or `destsz` is zero or greater than `RSIZE_MAX`). ### Notes
`strcpy_s` is allowed to clobber the destination array from the last character written up to `destsz` in order to improve efficiency: it may copy in multibyte blocks and then check for null bytes.
The function `strcpy_s` is similar to the BSD function `strlcpy`, except that.
* `strlcpy` truncates the source string to fit in the destination (which is a security risk)
* `strlcpy` does not perform all the runtime checks that `strcpy_s` does
* `strlcpy` does not make failures obvious by setting the destination to a null string or calling a handler if the call fails.
Although `strcpy_s` prohibits truncation due to potential security risks, it's possible to truncate a string using bounds-checked `[strncpy\_s](strncpy "c/string/byte/strncpy")` instead.
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *src = "Take the test.";
// src[0] = 'M' ; // this would be undefined behavior
char dst[strlen(src) + 1]; // +1 to accomodate for the null terminator
strcpy(dst, src);
dst[0] = 'M'; // OK
printf("src = %s\ndst = %s\n", src, dst);
#ifdef __STDC_LIB_EXT1__
set_constraint_handler_s(ignore_handler_s);
int r = strcpy_s(dst, sizeof dst, src);
printf("dst = \"%s\", r = %d\n", dst, r);
r = strcpy_s(dst, sizeof dst, "Take even more tests.");
printf("dst = \"%s\", r = %d\n", dst, r);
#endif
}
```
Possible output:
```
src = Take the test.
dst = Make the test.
dst = "Take the test.", r = 0
dst = "", r = 22
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.24.2.3 The strcpy function (p: 264-265)
+ K.3.7.1.3 The strcpy\_s function (p: 447)
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.2.3 The strcpy function (p: 363)
+ K.3.7.1.3 The strcpy\_s function (p: 615-616)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.2.3 The strcpy function (p: 326)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.2.3 The strcpy function
### See also
| | |
| --- | --- |
| [strncpystrncpy\_s](strncpy "c/string/byte/strncpy")
(C11) | copies a certain amount of characters from one string to another (function) |
| [memcpymemcpy\_s](memcpy "c/string/byte/memcpy")
(C11) | copies one buffer to another (function) |
| [wcscpywcscpy\_s](../wide/wcscpy "c/string/wide/wcscpy")
(C95)(C11) | copies one wide string to another (function) |
| [strdup](https://en.cppreference.com/w/c/experimental/dynamic/strdup "c/experimental/dynamic/strdup")
(dynamic memory TR) | allocate a copy of a string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strcpy "cpp/string/byte/strcpy") for `strcpy` |
c isupper isupper
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int isupper( int ch );
```
| | |
Checks if the given character is an uppercase character according to the current C locale. In the default "C" locale, `isupper` returns true only for the uppercase letters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`).
If `isupper` returns `true`, it is guaranteed that `[iscntrl](iscntrl "c/string/byte/iscntrl")`, `[isdigit](isdigit "c/string/byte/isdigit")`, `[ispunct](ispunct "c/string/byte/ispunct")`, and `[isspace](isspace "c/string/byte/isspace")` return `false` for the same character in the same C locale.
The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/c/io)`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to classify |
### Return value
Non-zero value if the character is an uppercase letter, zero otherwise.
### Example
```
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
int main(void)
{
unsigned char c = '\xc6'; // letter Æ in ISO-8859-1
printf("In the default C locale, \\xc6 is %suppercase\n",
isupper(c) ? "" : "not " );
setlocale(LC_ALL, "en_GB.iso88591");
printf("In ISO-8859-1 locale, \\xc6 is %suppercase\n",
isupper(c) ? "" : "not " );
}
```
Possible output:
```
In the default C locale, \xc6 is not uppercase
In ISO-8859-1 locale, \xc6 is uppercase
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.1.11 The isupper function (p: 147)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.1.11 The isupper function (p: 203)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.1.11 The isupper function (p: 184)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.1.10 The isupper function
### See also
| | |
| --- | --- |
| [iswupper](../wide/iswupper "c/string/wide/iswupper")
(C95) | checks if a wide character is an uppercase character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/isupper "cpp/string/byte/isupper") for `isupper` |
| ASCII values | characters | [`iscntrl`](iscntrl "c/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](isprint "c/string/byte/isprint") [`iswprint`](../wide/iswprint "c/string/wide/iswprint"). | [`isspace`](isspace "c/string/byte/isspace") [`iswspace`](../wide/iswspace "c/string/wide/iswspace"). | [`isblank`](isblank "c/string/byte/isblank") [`iswblank`](../wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](isgraph "c/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](ispunct "c/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](isalnum "c/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](isalpha "c/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "c/string/wide/iswalpha"). | **`isupper`** [`iswupper`](../wide/iswupper "c/string/wide/iswupper"). | [`islower`](islower "c/string/byte/islower") [`iswlower`](../wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](isdigit "c/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](isxdigit "c/string/byte/isxdigit") [`iswxdigit`](../wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c strerror, strerror_s, strerrorlen_s strerror, strerror\_s, strerrorlen\_s
=====================================
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
char* strerror( int errnum );
```
| (1) | |
|
```
errno_t strerror_s( char *buf, rsize_t bufsz, errno_t errnum );
```
| (2) | (since C11) |
|
```
size_t strerrorlen_s( errno_t errnum );
```
| (3) | (since C11) |
1) Returns a pointer to the textual description of the system error code `errnum`, identical to the description that would be printed by `[perror()](../../io/perror "c/io/perror")`.
`errnum` is usually acquired from the `errno` variable, however the function accepts any value of type `int`. The contents of the string are locale-specific.
The returned string must not be modified by the program, but may be overwritten by a subsequent call to the `strerror` function. `strerror` is not required to be thread-safe. Implementations may be returning different pointers to static read-only string literals or may be returning the same pointer over and over, pointing at a static buffer in which strerror places the string.
2) Same as (1), except that the message is copied into user-provided storage `buf`. No more than `bufsz-1` bytes are written, the buffer is always null-terminated. If the message had to be truncated to fit the buffer and `bufsz` is greater than 3, then only `bufsz-4` bytes are written, and the characters `"..."` are appended before the null terminator. In addition, the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function: * `buf` is a null pointer
* `bufsz` is zero or greater than `RSIZE_MAX`
The behavior is undefined if writing to `buf` occurs past the end of the array, which can happen when the size of the buffer pointed to by `buf` is less than the number of characters in the error message which in turn is less than `bufsz`.
3) Computes the length of the untruncated locale-specific error message that `strerror_s` would write if it were called with `errnum`. The length does not include the null terminator. As with all bounds-checked functions, `strerror_s` and `strerrorlen_s` are only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<string.h>`. ### Parameters
| | | |
| --- | --- | --- |
| errnum | - | integral value referring to an error code |
| buf | - | pointer to a user-provided buffer |
| bufsz | - | size of the user-provided buffer |
### Return value
1) Pointer to a null-terminated byte string corresponding to the `[errno](../../error/errno "c/error/errno")` error code `errnum`.
2) Zero if the entire message was successfully stored in `buf`, non-zero otherwise.
3) Length (not including the null terminator) of the message that `strerror_s` would return ### Notes
[POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strerror.html) allows subsequent calls to `strerror` to invalidate the pointer value returned by an earlier call. It also specifies that it is the [`LC_MESSAGES`](../../locale/lc_categories "c/locale/LC categories") locale facet that controls the contents of these messages.
`strerror_s` is the only bounds-checked function that allows truncation, because providing as much information as possible about a failure was deemed to be more desirable. POSIX also defines [`strerror_r`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strerror.html) for similar purposes.
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <locale.h>
int main(void)
{
FILE *fp = fopen(tmpnam((char[L_tmpnam]){0}), "r");
if(fp==NULL) {
printf("File opening error: %s\n", strerror(errno));
setlocale(LC_MESSAGES, "de_DE.utf8");
printf("Now in German: %s\n", strerror(errno));
#ifdef __STDC_LIB_EXT1__
setlocale(LC_ALL, "ja_JP.utf8"); // printf needs CTYPE for multibyte output
size_t errmsglen = strerrorlen_s(errno) + 1;
char errmsg[errmsglen];
strerror_s(errmsg, errmsglen, errno);
printf("Now in Japanese: %s\n", errmsg);
#endif
}
}
```
Possible output:
```
File opening error: No such file or directory
Now in German: Datei oder Verzeichnis nicht gefunden
Now in Japanese: そのようなファイル、又はディレクトリはありません
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.6.2 The strerror function (p: 371)
+ K.3.7.4.2 The strerror\_s function (p: 622)
+ K.3.7.4.3 The strerrorlen\_s function (p: 623)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.6.2 The strerror function (p: 334)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.6.2 The strerror function
### See also
| | |
| --- | --- |
| [perror](../../io/perror "c/io/perror") | displays a character string corresponding of the current error to `[stderr](../../io/std_streams "c/io/std streams")` (function) |
| [errno](../../error/errno "c/error/errno") | macro which expands to POSIX-compatible thread-local error number variable(macro variable) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strerror "cpp/string/byte/strerror") for `strerror` |
| programming_docs |
c ispunct ispunct
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int ispunct( int ch );
```
| | |
Checks if the given character is a punctuation character in the current C locale. The default C locale classifies the characters `!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~` as punctuation.
The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/c/io)`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to classify |
### Return value
Non-zero value if the character is a punctuation character, zero otherwise.
### Example
```
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
int main(void)
{
unsigned char c = '\xd7'; // the character × (multiplication sign) in ISO-8859-1
printf("In the default C locale, \\xd7 is %spunctuation\n",
ispunct(c) ? "" : "not " );
setlocale(LC_ALL, "en_GB.iso88591");
printf("In ISO-8859-1 locale, \\xd7 is %spunctuation\n",
ispunct(c) ? "" : "not " );
}
```
Possible output:
```
In the default C locale, \xd7 is not punctuation
In ISO-8859-1 locale, \xd7 is punctuation
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.1.9 The ispunct function (p: 146)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.1.9 The ispunct function (p: 202)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.1.9 The ispunct function (p: 183)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.1.8 The ispunct function
### See also
| | |
| --- | --- |
| [iswpunct](../wide/iswpunct "c/string/wide/iswpunct")
(C95) | checks if a wide character is a punctuation character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/ispunct "cpp/string/byte/ispunct") for `ispunct` |
| ASCII values | characters | [`iscntrl`](iscntrl "c/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](isprint "c/string/byte/isprint") [`iswprint`](../wide/iswprint "c/string/wide/iswprint"). | [`isspace`](isspace "c/string/byte/isspace") [`iswspace`](../wide/iswspace "c/string/wide/iswspace"). | [`isblank`](isblank "c/string/byte/isblank") [`iswblank`](../wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](isgraph "c/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "c/string/wide/iswgraph"). | **`ispunct`** [`iswpunct`](../wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](isalnum "c/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](isalpha "c/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](isupper "c/string/byte/isupper") [`iswupper`](../wide/iswupper "c/string/wide/iswupper"). | [`islower`](islower "c/string/byte/islower") [`iswlower`](../wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](isdigit "c/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](isxdigit "c/string/byte/isxdigit") [`iswxdigit`](../wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c iscntrl iscntrl
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int iscntrl( int ch );
```
| | |
Checks if the given character is a control character, i.e. codes `0x00-0x1F` and `0x7F`.
The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/c/io)`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to classify |
### Return value
Non-zero value if the character is a control character, zero otherwise.
### Example
```
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
int main(void)
{
unsigned char c = '\x94'; // the control code CCH in ISO-8859-1
printf("In the default C locale, \\x94 is %sa control character\n",
iscntrl(c) ? "" : "not " );
setlocale(LC_ALL, "en_GB.iso88591");
printf("In ISO-8859-1 locale, \\x94 is %sa control character\n",
iscntrl(c) ? "" : "not " );
}
```
Possible output:
```
In the default C locale, \x94 is not a control character
In ISO-8859-1 locale, \x94 is a control character
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.1.4 The iscntrl function (p: 146)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.1.4 The iscntrl function (p: 201)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.1.4 The iscntrl function (p: 182)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.1.3 The iscntrl function
### See also
| | |
| --- | --- |
| [iswcntrl](../wide/iswcntrl "c/string/wide/iswcntrl")
(C95) | checks if a wide character is a control character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/iscntrl "cpp/string/byte/iscntrl") for `iscntrl` |
| ASCII values | characters | **`iscntrl`** [`iswcntrl`](../wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](isprint "c/string/byte/isprint") [`iswprint`](../wide/iswprint "c/string/wide/iswprint"). | [`isspace`](isspace "c/string/byte/isspace") [`iswspace`](../wide/iswspace "c/string/wide/iswspace"). | [`isblank`](isblank "c/string/byte/isblank") [`iswblank`](../wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](isgraph "c/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](ispunct "c/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](isalnum "c/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](isalpha "c/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](isupper "c/string/byte/isupper") [`iswupper`](../wide/iswupper "c/string/wide/iswupper"). | [`islower`](islower "c/string/byte/islower") [`iswlower`](../wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](isdigit "c/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](isxdigit "c/string/byte/isxdigit") [`iswxdigit`](../wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c strcoll strcoll
=======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
int strcoll( const char *lhs, const char *rhs );
```
| | |
Compares two null-terminated byte strings according to the current locale as defined by the `[LC\_COLLATE](../../locale/lc_categories "c/locale/LC categories")` category.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | pointers to the null-terminated byte strings to compare |
### Return value
Negative value if `lhs` is *less than* (precedes) `rhs`.
`0` if `lhs` is *equal to* `rhs`.
Positive value if `lhs` is *greater than* (follows) `rhs`.
### Notes
Collation order is the dictionary order: the position of the letter in the national alphabet (its *equivalence class*) has higher priority than its case or variant. Within an equivalence class, lowercase characters collate before their uppercase equivalents and locale-specific order may apply to the characters with diacritics. In some locales, groups of characters compare as single *collation units*. For example, `"ch"` in Czech follows `"h"` and precedes `"i"`, and `"dzs"` in Hungarian follows `"dz"` and precedes `"g"`.
### Example
```
#include <stdio.h>
#include <string.h>
#include <locale.h>
int main(void)
{
setlocale(LC_COLLATE, "cs_CZ.iso88592");
const char* s1 = "hrnec";
const char* s2 = "chrt";
printf("In the Czech locale: ");
if(strcoll(s1, s2) < 0)
printf("%s before %s\n", s1, s2);
else
printf("%s before %s\n", s2, s1);
printf("In lexicographical comparison: ");
if(strcmp(s1, s2) < 0)
printf("%s before %s\n", s1, s2);
else
printf("%s before %s\n", s2, s1);
}
```
Output:
```
In the Czech locale: hrnec before chrt
In lexicographical comparison: chrt before hrnec
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.4.3 The strcoll function (p: 366)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.4.3 The strcoll function (p: 329)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.4.3 The strcoll function
### See also
| | |
| --- | --- |
| [wcscoll](../wide/wcscoll "c/string/wide/wcscoll")
(C95) | compares two wide strings in accordance to the current locale (function) |
| [strxfrm](strxfrm "c/string/byte/strxfrm") | transform a string so that strcmp would produce the same result as strcoll (function) |
| [wcsxfrm](../wide/wcsxfrm "c/string/wide/wcsxfrm")
(C95) | transform a wide string so that wcscmp would produce the same result as wcscoll (function) |
| [strcmp](strcmp "c/string/byte/strcmp") | compares two strings (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strcoll "cpp/string/byte/strcoll") for `strcoll` |
c isdigit isdigit
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int isdigit( int ch );
```
| | |
Checks if the given character is a numeric character (`0123456789`).
The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/c/io)`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to classify |
### Return value
Non-zero value if the character is a numeric character, zero otherwise.
### Notes
`isdigit` and `isxdigit` are the only standard narrow character classification functions that are not affected by the currently installed C locale, although some implementations (e.g. Microsoft in 1252 codepage) may classify additional single-byte characters as digits.
### Example
```
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
int main(void)
{
for (int ndx=0; ndx<=UCHAR_MAX; ndx++)
if (isdigit(ndx)) printf("%c", ndx);
printf("\n");
}
```
Output:
```
0123456789
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.1.5 The isdigit function (p: 146)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.1.5 The isdigit function (p: 201)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.1.5 The isdigit function (p: 182)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.1.4 The isdigit function
### See also
| | |
| --- | --- |
| [iswdigit](../wide/iswdigit "c/string/wide/iswdigit")
(C95) | checks if a wide character is a digit (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/isdigit "cpp/string/byte/isdigit") for `isdigit` |
| ASCII values | characters | [`iscntrl`](iscntrl "c/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](isprint "c/string/byte/isprint") [`iswprint`](../wide/iswprint "c/string/wide/iswprint"). | [`isspace`](isspace "c/string/byte/isspace") [`iswspace`](../wide/iswspace "c/string/wide/iswspace"). | [`isblank`](isblank "c/string/byte/isblank") [`iswblank`](../wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](isgraph "c/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](ispunct "c/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](isalnum "c/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](isalpha "c/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](isupper "c/string/byte/isupper") [`iswupper`](../wide/iswupper "c/string/wide/iswupper"). | [`islower`](islower "c/string/byte/islower") [`iswlower`](../wide/iswlower "c/string/wide/iswlower"). | **`isdigit`** [`iswdigit`](../wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](isxdigit "c/string/byte/isxdigit") [`iswxdigit`](../wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| programming_docs |
c strpbrk strpbrk
=======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
char* strpbrk( const char* dest, const char* breakset );
```
| | |
Scans the null-terminated byte string pointed to by `dest` for any character from the null-terminated byte string pointed to by `breakset`, and returns a pointer to that character.
The behavior is undefined if either `dest` or `breakset` is not a pointer to a null-terminated byte string.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated byte string to be analyzed |
| breakset | - | pointer to the null-terminated byte string that contains the characters to search for |
### Return value
Pointer to the first character in `dest`, that is also in `breakset`, or null pointer if no such character exists.
### Notes
The name stands for "string pointer break", because it returns a pointer to the first of the separator ("break") characters.
### Example
```
#include <stdio.h>
#include <string.h>
int main(void)
{
const char* str = "hello world, friend of mine!";
const char* sep = " ,!";
unsigned int cnt = 0;
do {
str = strpbrk(str, sep); // find separator
if(str) str += strspn(str, sep); // skip separator
++cnt; // increment word count
} while(str && *str);
printf("There are %u words\n", cnt);
}
```
Output:
```
There are 5 words
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.5.4 The strpbrk function (p: 368)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.5.4 The strpbrk function (p: 331)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.5.4 The strpbrk function
### See also
| | |
| --- | --- |
| [strcspn](strcspn "c/string/byte/strcspn") | returns the length of the maximum initial segment that consists of only the characters not found in another byte string (function) |
| [strchr](strchr "c/string/byte/strchr") | finds the first occurrence of a character (function) |
| [strtokstrtok\_s](strtok "c/string/byte/strtok")
(C11) | finds the next token in a byte string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strpbrk "cpp/string/byte/strpbrk") for `strpbrk` |
c strncmp strncmp
=======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
int strncmp( const char *lhs, const char *rhs, size_t count );
```
| | |
Compares at most `count` characters of two possibly null-terminated arrays. The comparison is done lexicographically. Characters following the null character are not compared.
The sign of the result is the sign of the difference between the values of the first pair of characters (both interpreted as `unsigned char`) that differ in the arrays being compared.
The behavior is undefined when access occurs past the end of either array `lhs` or `rhs`. The behavior is undefined when either `lhs` or `rhs` is the null pointer.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | pointers to the possibly null-terminated arrays to compare |
| count | - | maximum number of characters to compare |
### Return value
Negative value if `lhs` appears before `rhs` in lexicographical order.
Zero if `lhs` and `rhs` compare equal, or if count is zero.
Positive value if `lhs` appears after `rhs` in lexicographical order.
### Notes
This function is not locale-sensitive, unlike `[strcoll](strcoll "c/string/byte/strcoll")` and `[strxfrm](strxfrm "c/string/byte/strxfrm")`.
### Example
```
#include <string.h>
#include <stdio.h>
void demo(const char* lhs, const char* rhs, int sz)
{
int rc = strncmp(lhs, rhs, sz);
if(rc == 0)
printf("First %d chars of [%s] equal [%s]\n", sz, lhs, rhs);
else if(rc < 0)
printf("First %d chars of [%s] precede [%s]\n", sz, lhs, rhs);
else if(rc > 0)
printf("First %d chars of [%s] follow [%s]\n", sz, lhs, rhs);
}
int main(void)
{
const char* string = "Hello World!";
demo(string, "Hello!", 5);
demo(string, "Hello", 10);
demo(string, "Hello there", 10);
demo("Hello, everybody!" + 12, "Hello, somebody!" + 11, 5);
}
```
Output:
```
First 5 chars of [Hello World!] equal [Hello!]
First 10 chars of [Hello World!] follow [Hello]
First 10 chars of [Hello World!] precede [Hello there]
First 5 chars of [body!] equal [body!]
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.4.4 The strncmp function (p: 366)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.4.4 The strncmp function (p: 329)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.4.4 The strncmp function
### See also
| | |
| --- | --- |
| [strcmp](strcmp "c/string/byte/strcmp") | compares two strings (function) |
| [wcsncmp](../wide/wcsncmp "c/string/wide/wcsncmp")
(C95) | compares a certain amount of characters from two wide strings (function) |
| [memcmp](memcmp "c/string/byte/memcmp") | compares two buffers (function) |
| [strcoll](strcoll "c/string/byte/strcoll") | compares two strings in accordance to the current locale (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strncmp "cpp/string/byte/strncmp") for `strncmp` |
c strxfrm strxfrm
=======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
size_t strxfrm( char *dest, const char *src, size_t count );
```
| | (until C99) |
|
```
size_t strxfrm( char *restrict dest, const char *restrict src, size_t count );
```
| | (since C99) |
Transforms the null-terminated byte string pointed to by `src` into the implementation-defined form such that comparing two transformed strings with `[strcmp](strcmp "c/string/byte/strcmp")` gives the same result as comparing the original strings with `[strcoll](strcoll "c/string/byte/strcoll")`, in the current C locale.
The first `count` characters of the transformed string are written to destination, including the terminating null character, and the length of the full transformed string is returned, excluding the terminating null character.
The behavior is undefined if the `dest` array is not large enough. The behavior is undefined if `dest` and `src` overlap.
If `count` is `0`, then `dest` is allowed to be a null pointer.
### Notes
The correct length of the buffer that can receive the entire transformed string is `1+strxfrm([NULL](http://en.cppreference.com/w/c/types/NULL), src, 0)`.
This function is used when making multiple locale-dependent comparisons using the same string or set of strings, because it is more efficient to use `strxfrm` to transform all the strings just once, and subsequently compare the transformed strings with `[strcmp](strcmp "c/string/byte/strcmp")`.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the first element of the array where the transformed string will be written |
| src | - | pointer to the first character of a null-terminated byte string to transform |
| count | - | maximum number of characters to be written |
### Return value
The length of the transformed string, not including the terminating null-character.
### Example
```
#include <stdio.h>
#include <string.h>
#include <locale.h>
int main(void)
{
setlocale(LC_COLLATE, "cs_CZ.iso88592");
const char *in1 = "hrnec";
char out1[1+strxfrm(NULL, in1, 0)];
strxfrm(out1, in1, sizeof out1);
const char *in2 = "chrt";
char out2[1+strxfrm(NULL, in2, 0)];
strxfrm(out2, in2, sizeof out2);
printf("In the Czech locale: ");
if(strcmp(out1, out2) < 0)
printf("%s before %s\n",in1, in2);
else
printf("%s before %s\n",in2, in1);
printf("In lexicographical comparison: ");
if(strcmp(in1, in2)<0)
printf("%s before %s\n",in1, in2);
else
printf("%s before %s\n",in2, in1);
}
```
Possible output:
```
In the Czech locale: hrnec before chrt
In lexicographical comparison: chrt before hrnec
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.24.4.5 The strxfrm function (p: 267)
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.4.5 The strxfrm function (p: 366-367)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.4.5 The strxfrm function (p: 329-330)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.4.5 The strxfrm function
### See also
| | |
| --- | --- |
| [strcoll](strcoll "c/string/byte/strcoll") | compares two strings in accordance to the current locale (function) |
| [wcscoll](../wide/wcscoll "c/string/wide/wcscoll")
(C95) | compares two wide strings in accordance to the current locale (function) |
| [strcmp](strcmp "c/string/byte/strcmp") | compares two strings (function) |
| [wcsxfrm](../wide/wcsxfrm "c/string/wide/wcsxfrm")
(C95) | transform a wide string so that wcscmp would produce the same result as wcscoll (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strxfrm "cpp/string/byte/strxfrm") for `strxfrm` |
c atof atof
====
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
double atof( const char* str );
```
| | |
Interprets a floating-point value in a byte string pointed to by `str`.
Function discards any whitespace characters (as determined by `std::[isspace](http://en.cppreference.com/w/c/string/byte/isspace)()`) until first non-whitespace character is found. Then it takes as many characters as possible to form a valid floating-point representation and converts them to a floating-point value. The valid floating-point value can be one of the following:
* decimal floating-point expression. It consists of the following parts:
+ (optional) plus or minus sign
+ nonempty sequence of decimal digits optionally containing decimal-point character (as determined by the current C [locale](../../locale/setlocale "c/locale/setlocale")) (defines significand)
+ (optional) `e` or `E` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 10)
| | |
| --- | --- |
| * hexadecimal floating-point expression. It consists of the following parts:
+ (optional) plus or minus sign
+ `0x` or `0X`
+ nonempty sequence of hexadecimal digits optionally containing a decimal-point character (as determined by the current C [locale](../../locale/setlocale "c/locale/setlocale")) (defines significand)
+ (optional) `p` or `P` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 2)
* infinity expression. It consists of the following parts:
+ (optional) plus or minus sign
+ `INF` or `INFINITY` ignoring case
* not-a-number expression. It consists of the following parts:
+ (optional) plus or minus sign
+ `NAN` or `NAN(`*char\_sequence*`)` ignoring case of the `NAN` part. *char\_sequence* can only contain digits, Latin letters, and underscores. The result is a quiet NaN floating-point value.
| (since C99) |
* any other expression that may be accepted by the currently installed C [locale](../../locale/setlocale "c/locale/setlocale")
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated byte string to be interpreted |
### Return value
`double` value corresponding to the contents of `str` on success. If the converted value falls out of range of the return type, the return value is undefined. If no conversion can be performed, `0.0` is returned.
### Notes
The name stands for "ASCII to float".
### Example
```
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
printf("%g\n", atof(" -0.0000000123junk"));
printf("%g\n", atof("0.012"));
printf("%g\n", atof("15e16"));
printf("%g\n", atof("-0x1afp-2"));
printf("%g\n", atof("inF"));
printf("%g\n", atof("Nan"));
printf("%g\n", atof("1.0e+309")); // UB: out of range of double
printf("%g\n", atof("0.0"));
printf("%g\n", atof("junk")); // no conversion can be performed
}
```
Possible output:
```
-1.23e-08
0.012
1.5e+17
-107.75
inf
nan
inf
0
0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.1.1 The atof function (p: 341)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.1.1 The atof function (p: 307)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.1.1 The atof function
### See also
| | |
| --- | --- |
| [strtofstrtodstrtold](strtof "c/string/byte/strtof")
(C99)(C99) | converts a byte string to a floating point value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/atof "cpp/string/byte/atof") for `atof` |
c memchr memchr
======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
void* memchr( const void* ptr, int ch, size_t count );
```
| | |
Finds the first occurrence of `(unsigned char)ch` in the initial `count` bytes (each interpreted as `unsigned char`) of the object pointed to by `ptr`.
The behavior is undefined if access occurs beyond the end of the array searched. The behavior is undefined if `ptr` is a null pointer.
| | |
| --- | --- |
| This function behaves as if it reads the bytes sequentially and stops as soon as a matching bytes is found: if the array pointed to by `ptr` is smaller than `count`, but the match is found within the array, the behavior is well-defined. | (since C11) |
### Parameters
| | | |
| --- | --- | --- |
| ptr | - | pointer to the object to be examined |
| ch | - | bytes to search for |
| count | - | max number of bytes to examine |
### Return value
Pointer to the location of the byte, or a null pointer if no such byte is found.
### Example
```
#include <stdio.h>
#include <string.h>
int main(void)
{
const char str[] = "ABCDEFG";
const int chars[] = {'D', 'd'};
for (size_t i = 0; i < sizeof chars / (sizeof chars[0]); ++i)
{
const int c = chars[i];
const char *ps = memchr(str, c, strlen(str));
ps ? printf ("character '%c'(%i) found: %s\n", c, c, ps)
: printf ("character '%c'(%i) not found\n", c, c);
}
return 0;
}
```
Possible output:
```
character 'D'(68) found: DEFG
character 'd'(100) not found
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.24.5.1 The memchr function (p: 267-268)
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.5.1 The memchr function (p: 367)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.5.1 The memchr function (p: 330)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.5.1 The memchr function
### See also
| | |
| --- | --- |
| [strchr](strchr "c/string/byte/strchr") | finds the first occurrence of a character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/memchr "cpp/string/byte/memchr") for `memchr` |
c strcspn strcspn
=======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
size_t strcspn( const char *dest, const char *src );
```
| | |
Returns the length of the maximum initial segment of the null-terminated byte string pointed to by `dest`, that consists of only the characters *not* found in the null-terminated byte string pointed to by `src`.
The behavior is undefined if either `dest` or `src` is not a pointer to a null-terminated byte string.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated byte string to be analyzed |
| src | - | pointer to the null-terminated byte string that contains the characters to search for |
### Return value
The length of the maximum initial segment that contains only characters not found in the null-terminated byte string pointed to by `src`.
### Notes
The function name stands for "complementary span" because the function searches for characters not found in `src`, that is the complement of `src`.
### Example
```
#include <string.h>
#include <stdio.h>
int main(void)
{
const char *string = "abcde312$#@";
const char *invalid = "*$#";
size_t valid_len = strcspn(string, invalid);
if(valid_len != strlen(string))
printf("'%s' contains invalid chars starting at position %zu\n",
string, valid_len);
}
```
Output:
```
'abcde312$#@' contains invalid chars starting at position 8
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.5.3 The strcspn function (p: 368)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.5.3 The strcspn function (p: 331)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.5.3 The strcspn function
### See also
| | |
| --- | --- |
| [strspn](strspn "c/string/byte/strspn") | returns the length of the maximum initial segment that consists of only the characters found in another byte string (function) |
| [wcscspn](../wide/wcscspn "c/string/wide/wcscspn")
(C95) | returns the length of the maximum initial segment that consists of only the wide chars *not* found in another wide string (function) |
| [strpbrk](strpbrk "c/string/byte/strpbrk") | finds the first location of any character in one string, in another string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strcspn "cpp/string/byte/strcspn") for `strcspn` |
c isalpha isalpha
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int isalpha( int ch );
```
| | |
Checks if the given character is an alphabetic character, i.e. either an uppercase letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`), or a lowercase letter (`abcdefghijklmnopqrstuvwxyz`).
In locales other than `"C"`, an alphabetic character is a character for which `[isupper()](isupper "c/string/byte/isupper")` or `[islower()](islower "c/string/byte/islower")` returns `true` or any other character considered alphabetic by the locale. In any case, `[iscntrl()](iscntrl "c/string/byte/iscntrl")`, `[isdigit()](isdigit "c/string/byte/isdigit")`, `[ispunct()](ispunct "c/string/byte/ispunct")` and `[isspace()](isspace "c/string/byte/isspace")` will return `false` for this character.
The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/c/io)`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to classify |
### Return value
Non-zero value if the character is an alphabetic character, zero otherwise.
### Example
Demonstrates the use of `isalpha` with different locales (OS-specific).
```
#include <ctype.h>
#include <stdio.h>
#include <locale.h>
int main(void)
{
unsigned char c = '\xdf'; // German letter ß in ISO-8859-1
printf("isalpha('\\xdf') in default C locale returned %d\n", !!isalpha(c));
setlocale(LC_CTYPE, "de_DE.iso88591");
printf("isalpha('\\xdf') in ISO-8859-1 locale returned %d\n", !!isalpha(c));
}
```
Possible output:
```
isalpha('\xdf') in default C locale returned 0
isalpha('\xdf') in ISO-8859-1 locale returned 1
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.1.2 The isalpha function (p: 145)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.1.2 The isalpha function (p: 200-201)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.1.2 The isalpha function (p: 181-182)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.1.2 The isalpha function
### See also
| | |
| --- | --- |
| [iswalpha](../wide/iswalpha "c/string/wide/iswalpha")
(C95) | checks if a wide character is alphabetic (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/isalpha "cpp/string/byte/isalpha") for `isalpha` |
| ASCII values | characters | [`iscntrl`](iscntrl "c/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](isprint "c/string/byte/isprint") [`iswprint`](../wide/iswprint "c/string/wide/iswprint"). | [`isspace`](isspace "c/string/byte/isspace") [`iswspace`](../wide/iswspace "c/string/wide/iswspace"). | [`isblank`](isblank "c/string/byte/isblank") [`iswblank`](../wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](isgraph "c/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](ispunct "c/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](isalnum "c/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "c/string/wide/iswalnum"). | **`isalpha`** [`iswalpha`](../wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](isupper "c/string/byte/isupper") [`iswupper`](../wide/iswupper "c/string/wide/iswupper"). | [`islower`](islower "c/string/byte/islower") [`iswlower`](../wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](isdigit "c/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](isxdigit "c/string/byte/isxdigit") [`iswxdigit`](../wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| programming_docs |
c isgraph isgraph
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int isgraph( int ch );
```
| | |
Checks if the given character has a graphical representation, i.e. it is either a number (`0123456789`), an uppercase letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`), a lowercase letter (`abcdefghijklmnopqrstuvwxyz`), or a punctuation character(`!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`), or any graphical character specific to the current C locale.
The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/c/io)`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to classify |
### Return value
Non-zero value if the character has a graphical representation character, zero otherwise.
### Example
```
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
int main(void)
{
unsigned char c = '\xb6'; // the character ¶ in ISO-8859-1
printf("In the default C locale, \\xb6 is %sgraphical\n",
isgraph(c) ? "" : "not " );
setlocale(LC_ALL, "en_GB.iso88591");
printf("In ISO-8859-1 locale, \\xb6 is %sgraphical\n",
isgraph(c) ? "" : "not " );
}
```
Possible output:
```
In the default C locale, \xb6 is not graphical
In ISO-8859-1 locale, \xb6 is graphical
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.1.6 The isgraph function (p: 146)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.1.6 The isgraph function (p: 201-202)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.1.6 The isgraph function (p: 182-183)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.1.5 The isgraph function
### See also
| | |
| --- | --- |
| [iswgraph](../wide/iswgraph "c/string/wide/iswgraph")
(C95) | checks if a wide character is a graphical character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/isgraph "cpp/string/byte/isgraph") for `isgraph` |
| ASCII values | characters | [`iscntrl`](iscntrl "c/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](isprint "c/string/byte/isprint") [`iswprint`](../wide/iswprint "c/string/wide/iswprint"). | [`isspace`](isspace "c/string/byte/isspace") [`iswspace`](../wide/iswspace "c/string/wide/iswspace"). | [`isblank`](isblank "c/string/byte/isblank") [`iswblank`](../wide/iswblank "c/string/wide/iswblank"). | **`isgraph`** [`iswgraph`](../wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](ispunct "c/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](isalnum "c/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](isalpha "c/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](isupper "c/string/byte/isupper") [`iswupper`](../wide/iswupper "c/string/wide/iswupper"). | [`islower`](islower "c/string/byte/islower") [`iswlower`](../wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](isdigit "c/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](isxdigit "c/string/byte/isxdigit") [`iswxdigit`](../wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c strspn strspn
======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
size_t strspn( const char *dest, const char *src );
```
| | |
Returns the length of the maximum initial segment (span) of the null-terminated byte string pointed to by `dest`, that consists of only the characters found in the null-terminated byte string pointed to by `src`.
The behavior is undefined if either `dest` or `src` is not a pointer to a null-terminated byte string.
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated byte string to be analyzed |
| src | - | pointer to the null-terminated byte string that contains the characters to search for |
### Return value
The length of the maximum initial segment that contains only characters from the null-terminated byte string pointed to by `src`.
### Example
```
#include <string.h>
#include <stdio.h>
int main(void)
{
const char *string = "abcde312$#@";
const char *low_alpha = "qwertyuiopasdfghjklzxcvbnm";
size_t spnsz = strspn(string, low_alpha);
printf("After skipping initial lowercase letters from '%s'\n"
"The remainder is '%s'\n", string, string+spnsz);
}
```
Output:
```
After skipping initial lowercase letters from 'abcde312$#@'
The remainder is '312$#@'
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.5.6 The strspn function (p: 369)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.5.6 The strspn function (p: 332)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.5.6 The strspn function
### See also
| | |
| --- | --- |
| [strcspn](strcspn "c/string/byte/strcspn") | returns the length of the maximum initial segment that consists of only the characters not found in another byte string (function) |
| [wcsspn](../wide/wcsspn "c/string/wide/wcsspn")
(C95) | returns the length of the maximum initial segment that consists of only the wide characters found in another wide string (function) |
| [strpbrk](strpbrk "c/string/byte/strpbrk") | finds the first location of any character in one string, in another string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strspn "cpp/string/byte/strspn") for `strspn` |
c atoi, atol, atoll atoi, atol, atoll
=================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
int atoi( const char *str );
```
| | |
|
```
long atol( const char *str );
```
| | |
|
```
long long atoll( const char *str );
```
| | (since C99) |
Interprets an integer value in a byte string pointed to by `str`.
Discards any whitespace characters until the first non-whitespace character is found, then takes as many characters as possible to form a valid integer number representation and converts them to an integer value. The valid integer value consists of the following parts:
* (optional) plus or minus sign
* numeric digits
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated byte string to be interpreted |
### Return value
Integer value corresponding to the contents of `str` on success.
If no conversion can be performed, `0` is returned.
If the value of the result cannot be represented, i.e. the converted value falls out of range of the corresponding return type, behavior is undefined.
### Notes
The name stands for "ASCII to integer".
### Example
```
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("%i\n", atoi(" -123junk"));
printf("%i\n", atoi(" +321dust"));
printf("%i\n", atoi("0"));
printf("%i\n", atoi("junk")); // no conversion can be performed
printf("%i\n", atoi("2147483648")); // UB: out of range of int
}
```
Possible output:
```
-123
321
0
0
-2147483648
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.1.2 The atoi, atol, and atoll functions (p: 249)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.1.2 The atoi, atol, and atoll functions (p: 341)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.1.2 The atoi, atol, and atoll functions (p: 307)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.1.2 The atoi function
+ 4.10.1.3 The atol function
### See also
| | |
| --- | --- |
| [strtolstrtoll](strtol "c/string/byte/strtol")
(C99) | converts a byte string to an integer value (function) |
| [strtoul strtoull](strtoul "c/string/byte/strtoul")
(C99) | converts a byte string to an unsigned integer value (function) |
| [wcstolwcstoll](../wide/wcstol "c/string/wide/wcstol")
(C95)(C99) | converts a wide string to an integer value (function) |
| [wcstoulwcstoull](../wide/wcstoul "c/string/wide/wcstoul")
(C95)(C99) | converts a wide string to an unsigned integer value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/atoi "cpp/string/byte/atoi") for `atoi, atol, atoll` |
c islower islower
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int islower( int ch );
```
| | |
Checks if the given character is classified as a lowercase character according to the current C locale. In the default "C" locale, `islower` returns true only for the lowercase letters (`abcdefghijklmnopqrstuvwxyz`).
If `islower` returns `true`, it is guaranteed that `[iscntrl](iscntrl "c/string/byte/iscntrl")`, `[isdigit](isdigit "c/string/byte/isdigit")`, `[ispunct](ispunct "c/string/byte/ispunct")`, and `[isspace](isspace "c/string/byte/isspace")` return `false` for the same character in the same C locale.
The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/c/io)`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to classify |
### Return value
Non-zero value if the character is a lowercase letter, zero otherwise.
### Example
```
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
int main(void)
{
unsigned char c = '\xe5'; // letter å in ISO-8859-1
printf("In the default C locale, \\xe5 is %slowercase\n",
islower(c) ? "" : "not " );
setlocale(LC_ALL, "en_GB.iso88591");
printf("In ISO-8859-1 locale, \\xe5 is %slowercase\n",
islower(c) ? "" : "not " );
}
```
Possible output:
```
In the default C locale, \xe5 is not lowercase
In ISO-8859-1 locale, \xe5 is lowercase
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.1.7 The islower function (p: 146)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.1.7 The islower function (p: 202)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.1.7 The islower function (p: 183)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.1.6 The islower function
### See also
| | |
| --- | --- |
| [iswlower](../wide/iswlower "c/string/wide/iswlower")
(C95) | checks if a wide character is an lowercase character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/islower "cpp/string/byte/islower") for `islower` |
| ASCII values | characters | [`iscntrl`](iscntrl "c/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](isprint "c/string/byte/isprint") [`iswprint`](../wide/iswprint "c/string/wide/iswprint"). | [`isspace`](isspace "c/string/byte/isspace") [`iswspace`](../wide/iswspace "c/string/wide/iswspace"). | [`isblank`](isblank "c/string/byte/isblank") [`iswblank`](../wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](isgraph "c/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](ispunct "c/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](isalnum "c/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](isalpha "c/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](isupper "c/string/byte/isupper") [`iswupper`](../wide/iswupper "c/string/wide/iswupper"). | **`islower`** [`iswlower`](../wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](isdigit "c/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](isxdigit "c/string/byte/isxdigit") [`iswxdigit`](../wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c isblank isblank
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int isblank( int ch );
```
| | (since C99) |
Checks if the given character is a blank character in the current C locale. In the default C locale, only space (`0x20`) and horizontal tab (`0x09`) are classified as blank.
The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/c/io)`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to classify |
### Return value
Non-zero value if the character is a blank character, zero otherwise.
### Example
```
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
int main(void)
{
for (int ndx=0; ndx<=UCHAR_MAX; ndx++)
if (isblank(ndx)) printf("0x%02x\n", ndx);
}
```
Output:
```
0x09
0x20
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.1.3 The isblank function (p: 145)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.1.3 The isblank function (p: 201)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.1.3 The isblank function (p: 182)
### See also
| | |
| --- | --- |
| [iswblank](../wide/iswblank "c/string/wide/iswblank")
(C99) | checks if a wide character is a blank character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/isblank "cpp/string/byte/isblank") for `isblank` |
| ASCII values | characters | [`iscntrl`](iscntrl "c/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](isprint "c/string/byte/isprint") [`iswprint`](../wide/iswprint "c/string/wide/iswprint"). | [`isspace`](isspace "c/string/byte/isspace") [`iswspace`](../wide/iswspace "c/string/wide/iswspace"). | **`isblank`** [`iswblank`](../wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](isgraph "c/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](ispunct "c/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](isalnum "c/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](isalpha "c/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](isupper "c/string/byte/isupper") [`iswupper`](../wide/iswupper "c/string/wide/iswupper"). | [`islower`](islower "c/string/byte/islower") [`iswlower`](../wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](isdigit "c/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](isxdigit "c/string/byte/isxdigit") [`iswxdigit`](../wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| programming_docs |
c memmove, memmove_s memmove, memmove\_s
===================
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
void* memmove( void* dest, const void* src, size_t count );
```
| (1) | |
|
```
errno_t memmove_s(void *dest, rsize_t destsz, const void *src, rsize_t count);
```
| (2) | (since C11) |
1) Copies `count` characters from the object pointed to by `src` to the object pointed to by `dest`. Both objects are interpreted as arrays of `unsigned char`. The objects may overlap: copying takes place as if the characters were copied to a temporary character array and then the characters were copied from the array to `dest`.
The behavior is undefined if access occurs beyond the end of the dest array. The behavior is undefined if either `dest` or `src` is an invalid or null pointer.
2) Same as (1), except when detecting the following errors at runtime, it zeroes out the entire destination range `[dest, dest+destsz)` (if both `dest` and `destsz` are valid) and calls the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function: * `dest` or `src` is a null pointer
* `destsz` or `count` is greater than `RSIZE_MAX`
* `count` is greater than `destsz` (buffer overflow would occur)
The behavior is undefined if the size of the character array pointed to by `dest` < `count` <= `destsz`; in other words, an erroneous value of `destsz` does not expose the impending buffer overflow. As with all bounds-checked functions, `memmove_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<string.h>`. ### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the object to copy to |
| destsz | - | max number of bytes to modify in the destination (typically the size of the destination object) |
| src | - | pointer to the object to copy from |
| count | - | number of bytes to copy |
### Return value
1) Returns a copy of `dest`
2) Returns zero on success and non-zero value on error. Also on error, if `dest` is not a null pointer and `destsz` is valid, writes `destsz` zero bytes in to the destination array. ### Notes
`memmove` may be used to set the [effective type](../../language/object#Effective_type "c/language/object") of an object obtained by an allocation function.
Despite being specified "as if" a temporary buffer is used, actual implementations of this function do not incur the overhead or double copying or extra memory. A common approach (glibc and bsd libc) is to copy bytes forwards from the beginning of the buffer if the destination starts before the source, and backwards from the end otherwise, with a fall back to the more efficient `[memcpy](memcpy "c/string/byte/memcpy")` when there is no overlap at all.
Where [strict aliasing](../../language/object#Strict_aliasing "c/language/object") prohibits examining the same memory as values of two different types, `memmove` may be used to convert the values.
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char str[] = "1234567890";
puts(str);
memmove(str+4, str+3, 3); // copy from [4,5,6] to [5,6,7]
puts(str);
// setting effective type of allocated memory to be int
int *p = malloc(3*sizeof(int)); // allocated memory has no effective type
int arr[3] = {1,2,3};
memmove(p,arr,3*sizeof(int)); // allocated memory now has an effective type
// reinterpreting data
double d = 0.1;
// int64_t n = *(int64_t*)(&d); // strict aliasing violation
int64_t n;
memmove(&n, &d, sizeof d); // OK
printf("%a is %" PRIx64 " as an int64_t\n", d, n);
#ifdef __STDC_LIB_EXT1__
set_constraint_handler_s(ignore_handler_s);
char src[] = "aaaaaaaaaa";
char dst[] = "xyxyxyxyxy";
int r = memmove_s(dst,sizeof dst,src,5);
printf("dst = \"%s\", r = %d\n", dst,r);
r = memmove_s(dst,5,src,10); // count is greater than destsz
printf("dst = \"");
for(size_t ndx=0; ndx<sizeof dst; ++ndx) {
char c = dst[ndx];
c ? printf("%c", c) : printf("\\0");
}
printf("\", r = %d\n", r);
#endif
}
```
Possible output:
```
1234567890
1234456890
0x1.999999999999ap-4 is 3fb999999999999a as an int64_t
dst = "aaaaayxyxy", r = 0
dst = "\0\0\0\0\0yxyxy", r = 22
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.24.2.2 The memmove function (p: 264)
+ K.3.7.1.2 The memmove\_s function (p: 446)
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.2.2 The memmove function (p: 363)
+ K.3.7.1.2 The memmove\_s function (p: 615)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.2.2 The memmove function (p: 326)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.2.2 The memmove function
### See also
| | |
| --- | --- |
| [memcpymemcpy\_s](memcpy "c/string/byte/memcpy")
(C11) | copies one buffer to another (function) |
| [wmemmovewmemmove\_s](../wide/wmemmove "c/string/wide/wmemmove")
(C95)(C11) | copies a certain amount of wide characters between two, possibly overlapping, arrays (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/memmove "cpp/string/byte/memmove") for `memmove` |
c strcmp strcmp
======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
int strcmp( const char *lhs, const char *rhs );
```
| | |
Compares two null-terminated byte strings lexicographically.
The sign of the result is the sign of the difference between the values of the first pair of characters (both interpreted as `unsigned char`) that differ in the strings being compared.
The behavior is undefined if `lhs` or `rhs` are not pointers to null-terminated byte strings.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | pointers to the null-terminated byte strings to compare |
### Return value
Negative value if `lhs` appears before `rhs` in lexicographical order.
Zero if `lhs` and `rhs` compare equal.
Positive value if `lhs` appears after `rhs` in lexicographical order.
### Notes
This function is not locale-sensitive, unlike `[strcoll](strcoll "c/string/byte/strcoll")` and `[strxfrm](strxfrm "c/string/byte/strxfrm")`.
### Example
```
#include <string.h>
#include <stdio.h>
void demo(const char* lhs, const char* rhs)
{
int rc = strcmp(lhs, rhs);
const char *rel = rc < 0 ? "precedes" : rc > 0 ? "follows" : "equals";
printf("[%s] %s [%s]\n", lhs, rel, rhs);
}
int main(void)
{
const char* string = "Hello World!";
demo(string, "Hello!");
demo(string, "Hello");
demo(string, "Hello there");
demo("Hello, everybody!" + 12, "Hello, somebody!" + 11);
}
```
Output:
```
[Hello World!] precedes [Hello!]
[Hello World!] follows [Hello]
[Hello World!] precedes [Hello there]
[body!] equals [body!]
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.4.2 The strcmp function (p: 365-366)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.4.2 The strcmp function (p: 328-329)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.4.2 The strcmp function
### See also
| | |
| --- | --- |
| [strncmp](strncmp "c/string/byte/strncmp") | compares a certain amount of characters of two strings (function) |
| [wcscmp](../wide/wcscmp "c/string/wide/wcscmp")
(C95) | compares two wide strings (function) |
| [memcmp](memcmp "c/string/byte/memcmp") | compares two buffers (function) |
| [strcoll](strcoll "c/string/byte/strcoll") | compares two strings in accordance to the current locale (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strcmp "cpp/string/byte/strcmp") for `strcmp` |
c strtol, strtoll strtol, strtoll
===============
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
long strtol( const char *str, char **str_end, int base );
```
| | (until C99) |
|
```
long strtol( const char *restrict str, char **restrict str_end, int base );
```
| | (since C99) |
|
```
long long strtoll( const char *restrict str, char **restrict str_end, int base );
```
| | (since C99) |
Interprets an integer value in a byte string pointed to by `str`.
Discards any whitespace characters (as identified by calling [`isspace`](isspace "c/string/byte/isspace")) until the first non-whitespace character is found, then takes as many characters as possible to form a valid *base-n* (where n=`base`) integer number representation and converts them to an integer value. The valid integer value consists of the following parts:
* (optional) plus or minus sign
* (optional) prefix (`0`) indicating octal base (applies only when the base is `8` or `0`)
* (optional) prefix (`0x` or `0X`) indicating hexadecimal base (applies only when the base is `16` or `0`)
* a sequence of digits
The set of valid values for base is `{0,2,3,...,36}.` The set of valid digits for base-`2` integers is `{0,1},` for base-`3` integers is `{0,1,2},` and so on. For bases larger than `10`, valid digits include alphabetic characters, starting from `Aa` for base-`11` integer, to `Zz` for base-`36` integer. The case of the characters is ignored.
Additional numeric formats may be accepted by the currently installed C [locale](../../locale/setlocale "c/locale/setlocale").
If the value of `base` is `0`, the numeric base is auto-detected: if the prefix is `0`, the base is octal, if the prefix is `0x` or `0X`, the base is hexadecimal, otherwise the base is decimal.
If the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by [unary minus](../../language/operator_arithmetic#Unary_arithmetic "c/language/operator arithmetic") in the result type.
The functions sets the pointer pointed to by `str_end` to point to the character past the last character interpreted. If `str_end` is a null pointer, it is ignored.
If the `str` is empty or does not have the expected form, no conversion is performed, and (if `str_end` is not a null pointer) the value of `str` is stored in the object pointed to by `str_end`.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated byte string to be interpreted |
| str\_end | - | pointer to a pointer to character. |
| base | - | *base* of the interpreted integer value |
### Return value
* If successful, an integer value corresponding to the contents of `str` is returned.
* If the converted value falls out of range of corresponding return type, a range error occurs (setting `[errno](../../error/errno "c/error/errno")` to `[ERANGE](../../error/errno_macros "c/error/errno macros")`) and `[LONG\_MAX](../../types/limits "c/types/limits")`, `[LONG\_MIN](../../types/limits "c/types/limits")`, `[LLONG\_MAX](../../types/limits "c/types/limits")` or `[LLONG\_MIN](../../types/limits "c/types/limits")` is returned.
* If no conversion can be performed, `0` is returned.
### Example
```
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// parsing with error handling
const char *p = "10 200000000000000000000000000000 30 -40 junk";
printf("Parsing '%s':\n", p);
for (;;)
{
// errno can be set to any non-zero value by a library function call
// regardless of whether there was an error, so it needs to be cleared
// in order to check the error set by strtol
errno = 0;
char *end;
const long i = strtol(p, &end, 10);
if (p == end)
break;
const bool range_error = errno == ERANGE;
printf("Extracted '%.*s', strtol returned %ld.", (int)(end-p), p, i);
p = end;
if (range_error)
printf(" Range error occurred.");
putchar('\n');
}
printf("Unextracted leftover: '%s'\n\n", p);
// parsing without error handling
printf("\"1010\" in binary --> %ld\n", strtol("1010", NULL, 2));
printf("\"12\" in octal --> %ld\n", strtol("12", NULL, 8));
printf("\"A\" in hex --> %ld\n", strtol("A", NULL, 16));
printf("\"junk\" in base-36 --> %ld\n", strtol("junk", NULL, 36));
printf("\"012\" in auto-detected base --> %ld\n", strtol("012", NULL, 0));
printf("\"0xA\" in auto-detected base --> %ld\n", strtol("0xA", NULL, 0));
printf("\"junk\" in auto-detected base --> %ld\n", strtol("junk", NULL, 0));
}
```
Possible output:
```
Parsing '10 200000000000000000000000000000 30 -40 junk':
Extracted '10', strtol returned 10.
Extracted ' 200000000000000000000000000000', strtol returned 9223372036854775807. Range error occurred.
Extracted ' 30', strtol returned 30.
Extracted ' -40', strtol returned -40.
Unextracted leftover: ' junk'
"1010" in binary --> 10
"12" in octal --> 10
"A" in hex --> 10
"junk" in base-36 --> 926192
"012" in auto-detected base --> 10
"0xA" in auto-detected base --> 10
"junk" in auto-detected base --> 0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions (p: 344-345)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.1.4 The strtol, strtoll, strtoul, and strtoull functions (p: 310-311)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.1.5 The strtol function
### See also
| | |
| --- | --- |
| [atoiatolatoll](atoi "c/string/byte/atoi")
(C99) | converts a byte string to an integer value (function) |
| [strtoul strtoull](strtoul "c/string/byte/strtoul")
(C99) | converts a byte string to an unsigned integer value (function) |
| [wcstolwcstoll](../wide/wcstol "c/string/wide/wcstol")
(C95)(C99) | converts a wide string to an integer value (function) |
| [wcstoulwcstoull](../wide/wcstoul "c/string/wide/wcstoul")
(C95)(C99) | converts a wide string to an unsigned integer value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strtol "cpp/string/byte/strtol") for `strtol, strtoll` |
c memccpy memccpy
=======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
void *memccpy( void * restrict dest, const void * restrict src, int c, size_t count );
```
| | (since C23) |
Copies bytes from the object pointed to by `src` to the object pointed to by `dest`, stopping after *any* of the next two conditions are satisfied:
* `count` bytes are copied
* the byte `(unsigned char)c` is found (and copied).
The `src` and `dest` objects are interpreted as arrays of `unsigned char`.
The behavior is undefined if *any* condition is met:
* access occurs beyond the end of the `dest` array;
* the objects overlap (which is a violation of the [`restrict`](../../language/restrict "c/language/restrict") contract)
* either `dest` or `src` is an invalid or null pointer
### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the object to copy to |
| src | - | pointer to the object to copy from |
| c | - | terminating byte, converted to `unsigned char` at first |
| count | - | number of bytes to copy |
### Return value
If the byte `(unsigned char)c` was found `memccpy` returns a pointer to the next byte in `dest` after `(unsigned char)c`, otherwise returns null pointer.
### Notes
The function is identical to the [POSIX `memccpy`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/memccpy.html).
`memccpy(dest, src, 0, count)` behaves similar to `[strncpy](http://en.cppreference.com/w/c/string/byte/strncpy)(dest, src, count)`, except that the former returns a pointer to the *end* of the buffer written, and does not zero-pad the destination array. Thus, `memccpy` is useful for efficiently concatenating multiple strings.
```
char bigString[1000];
char* end = bigString + sizeof bigString;
char* p = memccpy(bigString, "John, ", 0, sizeof bigString);
if (p) p = memccpy(p - 1, "Paul, ", 0, end - p);
if (p) p = memccpy(p - 1, "George, ", 0, end - p);
if (p) p = memccpy(p - 1, "Joel ", 0, end - p);
puts(bigString); // John, Paul, George, Joel
```
### Example
```
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
const char src[] = "Stars: Altair, Sun, Vega.";
const char terminal[] = {':', ' ', ',', '.', '!'};
char dest[sizeof src];
const char alt = '@';
for (size_t i = 0; i != sizeof terminal; ++i) {
void *to = memccpy(dest, src, terminal[i], sizeof dest);
printf("Terminal '%c' (%s):\t\"", terminal[i], to ? "found" : "absent");
// if `terminal` character was not found - print the whole `dest`
to = to ? to : dest + sizeof dest;
for (char *from = dest; from != to; ++from)
putchar(isprint(*from) ? *from : alt);
puts("\"");
}
puts("\n" "Separate star names from distances (ly):");
const char *star_distance[] = {
"Arcturus : 37", "Vega : 25", "Capella : 43", "Rigel : 860", "Procyon : 11"
};
char names_only[64];
char *first = names_only;
char *last = names_only + sizeof names_only;
for (size_t t = 0; t != (sizeof star_distance)/(sizeof star_distance[0]); ++t) {
if (first) {
first = memccpy(first, star_distance[t], ' ', last - first);
} else break;
}
if (first) {
*first = '\0';
puts(names_only);
} else {
puts("Buffer is too small.");
}
}
```
Output:
```
Terminal ':' (found): "Stars:"
Terminal ' ' (found): "Stars: "
Terminal ',' (found): "Stars: Altair,"
Terminal '.' (found): "Stars: Altair, Sun, Vega."
Terminal '!' (absent): "Stars: Altair, Sun, Vega.@"
Separate star names from distances (ly):
Arcturus Vega Capella Rigel Procyon
```
### See also
| | |
| --- | --- |
| [memcpymemcpy\_s](memcpy "c/string/byte/memcpy")
(C11) | copies one buffer to another (function) |
| [wmemcpywmemcpy\_s](../wide/wmemcpy "c/string/wide/wmemcpy")
(C95)(C11) | copies a certain amount of wide characters between two non-overlapping arrays (function) |
| [memmovememmove\_s](memmove "c/string/byte/memmove")
(C11) | moves one buffer to another (function) |
| [strcpystrcpy\_s](strcpy "c/string/byte/strcpy")
(C11) | copies one string to another (function) |
| [strcatstrcat\_s](strcat "c/string/byte/strcat")
(C11) | concatenates two strings (function) |
c memcpy, memcpy_s memcpy, memcpy\_s
=================
| Defined in header `<string.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
void* memcpy( void *dest, const void *src, size_t count );
```
| (until C99) |
|
```
void* memcpy( void *restrict dest, const void *restrict src, size_t count );
```
| (since C99) |
|
```
errno_t memcpy_s( void *restrict dest, rsize_t destsz,
const void *restrict src, rsize_t count );
```
| (2) | (since C11) |
1) Copies `count` characters from the object pointed to by `src` to the object pointed to by `dest`. Both objects are interpreted as arrays of `unsigned char`.
The behavior is undefined if access occurs beyond the end of the `dest` array. If the objects overlap (which is a violation of the [`restrict`](../../language/restrict "c/language/restrict") contract) (since C99), the behavior is undefined. The behavior is undefined if either `dest` or `src` is an invalid or null pointer.
2) Same as (1), except that the following errors are detected at runtime and cause the entire destination range `[dest, dest+destsz)` to be zeroed out (if both `dest` and `destsz` are valid), as well as call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function: * `dest` or `src` is a null pointer
* `destsz` or `count` is greater than `RSIZE_MAX`
* `count` is greater than `destsz` (buffer overflow would occur)
* the source and the destination objects overlap
The behavior is undefined if the size of the character array pointed to by `dest` < `count` <= `destsz`; in other words, an erroneous value of `destsz` does not expose the impending buffer overflow. As with all bounds-checked functions, `memcpy_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<string.h>`. ### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the object to copy to |
| destsz | - | max number of bytes to modify in the destination (typically the size of the destination object) |
| src | - | pointer to the object to copy from |
| count | - | number of bytes to copy |
### Return value
1) Returns a copy of `dest`
2) Returns zero on success and non-zero value on error. Also on error, if `dest` is not a null pointer and `destsz` is valid, writes `destsz` zero bytes in to the destination array. ### Notes
`memcpy` may be used to set the [effective type](../../language/object#Effective_type "c/language/object") of an object obtained by an allocation function.
`memcpy` is the fastest library routine for memory-to-memory copy. It is usually more efficient than `[strcpy](strcpy "c/string/byte/strcpy")`, which must scan the data it copies or `[memmove](memmove "c/string/byte/memmove")`, which must take precautions to handle overlapping inputs.
Several C compilers transform suitable memory-copying loops to `memcpy` calls.
Where [strict aliasing](../../language/object#Strict_aliasing "c/language/object") prohibits examining the same memory as values of two different types, `memcpy` may be used to convert the values.
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
// simple usage
char source[] = "once upon a midnight dreary...", dest[4];
memcpy(dest, source, sizeof dest);
for(size_t n = 0; n < sizeof dest; ++n)
putchar(dest[n]);
// setting effective type of allocated memory to be int
int *p = malloc(3*sizeof(int)); // allocated memory has no effective type
int arr[3] = {1,2,3};
memcpy(p,arr,3*sizeof(int)); // allocated memory now has an effective type
// reinterpreting data
double d = 0.1;
// int64_t n = *(int64_t*)(&d); // strict aliasing violation
int64_t n;
memcpy(&n, &d, sizeof d); // OK
printf("\n%a is %" PRIx64 " as an int64_t\n", d, n);
#ifdef __STDC_LIB_EXT1__
set_constraint_handler_s(ignore_handler_s);
char src[] = "aaaaaaaaaa";
char dst[] = "xyxyxyxyxy";
int r = memcpy_s(dst,sizeof dst,src,5);
printf("dst = \"%s\", r = %d\n", dst,r);
r = memcpy_s(dst,5,src,10); // count is greater than destsz
printf("dst = \"");
for(size_t ndx=0; ndx<sizeof dst; ++ndx) {
char c = dst[ndx];
c ? printf("%c", c) : printf("\\0");
}
printf("\", r = %d\n", r);
#endif
}
```
Possible output:
```
once
0x1.999999999999ap-4 is 3fb999999999999a as an int64_t
dst = "aaaaayxyxy", r = 0
dst = "\0\0\0\0\0yxyxy", r = 22
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.2.1 The memcpy function (p: 362)
+ K.3.7.1.1 The memcpy\_s function (p: 614)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.2.1 The memcpy function (p: 325)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.2.1 The memcpy function
### See also
| | |
| --- | --- |
| [memccpy](memccpy "c/string/byte/memccpy")
(C23) | copies one buffer to another, stopping after the specified delimiter (function) |
| [memmovememmove\_s](memmove "c/string/byte/memmove")
(C11) | moves one buffer to another (function) |
| [wmemcpywmemcpy\_s](../wide/wmemcpy "c/string/wide/wmemcpy")
(C95)(C11) | copies a certain amount of wide characters between two non-overlapping arrays (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/memcpy "cpp/string/byte/memcpy") for `memcpy` |
| programming_docs |
c strlen, strnlen_s strlen, strnlen\_s
==================
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
size_t strlen( const char *str );
```
| (1) | |
|
```
size_t strnlen_s( const char *str, size_t strsz );
```
| (2) | (since C11) |
1) Returns the length of the given null-terminated byte string, that is, the number of characters in a character array whose first element is pointed to by `str` up to and not including the first null character.
The behavior is undefined if `str` is not a pointer to a null-terminated byte string.
2) Same as (1), except that the function returns zero if `str` is a null pointer and returns `strsz` if the null character was not found in the first `strsz` bytes of `str`.
The behavior is undefined if both `str` points to a character array which lacks the null character and the size of that character array < `strsz`; in other words, an erroneous value of `strsz` does not expose the impending buffer overflow. As with all bounds-checked functions, `strnlen_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<string.h>`. ### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated byte string to be examined |
| strsz | - | maximum number of characters to examine |
### Return value
1) The length of the null-terminated byte string `str`.
2) The length of the null-terminated byte string `str` on success, zero if `str` is a null pointer, `strsz` if the null character was not found. ### Notes
`strnlen_s` and `wcsnlen_s` are the only [bounds-checked functions](../../error "c/error") that do not invoke the runtime constraints handler. They are pure utility functions used to provide limited support for non-null terminated strings.
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>
int main(void)
{
const char str[] = "How many characters does this string contain?";
printf("without null character: %zu\n", strlen(str));
printf("with null character: %zu\n", sizeof str);
#ifdef __STDC_LIB_EXT1__
printf("without null character: %zu\n", strnlen_s(str, sizeof str));
#endif
}
```
Possible output:
```
without null character: 45
with null character: 46
without null character: 45
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.6.3 The strlen function (p: 372)
+ K.3.7.4.4 The strnlen\_s function (p: 623)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.6.3 The strlen function (p: 334)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.6.3 The strlen function
### See also
| | |
| --- | --- |
| [wcslenwcsnlen\_s](../wide/wcslen "c/string/wide/wcslen")
(C95)(C11) | returns the length of a wide string (function) |
| [mblen](../multibyte/mblen "c/string/multibyte/mblen") | returns the number of bytes in the next multibyte character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strlen "cpp/string/byte/strlen") for `strlen` |
c isprint isprint
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int isprint( int ch );
```
| | |
Checks if the given character can be printed, i.e. it is either a number (`0123456789`), an uppercase letter (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`), a lowercase letter (`abcdefghijklmnopqrstuvwxyz`), a punctuation character(`!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`), or space, or any character classified as printable by the current C locale.
The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/c/io)`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to classify |
### Return value
Non-zero value if the character can be printed, zero otherwise.
### Example
```
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
int main(void)
{
unsigned char c = '\xa0'; // the non-breaking space in ISO-8859-1
printf("In the default C locale, \\xa0 is %sprintable\n", isprint(c)?"":"not ");
setlocale(LC_ALL, "en_GB.iso88591");
printf("In ISO-8859-1 locale, \\xa0 is %sprintable\n", isprint(c)?"":"not ");
}
```
Possible output:
```
In the default C locale, \xa0 is not printable
In ISO-8859-1 locale, \xa0 is printable
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.1.8 The isprint function (p: 146)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.1.8 The isprint function (p: 202)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.1.8 The isprint function (p: 183)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.1.7 The isprint function
### See also
| | |
| --- | --- |
| [iswprint](../wide/iswprint "c/string/wide/iswprint")
(C95) | checks if a wide character is a printing character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/isprint "cpp/string/byte/isprint") for `isprint` |
| ASCII values | characters | [`iscntrl`](iscntrl "c/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "c/string/wide/iswcntrl"). | **`isprint`** [`iswprint`](../wide/iswprint "c/string/wide/iswprint"). | [`isspace`](isspace "c/string/byte/isspace") [`iswspace`](../wide/iswspace "c/string/wide/iswspace"). | [`isblank`](isblank "c/string/byte/isblank") [`iswblank`](../wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](isgraph "c/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](ispunct "c/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "c/string/wide/iswpunct"). | [`isalnum`](isalnum "c/string/byte/isalnum") [`iswalnum`](../wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](isalpha "c/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](isupper "c/string/byte/isupper") [`iswupper`](../wide/iswupper "c/string/wide/iswupper"). | [`islower`](islower "c/string/byte/islower") [`iswlower`](../wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](isdigit "c/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](isxdigit "c/string/byte/isxdigit") [`iswxdigit`](../wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c strtok, strtok_s strtok, strtok\_s
=================
| Defined in header `<string.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
char *strtok( char *str, const char *delim );
```
| (until C99) |
|
```
char *strtok( char *restrict str, const char *restrict delim );
```
| (since C99) |
|
```
char *strtok_s(char *restrict str, rsize_t *restrict strmax,
const char *restrict delim, char **restrict ptr);
```
| (2) | (since C11) |
1) Finds the next token in a null-terminated byte string pointed to by `str`. The separator characters are identified by null-terminated byte string pointed to by `delim`.
This function is designed to be called multiple times to obtain successive tokens from the same string. * If `str` is not a null pointer, the call is treated as the first call to `strtok` for this particular string. The function searches for the first character which is *not* contained in `delim`.
* If no such character was found, there are no tokens in `str` at all, and the function returns a null pointer.
* If such character was found, it is the *beginning of the token*. The function then searches from that point on for the first character that *is* contained in `delim`.
+ If no such character was found, `str` has only one token, and future calls to `strtok` will return a null pointer
+ If such character was found, it is *replaced* by the null character `'\0'` and the pointer to the following character is stored in a static location for subsequent invocations.
* The function then returns the pointer to the beginning of the token
* If `str` is a null pointer, the call is treated as a subsequent calls to `strtok`: the function continues from where it left in previous invocation. The behavior is the same as if the previously stored pointer is passed as `str`.
The behavior is undefined if either `str` or `delim` is not a pointer to a null-terminated byte string.
2) Same as (1), except that on every step, writes the number of characters left to see in `str` into `*strmax` and writes the tokenizer's internal state to `*ptr`. Repeat calls (with null `str`) must pass `strmax` and `ptr` with the values stored by the previous call. Also, the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function, without storing anything in the object pointed to by `ptr` * `strmax`, `delim`, or `ptr` is a null pointer
* on a non-initial call (with null `str`), `*ptr` is a null pointer
* on the first call, `*strmax` is zero or greater than `RSIZE_MAX`
* search for the end of a token reaches the end of the source string (as measured by the initial value of `*strmax`) without encountering the null terminator
The behavior is undefined if both `str` points to a character array which lacks the null character and `strmax` points to a value which is greater than the size of that character array. As with all bounds-checked functions, `strtok_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<string.h>`. ### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated byte string to tokenize |
| delim | - | pointer to the null-terminated byte string identifying delimiters |
| strmax | - | pointer to an object which initially holds the size of `str`: strtok\_s stores the number of characters that remain to be examined |
| ptr | - | pointer to an object of type `char*`, which is used by strtok\_s to store its internal state |
### Return value
Returns pointer to the beginning of the next token or a null pointer if there are no more tokens.
### Note
This function is destructive: it writes the `'\0'` characters in the elements of the string `str`. In particular, a string literal cannot be used as the first argument of `strtok`.
Each call to `strtok` modifies a static variable: is not thread safe.
Unlike most other tokenizers, the delimiters in `strtok` can be different for each subsequent token, and can even depend on the contents of the previous tokens.
The `strtok_s` function differs from the POSIX [`strtok_r`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strtok.html) function by guarding against storing outside of the string being tokenized, and by checking runtime constraints. The Microsoft CRT `strtok_s` signature matches this POSIX `strtok_r` definition, not the C11 `strtok_s`.
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>
int main(void)
{
char input[] = "A bird came down the walk";
printf("Parsing the input string '%s'\n", input);
char *token = strtok(input, " ");
while(token) {
puts(token);
token = strtok(NULL, " ");
}
printf("Contents of the input string now: '");
for(size_t n = 0; n < sizeof input; ++n)
input[n] ? putchar(input[n]) : fputs("\\0", stdout);
puts("'");
#ifdef __STDC_LIB_EXT1__
char str[] = "A bird came down the walk";
rsize_t strmax = sizeof str;
const char *delim = " ";
char *next_token;
printf("Parsing the input string '%s'\n", str);
token = strtok_s(str, &strmax, delim, &next_token);
while(token) {
puts(token);
token = strtok_s(NULL, &strmax, delim, &next_token);
}
printf("Contents of the input string now: '");
for(size_t n = 0; n < sizeof str; ++n)
str[n] ? putchar(str[n]) : fputs("\\0", stdout);
puts("'");
#endif
}
```
Possible output:
```
Parsing the input string 'A bird came down the walk'
A
bird
came
down
the
walk
Contents of the input string now: 'A\0bird\0came\0down\0the\0walk\0'
Parsing the input string 'A bird came down the walk'
A
bird
came
down
the
walk
Contents of the input string now: 'A\0bird\0came\0down\0the\0walk\0'
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.5.8 The strtok function (p: 369-370)
+ K.3.7.3.1 The strtok\_s function (p: 620-621)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.5.8 The strtok function (p: 332-333)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.5.8 The strtok function
### See also
| | |
| --- | --- |
| [strpbrk](strpbrk "c/string/byte/strpbrk") | finds the first location of any character in one string, in another string (function) |
| [strcspn](strcspn "c/string/byte/strcspn") | returns the length of the maximum initial segment that consists of only the characters not found in another byte string (function) |
| [strspn](strspn "c/string/byte/strspn") | returns the length of the maximum initial segment that consists of only the characters found in another byte string (function) |
| [wcstokwcstok\_s](../wide/wcstok "c/string/wide/wcstok")
(C95)(C11) | finds the next token in a wide string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strtok "cpp/string/byte/strtok") for `strtok` |
c tolower tolower
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int tolower( int ch );
```
| | |
Converts the given character to lowercase according to the character conversion rules defined by the currently installed C locale.
In the default "C" locale, the following uppercase letters `ABCDEFGHIJKLMNOPQRSTUVWXYZ` are replaced with respective lowercase letters `abcdefghijklmnopqrstuvwxyz`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to be converted. If the value of `ch` is not representable as `unsigned char` and does not equal `[EOF](http://en.cppreference.com/w/c/io)`, the behavior is undefined. |
### Return value
Lowercase version of `ch` or unmodified `ch` if no lowercase version is listed in the current C locale.
### Example
```
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
#include <limits.h>
int main(void)
{
/* In the default locale: */
for (unsigned char u = 0; u < UCHAR_MAX; u++) {
unsigned char l = tolower(u);
if (l != u) printf("%c%c ", u, l);
}
printf("\n\n");
unsigned char c = '\xb4'; // the character Ž in ISO-8859-15
// but ´ (acute accent) in ISO-8859-1
setlocale(LC_ALL, "en_US.iso88591");
printf("in iso8859-1, tolower('0x%x') gives 0x%x\n", c, tolower(c));
setlocale(LC_ALL, "en_US.iso885915");
printf("in iso8859-15, tolower('0x%x') gives 0x%x\n", c, tolower(c));
}
```
Possible output:
```
Aa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Ss Tt Uu Vv Ww Xx Yy Zz
in iso8859-1, tolower('0xb4') gives 0xb4
in iso8859-15, tolower('0xb4') gives 0xb8
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.2.1 The tolower function (p: 147)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.2.1 The tolower function (p: 203)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.2.1 The tolower function (p: 184)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.2.1 The tolower function
### See also
| | |
| --- | --- |
| [toupper](toupper "c/string/byte/toupper") | converts a character to uppercase (function) |
| [towlower](../wide/towlower "c/string/wide/towlower")
(C95) | converts a wide character to lowercase (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/tolower "cpp/string/byte/tolower") for `tolower` |
c strcat, strcat_s strcat, strcat\_s
=================
| Defined in header `<string.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
char *strcat( char *dest, const char *src );
```
| (until C99) |
|
```
char *strcat( char *restrict dest, const char *restrict src );
```
| (since C99) |
|
```
errno_t strcat_s(char *restrict dest, rsize_t destsz, const char *restrict src);
```
| (2) | (since C11) |
1) Appends a copy of the null-terminated byte string pointed to by `src` to the end of the null-terminated byte string pointed to by `dest`. The character `src[0]` replaces the null terminator at the end of `dest`. The resulting byte string is null-terminated.
The behavior is undefined if the destination array is not large enough for the contents of both `src` and `dest` and the terminating null character. The behavior is undefined if the strings overlap. The behavior is undefined if either `dest` or `src` is not a pointer to a null-terminated byte string.
2) Same as (1), except that it may clobber the rest of the destination array (from the last character written to `destsz`) with unspecified values and that the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function: * `src` or `dest` is a null pointer
* `destsz` is zero or greater than `RSIZE_MAX`
* there is no null terminator in the first `destsz` bytes of `dest`
* truncation would occur (the available space at the end of `dest` would not fit every character, including the null terminator, of `src`)
* overlap would occur between the source and the destination strings
The behavior is undefined if the size of the character array pointed to by `dest` < `[strlen](http://en.cppreference.com/w/c/string/byte/strlen)(dest)+[strlen](http://en.cppreference.com/w/c/string/byte/strlen)(src)+1` <= `destsz`; in other words, an erroneous value of `destsz` does not expose the impending buffer overflow. As with all bounds-checked functions, `strcat_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<string.h>`. ### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the null-terminated byte string to append to |
| src | - | pointer to the null-terminated byte string to copy from |
| destsz | - | maximum number of characters to write, typically the size of the destination buffer |
### Return value
1) returns a copy of `dest`
2) returns zero on success, returns non-zero on error. Also, on error, writes zero to `dest[0]` (unless `dest` is a null pointer or `destsz` is zero or greater than `RSIZE_MAX`). ### Notes
Because `strcat` needs to seek to the end of `dest` on each call, it is inefficient to concatenate many strings into one using `strcat`.
`strcat_s` is allowed to clobber the destination array from the last character written up to `destsz` in order to improve efficiency: it may copy in multibyte blocks and then check for null bytes.
The function `strcat_s` is similar to the [BSD function `strlcat`](https://www.freebsd.org/cgi/man.cgi?query=strlcat&sektion=3), except that.
* `strlcat` truncates the source string to fit in the destination
* `strlcat` does not perform all the runtime checks that `strcat_s` does
* `strlcat` does not make failures obvious by setting the destination to a null string or calling a handler if the call fails.
Although `strcat_s` prohibits truncation due to potential security risks, it's possible to truncate a string using bounds-checked `[strncat\_s](strncat "c/string/byte/strncat")` instead.
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[50] = "Hello ";
char str2[50] = "World!";
strcat(str, str2);
strcat(str, " ...");
strcat(str, " Goodbye World!");
puts(str);
#ifdef __STDC_LIB_EXT1__
set_constraint_handler_s(ignore_handler_s);
int r = strcat_s(str, sizeof str, " ... ");
printf("str = \"%s\", r = %d\n", str, r);
r = strcat_s(str, sizeof str, " and this is too much");
printf("str = \"%s\", r = %d\n", str, r);
#endif
}
```
Possible output:
```
Hello World! ... Goodbye World!
str = "Hello World! ... Goodbye World! ... ", r = 0
str = "", r = 22
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.3.1 The strcat function (p: 364)
+ K.3.7.2.1 The strcat\_s function (p: 617-618)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.3.1 The strcat function (p: 327)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.3.1 The strcat function
### See also
| | |
| --- | --- |
| [strncatstrncat\_s](strncat "c/string/byte/strncat")
(C11) | concatenates a certain amount of characters of two strings (function) |
| [strcpystrcpy\_s](strcpy "c/string/byte/strcpy")
(C11) | copies one string to another (function) |
| [memccpy](memccpy "c/string/byte/memccpy")
(C23) | copies one buffer to another, stopping after the specified delimiter (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strcat "cpp/string/byte/strcat") for `strcat` |
| programming_docs |
c strrchr strrchr
=======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
char *strrchr( const char *str, int ch );
```
| | |
Finds the last occurrence of `ch` (after conversion to `char` as if by `(char)ch`) in the null-terminated byte string pointed to by `str` (each character interpreted as `unsigned char`). The terminating null character is considered to be a part of the string and can be found if searching for `'\0'`.
The behavior is undefined if `str` is not a pointer to a null-terminated byte string.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated byte string to be analyzed |
| ch | - | character to search for |
### Return value
Pointer to the found character in `str`, or null pointer if no such character is found.
### Example
```
#include <string.h>
#include <stdio.h>
int main(void)
{
char szSomeFileName[] = "foo/bar/foobar.txt";
char *pLastSlash = strrchr(szSomeFileName, '/');
char *pszBaseName = pLastSlash ? pLastSlash + 1 : szSomeFileName;
printf("Base Name: %s", pszBaseName);
}
```
Output:
```
Base Name: foobar.txt
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.5.5 The strrchr function (p: 368-369)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.5.5 The strrchr function (p: 331)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.5.5 The strrchr function
### See also
| | |
| --- | --- |
| [strchr](strchr "c/string/byte/strchr") | finds the first occurrence of a character (function) |
| [strpbrk](strpbrk "c/string/byte/strpbrk") | finds the first location of any character in one string, in another string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strrchr "cpp/string/byte/strrchr") for `strrchr` |
c isalnum isalnum
=======
| Defined in header `<ctype.h>` | | |
| --- | --- | --- |
|
```
int isalnum( int ch );
```
| | |
Checks if the given character is an alphanumeric character as classified by the current C locale. In the default locale, the following characters are alphanumeric:
* digits (`0123456789`)
* uppercase letters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`)
* lowercase letters (`abcdefghijklmnopqrstuvwxyz`)
The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](http://en.cppreference.com/w/c/io)`.
### Parameters
| | | |
| --- | --- | --- |
| ch | - | character to classify |
### Return value
Non-zero value if the character is an alphanumeric character, `0` otherwise.
### Example
Demonstrates the use of `isalnum` with different locales (OS-specific).
```
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
int main(void)
{
unsigned char c = '\xdf'; // German letter ß in ISO-8859-1
printf("isalnum('\\xdf') in default C locale returned %d\n", !!isalnum(c));
if(setlocale(LC_CTYPE, "de_DE.iso88591"))
printf("isalnum('\\xdf') in ISO-8859-1 locale returned %d\n", !!isalnum(c));
}
```
Possible output:
```
isalnum('\xdf') in default C locale returned 0
isalnum('\xdf') in ISO-8859-1 locale returned 1
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.4.1.1 The isalnum function (p: 145)
* C11 standard (ISO/IEC 9899:2011):
+ 7.4.1.1 The isalnum function (p: 200)
* C99 standard (ISO/IEC 9899:1999):
+ 7.4.1.1 The isalnum function (p: 181)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.3.1.1 The isalnum function
### See also
| | |
| --- | --- |
| [iswalnum](../wide/iswalnum "c/string/wide/iswalnum")
(C95) | checks if a wide character is alphanumeric (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/isalnum "cpp/string/byte/isalnum") for `isalnum` |
| ASCII values | characters | [`iscntrl`](iscntrl "c/string/byte/iscntrl") [`iswcntrl`](../wide/iswcntrl "c/string/wide/iswcntrl"). | [`isprint`](isprint "c/string/byte/isprint") [`iswprint`](../wide/iswprint "c/string/wide/iswprint"). | [`isspace`](isspace "c/string/byte/isspace") [`iswspace`](../wide/iswspace "c/string/wide/iswspace"). | [`isblank`](isblank "c/string/byte/isblank") [`iswblank`](../wide/iswblank "c/string/wide/iswblank"). | [`isgraph`](isgraph "c/string/byte/isgraph") [`iswgraph`](../wide/iswgraph "c/string/wide/iswgraph"). | [`ispunct`](ispunct "c/string/byte/ispunct") [`iswpunct`](../wide/iswpunct "c/string/wide/iswpunct"). | **`isalnum`** [`iswalnum`](../wide/iswalnum "c/string/wide/iswalnum"). | [`isalpha`](isalpha "c/string/byte/isalpha") [`iswalpha`](../wide/iswalpha "c/string/wide/iswalpha"). | [`isupper`](isupper "c/string/byte/isupper") [`iswupper`](../wide/iswupper "c/string/wide/iswupper"). | [`islower`](islower "c/string/byte/islower") [`iswlower`](../wide/iswlower "c/string/wide/iswlower"). | [`isdigit`](isdigit "c/string/byte/isdigit") [`iswdigit`](../wide/iswdigit "c/string/wide/iswdigit"). | [`isxdigit`](isxdigit "c/string/byte/isxdigit") [`iswxdigit`](../wide/iswxdigit "c/string/wide/iswxdigit"). |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| decimal | hexadecimal | octal |
| 0–8 | `\x0`–`\x8` | `\0`–`\10` | control codes (`NUL`, etc.) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 9 | `\x9` | `\11` | tab (`\t`) | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 10–13 | `\xA`–`\xD` | `\12`–`\15` | whitespaces (`\n`, `\v`, `\f`, `\r`) | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 14–31 | `\xE`–`\x1F` | `\16`–`\37` | control codes | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 32 | `\x20` | `\40` | space | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 33–47 | `\x21`–`\x2F` | `\41`–`\57` | `!"#$%&'()*+,-./` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 48–57 | `\x30`–`\x39` | `\60`–`\71` | `0123456789` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** |
| 58–64 | `\x3A`–`\x40` | `\72`–`\100` | `:;<=>?@` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 65–70 | `\x41`–`\x46` | `\101`–`\106` | `ABCDEF` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** |
| 71–90 | `\x47`–`\x5A` | `\107`–`\132` | `GHIJKLMNOP``QRSTUVWXYZ` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** |
| 91–96 | `\x5B`–`\x60` | `\133`–`\140` | `[\]^_`` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 97–102 | `\x61`–`\x66` | `\141`–`\146` | `abcdef` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** |
| 103–122 | `\x67`–`\x7A` | `\147`–`\172` | `ghijklmnop``qrstuvwxyz` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`≠0`** | **`0`** | **`0`** |
| 123–126 | `\x7B`–`\x7E` | `\172`–`\176` | `{|}~` | **`0`** | **`≠0`** | **`0`** | **`0`** | **`≠0`** | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
| 127 | `\x7F` | `\177` | backspace character (`DEL`) | **`≠0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** | **`0`** |
c strndup strndup
=======
| Defined in header `<string.h>` | | |
| --- | --- | --- |
|
```
char *strndup( const char *src, size_t size );
```
| | (since C23) |
Returns a pointer to a null-terminated byte string, which contains copies of at most `size` bytes from the string pointed to by `src`. The space for the new string is obtained as if `[malloc](../../memory/malloc "c/memory/malloc")` was called. If the null terminator is not encountered in the first `size` bytes, it is appended to the duplicated string.
The returned pointer must be passed to `[free](../../memory/free "c/memory/free")` to avoid a memory leak.
If an error occurs, a null pointer is returned and `[errno](../../error/errno "c/error/errno")` might be set.
### Parameters
| | | |
| --- | --- | --- |
| src | - | pointer to the null-terminated byte string to duplicate |
| size | - | max number of bytes to copy from `src` |
### Return value
A pointer to the newly allocated string, or a null pointer if an error occurred.
### Notes
The function is identical to the [POSIX strndup](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strdup.html) except that it is allowed, but not required to set `[errno](../../error/errno "c/error/errno")` on error.
### Example
```
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const size_t n = 3;
const char *src = "Replica";
char *dup = strndup(src, n);
printf("strndup(\"%s\", %lu) == \"%s\"\n", src, n, dup);
free(dup);
src = "Hi";
dup = strndup(src, n);
printf("strndup(\"%s\", %lu) == \"%s\"\n", src, n, dup);
free(dup);
const char arr[] = {'A','B','C','D'}; // NB: no trailing '\0'
dup = strndup(arr, n);
printf("strndup({'A','B','C','D'}, %lu) == \"%s\"\n", n, dup);
free(dup);
}
```
Output:
```
strndup("Replica", 3) == "Rep"
strndup("Hi", 3) == "Hi"
strndup({'A','B','C','D'}, 3) == "ABC"
```
### See also
| | |
| --- | --- |
| [strdup](strdup "c/string/byte/strdup")
(C23) | allocates a copy of a string (function) |
| [strcpystrcpy\_s](strcpy "c/string/byte/strcpy")
(C11) | copies one string to another (function) |
| [malloc](../../memory/malloc "c/memory/malloc") | allocates memory (function) |
| [free](../../memory/free "c/memory/free") | deallocates previously allocated memory (function) |
c strtof, strtod, strtold strtof, strtod, strtold
=======================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
float strtof( const char *restrict str, char **restrict str_end );
```
| | (since C99) |
|
```
double strtod( const char *str, char **str_end );
```
| | (until C99) |
|
```
double strtod( const char *restrict str, char **restrict str_end );
```
| | (since C99) |
|
```
long double strtold( const char *restrict str, char **restrict str_end );
```
| | (since C99) |
Interprets a floating-point value in a byte string pointed to by `str`.
Function discards any whitespace characters (as determined by `std::[isspace](http://en.cppreference.com/w/c/string/byte/isspace)()`) until first non-whitespace character is found. Then it takes as many characters as possible to form a valid floating-point representation and converts them to a floating-point value. The valid floating-point value can be one of the following:
* decimal floating-point expression. It consists of the following parts:
+ (optional) plus or minus sign
+ nonempty sequence of decimal digits optionally containing decimal-point character (as determined by the current C [locale](../../locale/setlocale "c/locale/setlocale")) (defines significand)
+ (optional) `e` or `E` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 10)
| | |
| --- | --- |
| * hexadecimal floating-point expression. It consists of the following parts:
+ (optional) plus or minus sign
+ `0x` or `0X`
+ nonempty sequence of hexadecimal digits optionally containing a decimal-point character (as determined by the current C [locale](../../locale/setlocale "c/locale/setlocale")) (defines significand)
+ (optional) `p` or `P` followed with optional minus or plus sign and nonempty sequence of decimal digits (defines exponent to base 2)
* infinity expression. It consists of the following parts:
+ (optional) plus or minus sign
+ `INF` or `INFINITY` ignoring case
* not-a-number expression. It consists of the following parts:
+ (optional) plus or minus sign
+ `NAN` or `NAN(`*char\_sequence*`)` ignoring case of the `NAN` part. *char\_sequence* can only contain digits, Latin letters, and underscores. The result is a quiet NaN floating-point value.
| (since C99) |
* any other expression that may be accepted by the currently installed C [locale](../../locale/setlocale "c/locale/setlocale")
The functions sets the pointer pointed to by `str_end` to point to the character past the last character interpreted. If `str_end` is a null pointer, it is ignored.
### Parameters
| | | |
| --- | --- | --- |
| str | - | pointer to the null-terminated byte string to be interpreted |
| str\_end | - | pointer to a pointer to character. |
### Return value
Floating-point value corresponding to the contents of `str` on success. If the converted value falls out of range of corresponding return type, range error occurs and `[HUGE\_VAL](../../numeric/math/huge_val "c/numeric/math/HUGE VAL")`, `[HUGE\_VALF](../../numeric/math/huge_val "c/numeric/math/HUGE VAL")` or `[HUGE\_VALL](../../numeric/math/huge_val "c/numeric/math/HUGE VAL")` is returned. If no conversion can be performed, `0` is returned.
### Example
```
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
int main(void)
{
// parsing with error handling
const char *p = "111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6 1.18973e+4932zzz";
printf("Parsing '%s':\n", p);
char *end;
for (double f = strtod(p, &end); p != end; f = strtod(p, &end))
{
printf("'%.*s' -> ", (int)(end-p), p);
p = end;
if (errno == ERANGE){
printf("range error, got ");
errno = 0;
}
printf("%f\n", f);
}
// parsing without error handling
printf("\" -0.0000000123junk\" --> %g\n", strtod(" -0.0000000123junk", NULL));
printf("\"junk\" --> %g\n", strtod("junk", NULL));
}
```
Possible output:
```
Parsing '111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6 1.18973e+4932zzz':
'111.11' -> 111.110000
' -2.22' -> -2.220000
' Nan' -> nan
' nan(2)' -> nan
' inF' -> inf
' 0X1.BC70A3D70A3D7P+6' -> 111.110000
' 1.18973e+4932' -> range error, got inf
" -0.0000000123junk" --> -1.23e-08
"junk" --> 0
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.1.3 The strtod, strtof, and strtold functions (p: 249-251)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.1.3 The strtod, strtof, and strtold functions (p: 342-344)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.1.3 The strtod, strtof, and strtold functions (p: 308-310)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.1.4 The strtod function
### See also
| | |
| --- | --- |
| [atof](atof "c/string/byte/atof") | converts a byte string to a floating-point value (function) |
| [wcstofwcstodwcstold](../wide/wcstof "c/string/wide/wcstof")
(C99)(C95)(C99) | converts a wide string to a floating-point value (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strtof "cpp/string/byte/strtof") for `strtof, strtod, strtold` |
c strncpy, strncpy_s strncpy, strncpy\_s
===================
| Defined in header `<string.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
char *strncpy( char *dest, const char *src, size_t count );
```
| (until C99) |
|
```
char *strncpy( char *restrict dest, const char *restrict src, size_t count );
```
| (since C99) |
|
```
errno_t strncpy_s( char *restrict dest, rsize_t destsz,
const char *restrict src, rsize_t count );
```
| (2) | (since C11) |
1) Copies at most `count` characters of the character array pointed to by `src` (including the terminating null character, but not any of the characters that follow the null character) to character array pointed to by `dest`.
If `count` is reached before the entire array `src` was copied, the resulting character array is not null-terminated.
If, after copying the terminating null character from `src`, `count` is not reached, additional null characters are written to `dest` until the total of `count` characters have been written.
The behavior is undefined if the character arrays overlap, if either `dest` or `src` is not a pointer to a character array (including if `dest` or `src` is a null pointer), if the size of the array pointed to by `dest` is less than `count`, or if the size of the array pointed to by `src` is less than `count` and it does not contain a null character.
2) Same as (1), except that the function does not continue writing zeroes into the destination array to pad up to `count`, it stops after writing the terminating null character (if there was no null in the source, it writes one at `dest[count]` and then stops). Also, the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function: * `src` or `dest` is a null pointer
* `destsz` is zero or greater than `RSIZE_MAX`
* `count` is greater than `RSIZE_MAX`
* `count` is greater or equal `destsz`, but `destsz` is less or equal `strnlen_s(src, count)`, in other words, truncation would occur
* overlap would occur between the source and the destination strings
The behavior is undefined if the size of the character array pointed to by `dest` < `strnlen_s(src, destsz)` <= `destsz`; in other words, an erroneous value of `destsz` does not expose the impending buffer overflow. The behavior is undefined if the size of the character array pointed to by `src` < `strnlen_s(src, count)` < `destsz`; in other words, an erroneous value of `count` does not expose the impending buffer overflow. As with all bounds-checked functions, `strncpy_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<string.h>`. ### Parameters
| | | |
| --- | --- | --- |
| dest | - | pointer to the character array to copy to |
| src | - | pointer to the character array to copy from |
| count | - | maximum number of characters to copy |
| destsz | - | the size of the destination buffer |
### Return value
1) returns a copy of `dest`
2) returns zero on success, returns non-zero on error. Also, on error, writes zero to `dest[0]` (unless `dest` is a null pointer or `destsz` is zero or greater than `RSIZE_MAX`) and may clobber the rest of the destination array with unspecified values. ### Notes
As corrected by the post-C11 DR 468, `strncpy_s`, unlike `[strcpy\_s](strcpy "c/string/byte/strcpy")`, is only allowed to clobber the remainder of the destination array if an error occurs.
Unlike `strncpy`, `strncpy_s` does not pad the destination array with zeroes, This is a common source of errors when converting existing code to the bounds-checked version.
Although truncation to fit the destination buffer is a security risk and therefore a runtime constraints violation for `strncpy_s`, it is possible to get the truncating behavior by specifying `count` equal to the size of the destination array minus one: it will copy the first `count` bytes and append the null terminator as always: `strncpy_s(dst, sizeof dst, src, (sizeof dst)-1);`
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(void)
{
char src[] = "hi";
char dest[6] = "abcdef"; // no null terminator
strncpy(dest, src, 5); // writes five characters 'h', 'i', '\0', '\0', '\0' to dest
printf("strncpy(dest, src, 5) to a 6-byte dest gives : ");
for (size_t n = 0; n < sizeof dest; ++n) {
char c = dest[n];
c ? printf("'%c' ", c) : printf("'\\0' ");
}
printf("\nstrncpy(dest2, src, 2) to a 2-byte dst gives : ");
char dest2[2];
strncpy(dest2, src, 2); // truncation: writes two characters 'h', 'i', to dest2
for (size_t n = 0; n < sizeof dest2; ++n) {
char c = dest2[n];
c ? printf("'%c' ", c) : printf("'\\0' ");
}
printf("\n");
#ifdef __STDC_LIB_EXT1__
set_constraint_handler_s(ignore_handler_s);
char dst1[6], src1[100] = "hello";
errno_t r1 = strncpy_s(dst1, 6, src1, 100); // writes 0 to r1, 6 characters to dst1
printf("dst1 = \"%s\", r1 = %d\n", dst1,r1); // 'h','e','l','l','o','\0' to dst1
char dst2[5], src2[7] = {'g','o','o','d','b','y','e'};
errno_t r2 = strncpy_s(dst2, 5, src2, 7); // copy overflows the destination array
printf("dst2 = \"%s\", r2 = %d\n", dst2,r2); // writes nonzero to r2,'\0' to dst2[0]
char dst3[5];
errno_t r3 = strncpy_s(dst3, 5, src2, 4); // writes 0 to r3, 5 characters to dst3
printf("dst3 = \"%s\", r3 = %d\n", dst3,r3); // 'g', 'o', 'o', 'd', '\0' to dst3
#endif
}
```
Possible output:
```
strncpy(dest, src, 5) to a 6-byte dst gives : 'h' 'i' '\0' '\0' '\0' 'f'
strncpy(dest2, src, 2) to a 2-byte dst gives : 'h' 'i'
dst1 = "hello", r1 = 0
dst2 = "", r2 = 22
dst3 = "good", r3 = 0
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.24.2.4 The strncpy function (p: 265)
+ K.3.7.1.4 The strncpy\_s function (p: 447-448)
* C11 standard (ISO/IEC 9899:2011):
+ 7.24.2.4 The strncpy function (p: 363-364)
+ K.3.7.1.4 The strncpy\_s function (p: 616-617)
* C99 standard (ISO/IEC 9899:1999):
+ 7.21.2.4 The strncpy function (p: 326-327)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.11.2.4 The strncpy function
### See also
| | |
| --- | --- |
| [strcpystrcpy\_s](strcpy "c/string/byte/strcpy")
(C11) | copies one string to another (function) |
| [memcpymemcpy\_s](memcpy "c/string/byte/memcpy")
(C11) | copies one buffer to another (function) |
| [strndup](https://en.cppreference.com/w/c/experimental/dynamic/strndup "c/experimental/dynamic/strndup")
(dynamic memory TR) | allocate a copy of a string up to specified size (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/byte/strncpy "cpp/string/byte/strncpy") for `strncpy` |
| programming_docs |
c mbsinit mbsinit
=======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
int mbsinit( const mbstate_t* ps);
```
| | (since C95) |
If `ps` is not a null pointer, the `mbsinit` function determines whether the pointed-to `[mbstate\_t](mbstate_t "c/string/multibyte/mbstate t")` object describes the initial conversion state.
### Notes
Although a zero-initialized `[mbstate\_t](mbstate_t "c/string/multibyte/mbstate t")` always represents the initial conversion state, there may be other values of `[mbstate\_t](mbstate_t "c/string/multibyte/mbstate t")` that also represent the initial conversion state.
### Parameters
| | | |
| --- | --- | --- |
| ps | - | pointer to the mbstate\_t object to examine |
### Return value
`0` if `ps` is not a null pointer and does not represent the initial conversion state, nonzero value otherwise.
### Example
```
#include <locale.h>
#include <string.h>
#include <stdio.h>
#include <wchar.h>
int main(void)
{
// allow mbrlen() to work with UTF-8 multibyte encoding
setlocale(LC_ALL, "en_US.utf8");
// UTF-8 narrow multibyte encoding
const char* str = u8"水"; // or u8"\u6c34" or "\xe6\xb0\xb4"
static mbstate_t mb; // zero-initialize
(void)mbrlen(&str[0], 1, &mb);
if (!mbsinit(&mb)) {
printf("After processing the first 1 byte of %s,\n"
"the conversion state is not initial\n\n", str);
}
(void)mbrlen(&str[1], strlen(str), &mb);
if (mbsinit(&mb)) {
printf("After processing the remaining 2 bytes of %s,\n"
"the conversion state is initial conversion state\n", str);
}
}
```
Output:
```
After processing the first 1 byte of 水,
the conversion state is not initial
After processing the remaining 2 bytes of 水,
the conversion state is initial conversion state
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.29.6.2.1 The mbsinit function (p: 322)
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.6.2.1 The mbsinit function (p: 441-442)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.6.2.1 The mbsinit function (p: 387-388)
### See also
| | |
| --- | --- |
| [mbstate\_t](mbstate_t "c/string/multibyte/mbstate t")
(C95) | conversion state information necessary to iterate multibyte character strings (class) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/mbsinit "cpp/string/multibyte/mbsinit") for `mbsinit` |
c btowc btowc
=====
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
wint_t btowc( int c );
```
| | (since C95) |
Widens a single-byte character `c` (reinterpreted as `unsigned char`) to its wide character equivalent.
Most multibyte character encodings use single-byte codes to represent the characters from the ASCII character set. This function may be used to convert such characters to `wchar_t`.
### Parameters
| | | |
| --- | --- | --- |
| c | - | single-byte character to widen |
### Return value
`WEOF` if `c` is `[EOF](../../io "c/io")`.
wide character representation of `c` if `(unsigned char)c` is a valid single-byte character in the initial shift state, `WEOF` otherwise.
### Example
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
#include <assert.h>
void try_widen(unsigned char c)
{
wint_t w = btowc(c);
if(w != WEOF)
printf("The single-byte character %#x widens to %#x\n", c, w);
else
printf("The single-byte character %#x failed to widen\n", c);
}
int main(void)
{
char *loc = setlocale(LC_ALL, "lt_LT.iso88594");
assert(loc);
printf("In Lithuanian ISO-8859-4 locale:\n");
try_widen('A');
try_widen('\xdf'); // German letter ß (U+00df) in ISO-8859-4
try_widen('\xf9'); // Lithuanian letter ų (U+0173) in ISO-8859-4
setlocale(LC_ALL, "lt_LT.utf8");
printf("In Lithuanian UTF-8 locale:\n");
try_widen('A');
try_widen('\xdf');
try_widen('\xf9');
}
```
Possible output:
```
In Lithuanian ISO-8859-4 locale:
The single-byte character 0x41 widens to 0x41
The single-byte character 0xdf widens to 0xdf
The single-byte character 0xf9 widens to 0x173
In Lithuanian UTF-8 locale:
The single-byte character 0x41 widens to 0x41
The single-byte character 0xdf failed to widen
The single-byte character 0xf9 failed to widen
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.6.1.1 The btowc function (p: 441)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.6.1.1 The btowc function (p: 387)
### See also
| | |
| --- | --- |
| [wctob](wctob "c/string/multibyte/wctob")
(C95) | narrows a wide character to a single-byte narrow character, if possible (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/btowc "cpp/string/multibyte/btowc") for `btowc` |
c mbrlen mbrlen
======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
size_t mbrlen( const char *s, size_t n, mbstate_t *ps );
```
| | (since C95) (until C99) |
|
```
size_t mbrlen( const char *restrict s, size_t n, mbstate_t *restrict ps );
```
| | (since C99) |
Determines the size, in bytes, of the representation of a multibyte character.
This function is equivalent to the call `[mbrtowc](http://en.cppreference.com/w/c/string/multibyte/mbrtowc)([NULL](http://en.cppreference.com/w/c/types/NULL), s, n, ps?ps:&internal)` for some hidden object `internal` of type `[mbstate\_t](mbstate_t "c/string/multibyte/mbstate t")`, except that the expression `ps` is evaluated only once.
### Parameters
| | | |
| --- | --- | --- |
| s | - | pointer to an element of a multibyte character string |
| n | - | limit on the number of bytes in s that can be examined |
| ps | - | pointer to the variable holding the conversion state |
### Return value
The first of the following that applies:
* `0` if the next `n` or fewer bytes complete the null character or if `s` is a null pointer. Both cases reset the conversion state.
* the number of bytes `[1...n]` that complete a valid multibyte character
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-2` if the next `n` bytes are part of a possibly valid multibyte character, which is still incomplete after examining all `n` bytes
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1` if encoding error occurs. The value of `[errno](../../error/errno "c/error/errno")` is `EILSEQ`; the conversion state is unspecified.
### Example
```
#include <locale.h>
#include <string.h>
#include <stdio.h>
#include <wchar.h>
int main(void)
{
// allow mbrlen() to work with UTF-8 multibyte encoding
setlocale(LC_ALL, "en_US.utf8");
// UTF-8 narrow multibyte encoding
const char* str = u8"水";
size_t sz = strlen(str);
mbstate_t mb;
memset(&mb, 0, sizeof mb);
int len1 = mbrlen(str, 1, &mb);
if(len1 == -2)
printf("The first 1 byte of %s is an incomplete multibyte char"
" (mbrlen returns -2)\n", str);
int len2 = mbrlen(str+1, sz-1, &mb);
printf("The remaining %zu bytes of %s hold %d bytes of the multibyte"
" character\n", sz-1, str, len2);
printf("Attempting to call mbrlen() in the middle of %s while in initial"
" shift state returns %zd\n", str, mbrlen(str+1, sz-1, &mb));
}
```
Output:
```
The first 1 byte of 水 is an incomplete multibyte char (mbrlen returns -2)
The remaining 2 bytes of 水 hold 2 bytes of the multibyte character
Attempting to call mbrlen() in the middle of 水 while in initial shift state returns -1
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.6.3.1 The mbrlen function (p: 442)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.6.3.1 The mbrlen function (p: 388)
### See also
| | |
| --- | --- |
| [mbrtowc](mbrtowc "c/string/multibyte/mbrtowc")
(C95) | converts the next multibyte character to wide character, given state (function) |
| [mblen](mblen "c/string/multibyte/mblen") | returns the number of bytes in the next multibyte character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/mbrlen "cpp/string/multibyte/mbrlen") for `mbrlen` |
c mbrtowc mbrtowc
=======
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
size_t mbrtowc( wchar_t* pwc, const char* s, size_t n, mbstate_t* ps );
```
| | (since C95) |
|
```
size_t mbrtowc( wchar_t *restrict pwc, const char *restrict s, size_t n,
mbstate_t *restrict ps );
```
| | (since C99) |
Converts a narrow multibyte character to its wide character representation.
If `s` is not a null pointer, inspects at most `n` bytes of the multibyte character string, beginning with the byte pointed to by `s` to determine the number of bytes necessary to complete the next multibyte character (including any shift sequences, and taking into account the current multibyte conversion state `*ps`). If the function determines that the next multibyte character in `s` is complete and valid, converts it to the corresponding wide character and stores it in `*pwc` (if `pwc` is not null).
If `s` is a null pointer, the values of `n` and `pwc` are ignored and call is equivalent to `mbrtowc([NULL](http://en.cppreference.com/w/c/types/NULL), "", 1, ps)`.
If the wide character produced is the null character, the conversion state stored in `*ps` is the initial shift state.
If the environment macro `__STDC_ISO_10646__` is defined, the values of type `wchar_t` are the same as the short identifiers of the characters in the Unicode required set (typically UTF-32 encoding); otherwise, it is implementation-defined. In any case, the multibyte character encoding used by this function is specified by the currently active C locale.
### Parameters
| | | |
| --- | --- | --- |
| pwc | - | pointer to the location where the resulting wide character will be written |
| s | - | pointer to the multibyte character string used as input |
| n | - | limit on the number of bytes in s that can be examined |
| ps | - | pointer to the conversion state used when interpreting the multibyte character string |
### Return value
The first of the following that applies:
* `0` if the character converted from `s` (and stored in `pwc` if non-null) was the null character
* the number of bytes `[1...n]` of the multibyte character successfully converted from `s`
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-2` if the next `n` bytes constitute an incomplete, but so far valid, multibyte character. Nothing is written to `*pwc`.
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1` if encoding error occurs. Nothing is written to `*pwc`, the value `[EILSEQ](../../error/errno_macros "c/error/errno macros")` is stored in `[errno](../../error/errno "c/error/errno")` and the value of `*ps` is left unspecified.
### Example
```
#include <stdio.h>
#include <locale.h>
#include <string.h>
#include <wchar.h>
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
mbstate_t state;
memset(&state, 0, sizeof state);
char in[] = u8"z\u00df\u6c34\U0001F34C"; // or u8"zß水🍌"
size_t in_sz = sizeof in / sizeof *in;
printf("Processing %zu UTF-8 code units: [ ", in_sz);
for(size_t n = 0; n < in_sz; ++n) printf("%#x ", (unsigned char)in[n]);
puts("]");
wchar_t out[in_sz];
char *p_in = in, *end = in + in_sz;
wchar_t *p_out = out;
int rc;
while((rc = mbrtowc(p_out, p_in, end - p_in, &state)) > 0)
{
p_in += rc;
p_out += 1;
}
size_t out_sz = p_out - out + 1;
printf("into %zu wchar_t units: [ ", out_sz);
for(size_t x = 0; x < out_sz; ++x) printf("%#x ", out[x]);
puts("]");
}
```
Output:
```
Processing 11 UTF-8 code units: [ 0x7a 0xc3 0x9f 0xe6 0xb0 0xb4 0xf0 0x9f 0x8d 0x8c 0 ]
into 5 wchar_t units: [ 0x7a 0xdf 0x6c34 0x1f34c 0 ]
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.6.3.2 The mbrtowc function (p: 443)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.6.3.2 The mbrtowc function (p: 389)
### See also
| | |
| --- | --- |
| [mbtowc](mbtowc "c/string/multibyte/mbtowc") | converts the next multibyte character to wide character (function) |
| [wcrtombwcrtomb\_s](wcrtomb "c/string/multibyte/wcrtomb")
(C95)(C11) | converts a wide character to its multibyte representation, given state (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/mbrtowc "cpp/string/multibyte/mbrtowc") for `mbrtowc` |
c c16rtomb c16rtomb
========
| Defined in header `<uchar.h>` | | |
| --- | --- | --- |
|
```
size_t c16rtomb( char * restrict s, char16_t c16, mbstate_t * restrict ps );
```
| | (since C11) |
Converts a single code point from its variable-length 16-bit wide character representation (typically, UTF-16) to its narrow multibyte character representation.
If `s` is not a null pointer and `c16` is the last 16-bit code unit in a valid variable-length encoding of a code point, the function determines the number of bytes necessary to store the multibyte character representation of that code point (including any shift sequences, and taking into account the current multibyte conversion state `*ps`), and stores the multibyte character representation in the character array whose first element is pointed to by `s`, updating `*ps` as necessary. At most `MB_CUR_MAX` bytes can be written by this function.
If `s` is a null pointer, the call is equivalent to `c16rtomb(buf, u'\0', ps)` for some internal buffer `buf`.
If `c16` is the null wide character `u'\0'`, a null byte is stored, preceded by any shift sequence necessary to restore the initial shift state and the conversion state parameter `*ps` is updated to represent the initial shift state.
If `c16` is not the final code unit in a 16-bit representation of a wide character, it does not write to the array pointed to by `s`, only `*ps` is updated.
If the macro `__STDC_UTF_16__` is defined, the 16-bit encoding used by this function is UTF-16; otherwise, it is implementation-defined. In any case, the multibyte character encoding used by this function is specified by the currently active C locale.
### Parameters
| | | |
| --- | --- | --- |
| s | - | pointer to narrow character array where the multibyte character will be stored |
| c16 | - | the 16-bit wide character to convert |
| ps | - | pointer to the conversion state object used when interpreting the multibyte string |
### Return value
On success, returns the number of bytes (including any shift sequences) written to the character array whose first element is pointed to by `s`. This value may be `0`, e.g. when processing the leading `char16_t` units in a multi-`char16_t`-unit sequence (occurs when processing the leading surrogate in a surrogate pair of UTF-16).
On failure (if `c16` is not a valid 16-bit code unit), returns `-1`, stores `[EILSEQ](../../error/errno_macros "c/error/errno macros")` in `[errno](../../error/errno "c/error/errno")`, and leaves `*ps` in unspecified state.
### Notes
In C11 as published, unlike `[mbrtoc16](mbrtoc16 "c/string/multibyte/mbrtoc16")`, which converts variable-width multibyte (such as UTF-8) to variable-width 16-bit (such as UTF-16) encoding, this function can only convert single-unit 16-bit encoding, meaning it cannot convert UTF-16 to UTF-8 despite that being the original intent of this function. This was corrected by the post-C11 defect report [DR488](http://www.open-std.org/jtc1/sc22/WG14/www/docs/summary.htm#dr_488).
### Example
Note: this example assumes the fix for the defect report 488 is applied.
```
#include <stdio.h>
#include <locale.h>
#include <uchar.h>
#include <stdlib.h>
mbstate_t state;
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
char16_t in[] = u"zß水🍌"; // or "z\u00df\u6c34\U0001F34C"
size_t in_sz = sizeof in / sizeof *in;
printf("Processing %zu UTF-16 code units: [ ", in_sz);
for(size_t n = 0; n < in_sz; ++n) printf("%#x ", in[n]);
puts("]");
char out[MB_CUR_MAX * in_sz];
char *p = out;
for(size_t n = 0; n < in_sz; ++n) {
size_t rc = c16rtomb(p, in[n], &state);
if(rc == (size_t)-1) break;
p += rc;
}
size_t out_sz = p - out;
printf("into %zu UTF-8 code units: [ ", out_sz);
for(size_t x = 0; x < out_sz; ++x) printf("%#x ", +(unsigned char)out[x]);
puts("]");
}
```
Output:
```
Processing 6 UTF-16 code units: [ 0x7a 0xdf 0x6c34 0xd83c 0xdf4c 0 ]
into 11 UTF-8 code units: [ 0x7a 0xc3 0x9f 0xe6 0xb0 0xb4 0xf0 0x9f 0x8d 0x8c 0 ]
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.28.1.2 The c16rtomb function (p: 399-400)
### See also
| | |
| --- | --- |
| [mbrtoc16](mbrtoc16 "c/string/multibyte/mbrtoc16")
(C11) | generates the next 16-bit wide character from a narrow multibyte string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/c16rtomb "cpp/string/multibyte/c16rtomb") for `c16rtomb` |
c mbstate_t mbstate\_t
==========
| Defined in header `<uchar.h>` | | (since C11) |
| --- | --- | --- |
| Defined in header `<wchar.h>` | | |
|
```
struct mbstate_t;
```
| | (since C95) |
The type `mbstate_t` is a trivial non-array type that can represent any of the conversion states that can occur in an implementation-defined set of supported multibyte character encoding rules. Zero-initialized value of `mbstate_t` represents the initial conversion state, although other values of `mbstate_t` may exist that also represent the initial conversion state.
Possible implementation of `mbstate_t` is a struct type holding an array representing the incomplete multibyte character, an integer counter indicating the number of bytes in the array that have been processed, and a representation of the current shift state.
The following functions should not be called from multiple threads without synchronization with the `mbstate_t*` argument of a null pointer due to possible data races: `[mbrlen](mbrlen "c/string/multibyte/mbrlen")`, `[mbrtowc](mbrtowc "c/string/multibyte/mbrtowc")`, `[mbsrtowcs](mbsrtowcs "c/string/multibyte/mbsrtowcs")`, `[mbtowc](mbtowc "c/string/multibyte/mbtowc")`, `[wcrtomb](wcrtomb "c/string/multibyte/wcrtomb")`, `[wcsrtombs](wcsrtombs "c/string/multibyte/wcsrtombs")`, `[wctomb](wctomb "c/string/multibyte/wctomb")`.
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.1/2 Introduction (p: 402)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.1/2 Introduction (p: 348)
### See also
| | |
| --- | --- |
| [mbsinit](mbsinit "c/string/multibyte/mbsinit")
(C95) | checks if the mbstate\_t object represents initial shift state (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/mbstate_t "cpp/string/multibyte/mbstate t") for `mbstate_t` |
c wctomb, wctomb_s wctomb, wctomb\_s
=================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
int wctomb( char *s, wchar_t wc );
```
| (1) | |
|
```
errno_t wctomb_s( int *restrict status, char *restrict s, rsize_t ssz, wchar_t wc );
```
| (2) | (since C11) |
1) Converts a wide character `wc` to multibyte encoding and stores it (including any shift sequences) in the char array whose first element is pointed to by `s`. No more than `MB_CUR_MAX` characters are stored. The conversion is affected by the current locale's LC\_CTYPE category.
If `wc` is the null character, the null byte is written to `s`, preceded by any shift sequences necessary to restore the initial shift state.
If `s` is a null pointer, this function resets the global conversion state and determines whether shift sequences are used.
2) Same as (1), except that the result is returned in the out-parameter `status` and the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `ssz` is less than the number of bytes that would be written (unless `s` is null)
* `ssz` is greater than `RSIZE_MAX` (unless `s` is null)
* `s` is a null pointer but `ssz` is not zero
As with all bounds-checked functions, `wctomb_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<stdlib.h>`.
### Notes
Each call to `wctomb` updates the internal global conversion state (a static object of type `[mbstate\_t](mbstate_t "c/string/multibyte/mbstate t")`, known only to this function). If the multibyte encoding uses shift states, this function is not reentrant. In any case, multiple threads should not call `wctomb` without synchronization: `[wcrtomb](wcrtomb "c/string/multibyte/wcrtomb")` or `wctomb_s` may be used instead.
Unlike most bounds-checked functions, `wctomb_s` does not null-terminate its output, because it is designed to be used in loops that process strings character-by-character.
### Parameters
| | | |
| --- | --- | --- |
| s | - | pointer to the character array for output |
| wc | - | wide character to convert |
| ssz | - | maximum number of bytes to write to `s` (size of the array `s`) |
| status | - | pointer to an out-parameter where the result (length of the multibyte sequence or the shift sequence status) will be stored |
### Return value
1) If `s` is not a null pointer, returns the number of bytes that are contained in the multibyte representation of `wc` or `-1` if `wc` is not a valid character.
If `s` is a null pointer, resets its internal conversion state to represent the initial shift state and returns `0` if the current multibyte encoding is not state-dependent (does not use shift sequences) or a non-zero value if the current multibyte encoding is state-dependent (uses shift sequences).
2) zero on success, in which case the multibyte representation of `wc` is stored in `s` and its length is stored in `*status`, or, if `s` is null, the shift sequence status is stored in `status`). Non-zero on encoding error or runtime constraint violation, in which case `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1` is stored in `*status`. The value stored in `*status` never exceeds `MB_CUR_MAX`
### Example
```
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
void demo(wchar_t wc)
{
const char* dep = wctomb(NULL, wc) ? "Yes" : "No";
printf("State-dependent encoding? %s.\n", dep);
char mb[MB_CUR_MAX];
int len = wctomb(mb, wc);
printf("wide char '%lc' -> multibyte char [", wc);
for (int idx = 0; idx < len; ++idx)
printf("%s%#2x", idx ? " " : "", (unsigned char)mb[idx]);
printf("]\n");
}
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
printf("MB_CUR_MAX = %zu\n", MB_CUR_MAX);
demo(L'A');
demo(L'\u00df');
demo(L'\U0001d10b');
}
```
Possible output:
```
MB_CUR_MAX = 6
State-dependent encoding? No.
wide char 'A' -> multibyte char [0x41]
State-dependent encoding? No.
wide char 'ß' -> multibyte char [0xc3 0x9f]
State-dependent encoding? No.
wide char '𝄋' -> multibyte char [0xf0 0x9d 0x84 0x8b]
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.7.3 The wctomb function (p: 261)
+ K.3.6.4.1 The wctomb\_s function (p: 443)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.7.3 The wctomb function (p: 358-359)
+ K.3.6.4.1 The wctomb\_s function (p: 610-611)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.7.3 The wctomb function (p: 322-323)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.7.3 The wctomb function
### See also
| | |
| --- | --- |
| [mbtowc](mbtowc "c/string/multibyte/mbtowc") | converts the next multibyte character to wide character (function) |
| [wcrtombwcrtomb\_s](wcrtomb "c/string/multibyte/wcrtomb")
(C95)(C11) | converts a wide character to its multibyte representation, given state (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/wctomb "cpp/string/multibyte/wctomb") for `wctomb` |
| programming_docs |
c mbrtoc32 mbrtoc32
========
| Defined in header `<uchar.h>` | | |
| --- | --- | --- |
|
```
size_t mbrtoc32( char32_t restrict * pc32, const char * restrict s,
size_t n, mbstate_t * restrict ps );
```
| | (since C11) |
Converts a single code point from its narrow multibyte character representation to its variable-length 32-bit wide character representation (but typically, UTF-32).
If `s` is not a null pointer, inspects at most `n` bytes of the multibyte character string, beginning with the byte pointed to by `s` to determine the number of bytes necessary to complete the next multibyte character (including any shift sequences, and taking into account the current multibyte conversion state `*ps`). If the function determines that the next multibyte character in `s` is complete and valid, converts it to the corresponding 32-bit wide character and stores it in `*pc32` (if `pc32` is not null).
If the multibyte character in `*s` corresponds to a multi-char32\_t sequence (not possible with UTF-32), then after the first call to this function, `*ps` is updated in such a way that the next calls to `mbrtoc32` will write out the additional char32\_t, without considering `*s`.
If `s` is a null pointer, the values of `n` and `pc32` are ignored and the call is equivalent to `mbrtoc32([NULL](http://en.cppreference.com/w/c/types/NULL), "", 1, ps)`.
If the wide character produced is the null character, the conversion state `*ps` represents the initial shift state.
If the macro `__STDC_UTF_32__` is defined, the 32-bit encoding used by this function is UTF-32; otherwise, it is implementation-defined. In any case, the multibyte character encoding used by this function is specified by the currently active C locale.
### Parameters
| | | |
| --- | --- | --- |
| pc32 | - | pointer to the location where the resulting 32-bit wide character will be written |
| s | - | pointer to the multibyte character string used as input |
| n | - | limit on the number of bytes in s that can be examined |
| ps | - | pointer to the conversion state object used when interpreting the multibyte string |
### Return value
The first of the following that applies:
* `0` if the character converted from `s` (and stored in `*pc32` if non-null) was the null character
* the number of bytes `[1...n]` of the multibyte character successfully converted from `s`
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-3` if the next `char32_t` from a multi-`char32_t` character has now been written to `*pc32`. No bytes are processed from the input in this case.
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-2` if the next `n` bytes constitute an incomplete, but so far valid, multibyte character. Nothing is written to `*pc32`.
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1` if encoding error occurs. Nothing is written to `*pc32`, the value `[EILSEQ](../../error/errno_macros "c/error/errno macros")` is stored in `[errno](../../error/errno "c/error/errno")` and the value of `*ps` is unspecified.
### Example
```
#include <stdio.h>
#include <locale.h>
#include <string.h>
#include <uchar.h>
#include <assert.h>
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
char in[] = u8"zß水🍌"; // or "z\u00df\u6c34\U0001F34C"
const size_t in_size = sizeof in / sizeof *in;
printf("Processing %zu UTF-8 code units: [ ", in_size);
for (size_t i = 0; i < in_size; ++i)
printf("0x%02x ", (unsigned char)in[i]);
puts("]");
char32_t out[in_size];
char32_t *p_out = out;
char *p_in = in, *end = in + in_size;
mbstate_t state;
memset(&state, 0, sizeof(state));
size_t rc;
while ((rc = mbrtoc32(p_out, p_in, end - p_in, &state)))
{
assert(rc != (size_t)-3); // no surrogate pairs in UTF-32
if (rc == (size_t)-1) break; // invalid input
if (rc == (size_t)-2) break; // truncated input
p_in += rc;
++p_out;
}
size_t out_size = p_out+1 - out;
printf("into %zu UTF-32 code units: [ ", out_size);
for (size_t i = 0; i < out_size; ++i)
printf("0x%08X ", out[i]);
puts("]");
}
```
Output:
```
Processing 11 UTF-8 code units: [ 0x7a 0xc3 0x9f 0xe6 0xb0 0xb4 0xf0 0x9f 0x8d 0x8c 0x00 ]
into 5 UTF-32 code units: [ 0x0000007A 0x000000DF 0x00006C34 0x0001F34C 0x00000000 ]
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.28.1.3 The mbrtoc32 function (p: 293-294)
* C11 standard (ISO/IEC 9899:2011):
+ 7.28.1.3 The mbrtoc32 function (p: 400-401)
### See also
| | |
| --- | --- |
| [c32rtomb](c32rtomb "c/string/multibyte/c32rtomb")
(C11) | converts a 32-bit wide character to narrow multibyte string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/mbrtoc32 "cpp/string/multibyte/mbrtoc32") for `mbrtoc32` |
c mbstowcs, mbstowcs_s mbstowcs, mbstowcs\_s
=====================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
size_t mbstowcs( wchar_t *dst, const char *src, size_t len)
```
| (until C99) |
|
```
size_t mbstowcs( wchar_t *restrict dst, const char *restrict src, size_t len)
```
| (since C99) |
|
```
errno_t mbstowcs_s(size_t *restrict retval, wchar_t *restrict dst,
rsize_t dstsz, const char *restrict src, rsize_t len);
```
| (2) | (since C11) |
1) Converts a multibyte character string from the array whose first element is pointed to by `src` to its wide character representation. Converted characters are stored in the successive elements of the array pointed to by `dst`. No more than `len` wide characters are written to the destination array.
Each character is converted as if by a call to `[mbtowc](mbtowc "c/string/multibyte/mbtowc")`, except that the mbtowc conversion state is unaffected. The conversion stops if:
\* The multibyte null character was converted and stored.
\* An invalid (in the current C locale) multibyte character was encountered.
\* The next wide character to be stored would exceed `len`.
If `src` and `dst` overlap, the behavior is undefined
2) Same as (1), except that
\* conversion is as-if by `[mbrtowc](mbrtowc "c/string/multibyte/mbrtowc")`, not `[mbtowc](mbtowc "c/string/multibyte/mbtowc")`
\* the function returns its result as an out-parameter `retval`
\* if no null character was written to `dst` after `len` wide characters were written, then `L'\0'` is stored in `dst[len]`, which means len+1 total wide characters are written
\* if `dst` is a null pointer, the number of wide characters that would be produced is stored in `*retval`
\* the function clobbers the destination array from the terminating null and until `dstsz`
\* If `src` and `dst` overlap, the behavior is unspecified.
\* the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `retval` or `src` is a null pointer
* `dstsz` or `len` is greater than `RSIZE_MAX/sizeof(wchar_t)` (unless `dst` is null)
* `dstsz` is not zero (unless `dst` is null)
* There is no null character in the first `dstsz` multibyte characters in the `src` array and `len` is greater than `dstsz` (unless `dst` is null)
As with all bounds-checked functions, `mbstowcs_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<stdlib.h>`.
### Notes
In most implementations, `mbstowcs` updates a global static object of type `[mbstate\_t](mbstate_t "c/string/multibyte/mbstate t")` as it processes through the string, and cannot be called simultaneously by two threads, `[mbsrtowcs](mbsrtowcs "c/string/multibyte/mbsrtowcs")` should be used in such cases.
POSIX specifies a common extension: if `dst` is a null pointer, this function returns the number of wide characters that would be written to `dst`, if converted. Similar behavior is standard for `mbstowcs_s` and for `[mbsrtowcs](mbsrtowcs "c/string/multibyte/mbsrtowcs")`.
### Parameters
| | | |
| --- | --- | --- |
| dst | - | pointer to wide character array where the wide string will be stored |
| src | - | pointer to the first element of a null-terminated multibyte string to convert |
| len | - | number of wide characters available in the array pointed to by dst |
| dstsz | - | max number of wide characters that will be written (size of the `dst` array) |
| retval | - | pointer to a size\_t object where the result will be stored |
### Return value
1) On success, returns the number of wide characters, excluding the terminating `L'\0'`, written to the destination array. On conversion error (if invalid multibyte character was encountered), returns `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1`.
2) zero on success (in which case the number of wide characters excluding terminating zero that were, or would be written to `dst`, is stored in `*retval`), non-zero on error. In case of a runtime constraint violation, stores `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1` in `*retval` (unless `retval` is null) and sets `dst[0]` to `L'\0'` (unless `dst` is null or `dstmax` is zero or greater than `RSIZE_MAX`) ### Example
```
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
#include <wchar.h>
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
const char* mbstr = u8"z\u00df\u6c34\U0001F34C"; // or u8"zß水🍌"
wchar_t wstr[5];
mbstowcs(wstr, mbstr, 5);
wprintf(L"MB string: %s\n", mbstr);
wprintf(L"Wide string: %ls\n", wstr);
}
```
Output:
```
MB string: zß水🍌
Wide string: zß水🍌
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.8.1 The mbstowcs function (p: 359)
+ K.3.6.5.1 The mbstowcs\_s function (p: 611-612)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.8.1 The mbstowcs function (p: 323)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.8.1 The mbstowcs function
### See also
| | |
| --- | --- |
| [mbsrtowcsmbsrtowcs\_s](mbsrtowcs "c/string/multibyte/mbsrtowcs")
(C95)(C11) | converts a narrow multibyte character string to wide string, given state (function) |
| [wcstombswcstombs\_s](wcstombs "c/string/multibyte/wcstombs")
(C11) | converts a wide string to narrow multibyte character string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/mbstowcs "cpp/string/multibyte/mbstowcs") for `mbstowcs` |
c wcstombs, wcstombs_s wcstombs, wcstombs\_s
=====================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
size_t wcstombs( char *dst, const wchar_t *src, size_t len );
```
| (until C99) |
|
```
size_t wcstombs( char *restrict dst, const wchar_t *restrict src, size_t len );
```
| (since C99) |
|
```
errno_t wcstombs_s( size_t *restrict retval, char *restrict dst, rsize_t dstsz,
const wchar_t *restrict src, rsize_t len );
```
| (2) | (since C11) |
1) Converts a sequence of wide characters from the array whose first element is pointed to by `src` to its narrow multibyte representation that begins in the initial shift state. Converted characters are stored in the successive elements of the char array pointed to by `dst`. No more than `len` bytes are written to the destination array.
Each character is converted as if by a call to `[wctomb](wctomb "c/string/multibyte/wctomb")`, except that the wctomb's conversion state is unaffected. The conversion stops if:
\* The null character `L'\0'` was converted and stored. The bytes stored in this case are the unshift sequence (if necessary) followed by `'\0'`,
\* A `wchar_t` was found that does not correspond to a valid character in the current C locale.
\* The next multibyte character to be stored would exceed `len`.
If `src` and `dst` overlap, the behavior is unspecified.
2) Same as (1), except that
\* conversion is as-if by `[wcrtomb](wcrtomb "c/string/multibyte/wcrtomb")`, not `[wctomb](wctomb "c/string/multibyte/wctomb")`
\* the function returns its result as an out-parameter `retval`
\* if the conversion stops without writing a null character, the function will store `'\0'` in the next byte in `dst`, which may be `dst[len]` or `dst[dstsz]`, whichever comes first (meaning up to len+1/dstsz+1 total bytes may be written). In this case, there may be no unshift sequence written before the terminating null.
\* if `dst` is a null pointer, the number of bytes that would be produced is stored in `*retval`
\* the function clobbers the destination array from the terminating null and until `dstsz`
\* If `src` and `dst` overlap, the behavior is unspecified.
\* the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `retval` or `src` is a null pointer
* `dstsz` or `len` is greater than `RSIZE_MAX` (unless `dst` is null)
* `dstsz` is not zero (unless `dst` is null)
* `len` is greater than `dstsz` and the conversion does not encounter null or encoding error in the `src` array by the time `dstsz` is reached (unless `dst` is null)
As with all bounds-checked functions, `wcstombs_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<stdlib.h>`.
### Notes
In most implementations, `wcstombs` updates a global static object of type `[mbstate\_t](mbstate_t "c/string/multibyte/mbstate t")` as it processes through the string, and cannot be called simultaneously by two threads, `[wcsrtombs](wcsrtombs "c/string/multibyte/wcsrtombs")` or `wcstombs_s` should be used in such cases.
POSIX specifies a common extension: if `dst` is a null pointer, this function returns the number of bytes that would be written to `dst`, if converted. Similar behavior is standard for `[wcsrtombs](wcsrtombs "c/string/multibyte/wcsrtombs")` and `wcstombs_s`.
### Parameters
| | | |
| --- | --- | --- |
| dst | - | pointer to narrow character array where the multibyte character will be stored |
| src | - | pointer to the first element of a null-terminated wide string to convert |
| len | - | number of bytes available in the array pointed to by dst |
| dstsz | - | max number of bytes that will be written (size of the `dst` array) |
| retval | - | pointer to a size\_t object where the result will be stored |
### Return value
1) On success, returns the number of bytes (including any shift sequences, but excluding the terminating `'\0'`) written to the character array whose first element is pointed to by `dst`. On conversion error (if invalid wide character was encountered), returns `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1`.
2) Returns zero on success (in which case the number of bytes excluding terminating zero that were, or would be written to `dst`, is stored in `*retval`), non-zero on error. In case of a runtime constraint violation, stores `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1` in `*retval` (unless `retval` is null) and sets `dst[0]` to `'\0'` (unless `dst` is null or `dstmax` is zero or greater than `RSIZE_MAX`) ### Example
```
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main(void)
{
// 4 wide characters
const wchar_t src[] = L"z\u00df\u6c34\U0001f34c";
// they occupy 10 bytes in UTF-8
char dst[11];
setlocale(LC_ALL, "en_US.utf8");
printf("wide-character string: '%ls'\n",src);
for (size_t ndx=0; ndx < sizeof src/sizeof src[0]; ++ndx)
printf(" src[%2zu] = %#8x\n", ndx, src[ndx]);
int rtn_val = wcstombs(dst, src, sizeof dst);
printf("rtn_val = %d\n", rtn_val);
if (rtn_val > 0)
printf("multibyte string: '%s'\n",dst);
for (size_t ndx=0; ndx<sizeof dst; ++ndx)
printf(" dst[%2zu] = %#2x\n", ndx, (unsigned char)dst[ndx]);
}
```
Output:
```
wide-character string: 'zß水🍌'
src[ 0] = 0x7a
src[ 1] = 0xdf
src[ 2] = 0x6c34
src[ 3] = 0x1f34c
src[ 4] = 0
rtn_val = 10
multibyte string: 'zß水🍌'
dst[ 0] = 0x7a
dst[ 1] = 0xc3
dst[ 2] = 0x9f
dst[ 3] = 0xe6
dst[ 4] = 0xb0
dst[ 5] = 0xb4
dst[ 6] = 0xf0
dst[ 7] = 0x9f
dst[ 8] = 0x8d
dst[ 9] = 0x8c
dst[10] = 0
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.8.2 The wcstombs function (p: 360)
+ K.3.6.5.2 The wcstombs\_s function (p: 612-614)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.8.2 The wcstombs function (p: 324)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.8.2 The wcstombs function
### See also
| | |
| --- | --- |
| [wcsrtombswcsrtombs\_s](wcsrtombs "c/string/multibyte/wcsrtombs")
(C95)(C11) | converts a wide string to narrow multibyte character string, given state (function) |
| [mbstowcsmbstowcs\_s](mbstowcs "c/string/multibyte/mbstowcs")
(C11) | converts a narrow multibyte character string to wide string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/wcstombs "cpp/string/multibyte/wcstombs") for `wcstombs` |
c mblen mblen
=====
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
int mblen( const char* s, size_t n );
```
| | |
Determines the size, in bytes, of the multibyte character whose first byte is pointed to by `s`.
If `s` is a null pointer, resets the global conversion state and (until C23) determined whether shift sequences are used.
This function is equivalent to the call `[mbtowc](http://en.cppreference.com/w/c/string/multibyte/mbtowc)((wchar\_t\*)0, s, n)`, except that conversion state of `[mbtowc](mbtowc "c/string/multibyte/mbtowc")` is unaffected.
### Parameters
| | | |
| --- | --- | --- |
| s | - | pointer to the multibyte character |
| n | - | limit on the number of bytes in s that can be examined |
### Return value
If `s` is not a null pointer, returns the number of bytes that are contained in the multibyte character or `-1` if the first bytes pointed to by `s` do not form a valid multibyte character or `0` if `s` is pointing at the null charcter `'\0'`.
If `s` is a null pointer, resets its internal conversion state to represent the initial shift state and (until C23) returns `0` if the current multibyte encoding is not state-dependent (does not use shift sequences) or a non-zero value if the current multibyte encoding is state-dependent (uses shift sequences).
### Notes
| | |
| --- | --- |
| Each call to `mblen` updates the internal global conversion state (a static object of type `[mbstate\_t](mbstate_t "c/string/multibyte/mbstate t")`, only known to this function). If the multibyte encoding uses shift states, care must be taken to avoid backtracking or multiple scans. In any case, multiple threads should not call `mblen` without synchronization: `[mbrlen](mbrlen "c/string/multibyte/mbrlen")` may be used instead. | (until C23) |
| `mblen` is not allowed to have an internal state. | (since C23) |
### Example
```
#include <string.h>
#include <stdlib.h>
#include <locale.h>
#include <stdio.h>
// the number of characters in a multibyte string is the sum of mblen()'s
// note: the simpler approach is mbstowcs(NULL, str, sz)
size_t strlen_mb(const char* ptr)
{
size_t result = 0;
const char* end = ptr + strlen(ptr);
mblen(NULL, 0); // reset the conversion state
while(ptr < end) {
int next = mblen(ptr, end - ptr);
if(next == -1) {
perror("strlen_mb");
break;
}
ptr += next;
++result;
}
return result;
}
void dump_bytes(const char* str)
{
const char* end = str + strlen(str);
for (; str != end; ++str) {
printf("%02X ", (unsigned char)str[0]);
}
printf("\n");
}
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
const char* str = "z\u00df\u6c34\U0001f34c";
printf("The string \"%s\" consists of %zu characters, but %zu bytes: ",
str, strlen_mb(str), strlen(str));
dump_bytes(str);
}
```
Possible output:
```
The string "zß水🍌" consists of 4 characters, but 10 bytes: 7A C3 9F E6 B0 B4 F0 9F 8D 8C
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.22.7.1 The mblen function (p: 260)
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.7.1 The mblen function (p: 357)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.7.1 The mblen function (p: 321)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.7.1 The mblen function
### See also
| | |
| --- | --- |
| [mbtowc](mbtowc "c/string/multibyte/mbtowc") | converts the next multibyte character to wide character (function) |
| [mbrlen](mbrlen "c/string/multibyte/mbrlen")
(C95) | returns the number of bytes in the next multibyte character, given state (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/mblen "cpp/string/multibyte/mblen") for `mblen` |
| programming_docs |
c wctob wctob
=====
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
|
```
int wctob( wint_t c );
```
| | (since C95) |
Narrows a wide character `c` if its multibyte character equivalent in the initial shift state is a single byte.
This is typically possible for the characters from the ASCII character set, since most multibyte encodings (such as UTF-8) use single bytes to encode those characters.
### Parameters
| | | |
| --- | --- | --- |
| c | - | wide character to narrow |
### Return value
`[EOF](../../io "c/io")` if `c` does not represent a multibyte character with length `1` in initial shift state.
otherwise, the single-byte representation of `c` as `unsigned char` converted to `int`.
### Example
```
#include <locale.h>
#include <wchar.h>
#include <stdio.h>
#include <assert.h>
void try_narrowing(wchar_t c)
{
int cn = wctob(c);
if(cn != EOF)
printf("%#x narrowed to %#x\n", c, cn);
else
printf("%#x could not be narrowed\n", c);
}
int main(void)
{
char* utf_locale_present = setlocale(LC_ALL, "th_TH.utf8");
assert(utf_locale_present);
puts("In Thai UTF-8 locale:");
try_narrowing(L'a');
try_narrowing(L'๛');
char* tis_locale_present = setlocale(LC_ALL, "th_TH.tis620");
assert(tis_locale_present);
puts("In Thai TIS-620 locale:");
try_narrowing(L'a');
try_narrowing(L'๛');
}
```
Possible output:
```
In Thai UTF-8 locale:
0x61 narrowed to 0x61
0xe5b could not be narrowed
In Thai TIS-620 locale:
0x61 narrowed to 0x61
0xe5b narrowed to 0xfb
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.6.1.2 The wctob function (p: 441)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.6.1.2 The wctob function (p: 387)
### See also
| | |
| --- | --- |
| [btowc](btowc "c/string/multibyte/btowc")
(C95) | widens a single-byte narrow character to wide character, if possible (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/wctob "cpp/string/multibyte/wctob") for `wctob` |
c mbsrtowcs, mbsrtowcs_s mbsrtowcs, mbsrtowcs\_s
=======================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
size_t mbsrtowcs( wchar_t* dst, const char** src, size_t len, mbstate_t* ps );
```
| (since C95) (until C99) |
|
```
size_t mbsrtowcs( wchar_t *restrict dst, const char **restrict src, size_t len,
mbstate_t *restrict ps );
```
| (since C99) |
|
```
errno_t mbsrtowcs_s( size_t *restrict retval,
wchar_t *restrict dst, rsize_t dstsz,
const char **restrict src, rsize_t len,
mbstate_t *restrict ps );
```
| (2) | (since C11) |
1) Converts a null-terminated multibyte character sequence, which begins in the conversion state described by `*ps`, from the array whose first element is pointed to by `*src` to its wide character representation. If `dst` is not null, converted characters are stored in the successive elements of the wchar\_t array pointed to by `dst`. No more than `len` wide characters are written to the destination array. Each multibyte character is converted as if by a call to `[mbrtowc](mbrtowc "c/string/multibyte/mbrtowc")`. The conversion stops if: * The multibyte null character was converted and stored. `*src` is set to null pointer value and `*ps` represents the initial shift state.
* An invalid multibyte character (according to the current C locale) was encountered. `*src` is set to point at the beginning of the first unconverted multibyte character.
* the next wide character to be stored would exceed `len`. `*src` is set to point at the beginning of the first unconverted multibyte character. This condition is not checked if `dst` is a null pointer.
2) Same as (1), except that * the function returns its result as an out-parameter `retval`
* if no null character was written to `dst` after `len` wide characters were written, then `L'\0'` is stored in `dst[len]`, which means len+1 total wide characters are written
* the function clobbers the destination array from the terminating null and until `dstsz`
* If `src` and `dst` overlap, the behavior is unspecified.
* the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `retval`, `ps`, `src`, or `*src` is a null pointer
* `dstsz` or `len` is greater than `RSIZE_MAX/sizeof(wchar_t)` (unless `dst` is null)
* `dstsz` is not zero (unless `dst` is null)
* There is no null character in the first `dstsz` multibyte characters in the `*src` array and `len` is greater than `dstsz` (unless `dst` is null)
As with all bounds-checked functions, `mbsrtowcs_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<wchar.h>`.
### Parameters
| | | |
| --- | --- | --- |
| dst | - | pointer to wide character array where the results will be stored |
| src | - | pointer to pointer to the first element of a null-terminated multibyte string |
| len | - | number of wide characters available in the array pointed to by dst |
| ps | - | pointer to the conversion state object |
| dstsz | - | max number of wide characters that will be written (size of the `dst` array) |
| retval | - | pointer to a size\_t object where the result will be stored |
### Return value
1) On success, returns the number of wide characters, excluding the terminating `L'\0'`, written to the character array. If `dst` is a null pointer, returns the number of wide characters that would have been written given unlimited length. On conversion error (if invalid multibyte character was encountered), returns `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1`, stores `[EILSEQ](../../error/errno_macros "c/error/errno macros")` in `[errno](../../error/errno "c/error/errno")`, and leaves `*ps` in unspecified state.
2) zero on success (in which case the number of wide characters excluding terminating zero that were, or would be written to `dst`, is stored in `*retval`), non-sero on error. In case of a runtime constraint violation, stores `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1` in `*retval` (unless `retval` is null) and sets `dst[0]` to `L'\0'` (unless `dst` is null or `dstmax` is zero or greater than `RSIZE_MAX`) ### Example
```
#include <stdio.h>
#include <locale.h>
#include <wchar.h>
#include <string.h>
void print_as_wide(const char* mbstr)
{
mbstate_t state;
memset(&state, 0, sizeof state);
size_t len = 1 + mbsrtowcs(NULL, &mbstr, 0, &state);
wchar_t wstr[len];
mbsrtowcs(&wstr[0], &mbstr, len, &state);
wprintf(L"Wide string: %ls \n", wstr);
wprintf(L"The length, including L'\\0': %zu\n", len);
}
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
print_as_wide(u8"z\u00df\u6c34\U0001f34c"); // u8"zß水🍌"
}
```
Output:
```
Wide string: zß水🍌
The length, including L'\0': 5
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.6.4.1 The mbsrtowcs function (p: 445)
+ K.3.9.3.2.1 The mbsrtowcs\_s function (p: 648-649)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.6.4.1 The mbsrtowcs function (p: 391)
### See also
| | |
| --- | --- |
| [mbstowcsmbstowcs\_s](mbstowcs "c/string/multibyte/mbstowcs")
(C11) | converts a narrow multibyte character string to wide string (function) |
| [mbrtowc](mbrtowc "c/string/multibyte/mbrtowc")
(C95) | converts the next multibyte character to wide character, given state (function) |
| [wcsrtombswcsrtombs\_s](wcsrtombs "c/string/multibyte/wcsrtombs")
(C95)(C11) | converts a wide string to narrow multibyte character string, given state (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/mbsrtowcs "cpp/string/multibyte/mbsrtowcs") for `mbsrtowcs` |
c mbtowc mbtowc
======
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
int mbtowc( wchar_t *pwc, const char *s, size_t n )
```
| | (until C99) |
|
```
int mbtowc( wchar_t *restrict pwc, const char *restrict s, size_t n )
```
| | (since C99) |
Converts a multibyte character whose first byte is pointed to by `s` to a wide character, written to `*pwc` if `pwc` is not null.
If `s` is a null pointer, resets the global conversion state and determines whether shift sequences are used.
### Notes
Each call to `mbtowc` updates the internal global conversion state (a static object of type `[mbstate\_t](mbstate_t "c/string/multibyte/mbstate t")`, known only to this function). If the multibyte encoding uses shift states, care must be taken to avoid backtracking or multiple scans. In any case, multiple threads should not call `mbtowc` without synchronization: `[mbrtowc](mbrtowc "c/string/multibyte/mbrtowc")` may be used instead.
### Parameters
| | | |
| --- | --- | --- |
| pwc | - | pointer to the wide character for output |
| s | - | pointer to the multibyte character |
| n | - | limit on the number of bytes in s that can be examined |
### Return value
If `s` is not a null pointer, returns the number of bytes that are contained in the multibyte character or `-1` if the first bytes pointed to by `s` do not form a valid multibyte character or `0` if `s` is pointing at the null charcter `'\0'`.
If `s` is a null pointer, resets its internal conversion state to represent the initial shift state and returns `0` if the current multibyte encoding is not state-dependent (does not use shift sequences) or a non-zero value if the current multibyte encoding is state-dependent (uses shift sequences).
### Example
```
#include <stdio.h>
#include <locale.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
// print multibyte string to wide-oriented stdout
// equivalent to wprintf(L"%s\n", ptr);
void print_mb(const char* ptr)
{
mbtowc(NULL, 0, 0); // reset the conversion state
const char* end = ptr + strlen(ptr);
int ret;
for (wchar_t wc; (ret = mbtowc(&wc, ptr, end-ptr)) > 0; ptr+=ret) {
wprintf(L"%lc", wc);
}
wprintf(L"\n");
}
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
// UTF-8 narrow multibyte encoding
print_mb(u8"z\u00df\u6c34\U0001F34C"); // or u8"zß水🍌"
}
```
Output:
```
zß水🍌
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.22.7.2 The mbtowc function (p: 358)
* C99 standard (ISO/IEC 9899:1999):
+ 7.20.7.2 The mbtowc function (p: 322)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.7.2 The mbtowc function
### See also
| | |
| --- | --- |
| [mbrtowc](mbrtowc "c/string/multibyte/mbrtowc")
(C95) | converts the next multibyte character to wide character, given state (function) |
| [mblen](mblen "c/string/multibyte/mblen") | returns the number of bytes in the next multibyte character (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/mbtowc "cpp/string/multibyte/mbtowc") for `mbtowc` |
c char32_t char32\_t
=========
| Defined in header `<uchar.h>` | | |
| --- | --- | --- |
|
```
typedef uint_least32_t char32_t;
```
| | (since C11) |
| Defined in header `<stdint.h>` | | |
|
```
typedef /*implementation-defined*/ uint_least32_t;
```
| | (since C99) |
`char32_t` is an unsigned integer type used for 32-bit wide characters and is the same type as `[uint\_least32\_t](http://en.cppreference.com/w/c/types/integer)`.
`[uint\_least32\_t](http://en.cppreference.com/w/c/types/integer)` is the smallest unsigned integer type with width of at least 32 bits.
### Notes
On any given platform, the width of type `char32_t` can be greater than 32 bits, but the actual values stored in an object of type `char32_t` will always have a width of 32 bits.
### Example
```
#include <uchar.h>
#include <stdio.h>
int main(void)
{
char32_t wc[] = U"zß水🍌"; // or "z\u00df\u6c34\U0001f34c"
size_t wc_sz = sizeof wc / sizeof *wc;
printf("%zu UTF-32 code units: [ ", wc_sz);
for (size_t n = 0; n < wc_sz; ++n) printf("%#x ", wc[n]);
printf("]\n");
}
```
Possible output:
```
5 UTF-32 code units: [ 0x7a 0xdf 0x6c34 0x1f34c 0 ]
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.28 Unicode utilities <uchar.h> (p: 398)
+ 7.20.1.2 Minimum-width integer types (p: 290)
* C99 standard (ISO/IEC 9899:1999):
+ 7.18.1.2 Minimum-width integer types (p: 256)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/types "cpp/language/types") for `Fundamental types` |
c c8rtomb c8rtomb
=======
| Defined in header `<uchar.h>` | | |
| --- | --- | --- |
|
```
size_t c8rtomb( char* s, char8_t c8, mbstate_t* ps );
```
| | (since C23) |
Converts a single code point from UTF-8 to a narrow multibyte character representation.
If `s` is not a null pointer and `c8` is the last code unit in a valid UTF-8 encoding of a code point, the function determines the number of bytes necessary to store the multibyte character representation of that code point (including any shift sequences, and taking into account the current multibyte conversion state `*ps`), and stores the multibyte character representation in the character array whose first element is pointed to by `s`, updating `*ps` as necessary. At most `MB_CUR_MAX` bytes can be written by this function.
If `c8` is not the final UTF-8 code unit in a representation of a code point, the function does not write to the array pointed to by `s`, only `*ps` is updated.
If `s` is a null pointer, the call is equivalent to `c8rtomb(buf, u8'\0', ps)` for some internal buffer `buf`.
If `c8` is the null character `u8'\0'`, a null byte is stored, preceded by any shift sequence necessary to restore the initial shift state and the conversion state parameter `*ps` is updated to represent the initial shift state.
The multibyte encoding used by this function is specified by the currently active C locale.
### Parameters
| | | |
| --- | --- | --- |
| s | - | pointer to narrow character array where the multibyte character will be stored |
| c8 | - | the UTF-8 code unit to convert |
| ps | - | pointer to the conversion state object used when interpreting the multibyte string |
### Return value
The number of bytes stored in the array object (including any shift sequences). This may be zero when `c8` is not the final code unit in the UTF-8 representation of a code point.
If `c8` is invalid (does not contribute to a sequence of `char8_t` corresponding to a valid multibyte character), the value of the macro `[EILSEQ](../../error/errno_macros "c/error/errno macros")` is stored in `[errno](../../error/errno "c/error/errno")`, `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1` is returned, and the conversion state is unspecified.
### Notes
Calls to `c8rtomb` with a null pointer argument for `s` may introduce a data race with other calls to `c8rtomb` with a null pointer argument for `s`.
### Example
### See also
| | |
| --- | --- |
| [mbrtoc8](mbrtoc8 "c/string/multibyte/mbrtoc8")
(C23) | converts a narrow multibyte character to UTF-8 encoding (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/c8rtomb "cpp/string/multibyte/c8rtomb") for `c8rtomb` |
c mbrtoc8 mbrtoc8
=======
| Defined in header `<uchar.h>` | | |
| --- | --- | --- |
|
```
size_t mbrtoc8( char8_t* pc8, const char* s, size_t n, mbstate_t* ps );
```
| | (since C23) |
Converts a narrow multibyte character to UTF-8 encoding.
If `s` is not a null pointer, inspects at most `n` bytes of the multibyte character string, beginning with the byte pointed to by `s` to determine the number of bytes necessary to complete the next multibyte character (including any shift sequences). If the function determines that the next multibyte character in `s` is complete and valid, converts it to UTF-8 and stores the first UTF-8 code unit in `*pc8` (if `pc8` is not null).
If UTF-8 encoding of the multibyte character in `*s` consists of more than one UTF-8 code unit, then after the first call to this function, `*ps` is updated in such a way that the next call to `mbrtoc8` will write out the additional UTF-8 code units, without considering `*s`.
If `s` is a null pointer, the values of `n` and `pc8` are ignored and the call is equivalent to `mbrtoc8(nullptr, "", 1, ps)`.
If UTF-8 code unit produced is `u8'\0'`, the conversion state `*ps` represents the initial shift state.
The multibyte encoding used by this function is specified by the currently active C locale.
### Parameters
| | | |
| --- | --- | --- |
| pc8 | - | pointer to the location where the resulting UTF-8 code units will be written |
| s | - | pointer to the multibyte character string used as input |
| n | - | limit on the number of bytes in s that can be examined |
| ps | - | pointer to the conversion state object used when interpreting the multibyte string |
### Return value
The first of the following that applies:
* `0` if the character converted from `s` (and stored in `*pc8` if non-null) was the null character
* the number of bytes `[1...n]` of the multibyte character successfully converted from `s`
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-3` if the next UTF-8 code unit from a character whose encoding consists of multiple code units has now been written to `*pc8`. No bytes are processed from the input in this case.
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-2` if the next `n` bytes constitute an incomplete, but so far valid, multibyte character. Nothing is written to `*pc8`.
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1` if encoding error occurs. Nothing is written to `*pc8`, the value `[EILSEQ](../../error/errno_macros "c/error/errno macros")` is stored in `[errno](../../error/errno "c/error/errno")` and the value of `*ps` is unspecified.
### Example
### See also
| | |
| --- | --- |
| [c8rtomb](c8rtomb "c/string/multibyte/c8rtomb")
(C23) | converts UTF-8 string to narrow multibyte encoding (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/mbrtoc8 "cpp/string/multibyte/mbrtoc8") for `mbrtoc8` |
c wcrtomb, wcrtomb_s wcrtomb, wcrtomb\_s
===================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
size_t wcrtomb( char *s, wchar_t wc, mbstate_t *ps);
```
| (since C95) |
|
```
size_t wcrtomb( char *restrict s, wchar_t wc, mbstate_t *restrict ps);
```
| (since C99) |
|
```
errno_t wcrtomb_s(size_t *restrict retval, char *restrict s, rsize_t ssz,
wchar_t wc, mbstate_t *restrict ps);
```
| (2) | (since C11) |
Converts a wide character to its narrow multibyte representation.
1) If `s` is not a null pointer, the function determines the number of bytes necessary to store the multibyte character representation of `wc` (including any shift sequences, and taking into account the current multibyte conversion state `*ps`), and stores the multibyte character representation in the character array whose first element is pointed to by `s`, updating `*ps` as necessary. At most `MB_CUR_MAX` bytes can be written by this function.
If `s` is a null pointer, the call is equivalent to `wcrtomb(buf, L'\0', ps)` for some internal buffer `buf`.
If wc is the null wide character `L'\0'`, a null byte is stored, preceded by any shift sequence necessary to restore the initial shift state and the conversion state parameter `*ps` is updated to represent the initial shift state.
If the environment macro `__STDC_ISO_10646__` is defined, the values of type `wchar_t` are the same as the short identifiers of the characters in the Unicode required set (typically UTF-32 encoding); otherwise, it is implementation-defined. In any case, the multibyte character encoding used by this function is specified by the currently active C locale.
2) Same as (1), except that
if `s` is a null pointer, the call is equivalent to `wcrtomb_s(&retval, buf, sizeof buf, L'\0', ps)` with internal variables `retval` and `buf` (whose size is greater than `MB_CUR_MAX`)
the result is returned in the out-parameter `retval`
the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `retval` or `ps` is a null pointer.
* `ssz` is zero or greater than `RSIZE_MAX` (unless `s` is null)
* `ssz` is less than the number of bytes that would be written (unless `s` is null)
* `s` is a null pointer but `ssz` is not zero
As with all bounds-checked functions, `wcrtomb_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<wchar.h>`.
### Parameters
| | | |
| --- | --- | --- |
| s | - | pointer to narrow character array where the multibyte character will be stored |
| wc | - | the wide character to convert |
| ps | - | pointer to the conversion state object used when interpreting the multibyte string |
| ssz | - | max number of bytes to write (the size of the buffer `s`) |
| retval | - | pointer to an out-parameter where the result (number of bytes in the multibyte string including any shift sequences) will be stored |
### Return value
1) On success, returns the number of bytes (including any shift sequences) written to the character array whose first element is pointed to by `s`.
On failure (if `wc` is not a valid wide character), returns `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1`, stores `[EILSEQ](../../error/errno_macros "c/error/errno macros")` in `[errno](../../error/errno "c/error/errno")`, and leaves `*ps` in unspecified state.
2) Returns zero on success and non-zero on failure, in which case, `s[0]` is set to `'\0'` (unless `s` is null or `ssz` is zero or greater than `RSIZE_MAX`) and `*retval` is set to `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1` (unless `retval` is null) ### Example
```
#include <stdio.h>
#include <locale.h>
#include <string.h>
#include <wchar.h>
#include <stdlib.h>
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
mbstate_t state;
memset(&state, 0, sizeof state);
wchar_t in[] = L"zß水🍌"; // or "z\u00df\u6c34\U0001F34C"
size_t in_sz = sizeof in / sizeof *in;
printf("Processing %zu wchar_t units: [ ", in_sz);
for(size_t n = 0; n < in_sz; ++n) printf("%#x ", (unsigned int)in[n]);
puts("]");
char out[MB_CUR_MAX * in_sz];
char *p = out;
for(size_t n = 0; n < in_sz; ++n) {
int rc = wcrtomb(p, in[n], &state);
if(rc == -1) break;
p += rc;
}
size_t out_sz = p - out;
printf("into %zu UTF-8 code units: [ ", out_sz);
for(size_t x = 0; x < out_sz; ++x) printf("%#x ", +(unsigned char)out[x]);
puts("]");
}
```
Output:
```
Processing 5 wchar_t units: [ 0x7a 0xdf 0x6c34 0x1f34c 0 ]
into 11 UTF-8 code units: [ 0x7a 0xc3 0x9f 0xe6 0xb0 0xb4 0xf0 0x9f 0x8d 0x8c 0 ]
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.6.3.3 The wcrtomb function (p: 444)
+ K.3.9.3.1.1 The wcrtomb\_s function (p: 647-648)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.6.3.3 The wcrtomb function (p: 390)
### See also
| | |
| --- | --- |
| [wctombwctomb\_s](wctomb "c/string/multibyte/wctomb")
(C11) | converts a wide character to its multibyte representation (function) |
| [mbrtowc](mbrtowc "c/string/multibyte/mbrtowc")
(C95) | converts the next multibyte character to wide character, given state (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/wcrtomb "cpp/string/multibyte/wcrtomb") for `wcrtomb` |
| programming_docs |
c c32rtomb c32rtomb
========
| Defined in header `<uchar.h>` | | |
| --- | --- | --- |
|
```
size_t c32rtomb( char * restrict s, char32_t c32, mbstate_t * restrict ps );
```
| | (since C11) |
Converts a single code point from its variable-length 32-bit wide character representation (but typically, UTF-32) to its narrow multibyte character representation.
If `s` is not a null pointer, the function determines the number of bytes necessary to store the multibyte character representation of `c32` (including any shift sequences, and taking into account the current multibyte conversion state `*ps`), and stores the multibyte character representation in the character array whose first element is pointed to by `s`, updating `*ps` as necessary. At most `MB_CUR_MAX` bytes can be written by this function.
If `s` is a null pointer, the call is equivalent to `c32rtomb(buf, U'\0', ps)` for some internal buffer `buf`.
If `c32` is the null wide character `U'\0'`, a null byte is stored, preceded by any shift sequence necessary to restore the initial shift state and the conversion state parameter `*ps` is updated to represent the initial shift state.
If the macro `__STDC_UTF_32__` is defined, the 32-bit encoding used by this function is UTF-32; otherwise, it is implementation-defined. In any case, the multibyte character encoding used by this function is specified by the currently active C locale.
### Parameters
| | | |
| --- | --- | --- |
| s | - | pointer to narrow character array where the multibyte character will be stored |
| c32 | - | the 32-bit wide character to convert |
| ps | - | pointer to the conversion state object used when interpreting the multibyte string |
### Return value
On success, returns the number of bytes (including any shift sequences) written to the character array whose first element is pointed to by `s`. This value may be `0`, e.g. when processing the leading `char32_t` units in a multi-`char32_t`-unit sequence (does not occur in UTF-32).
On failure (if `c32` is not a valid 32-bit wide character), returns `-1`, stores `[EILSEQ](../../error/errno_macros "c/error/errno macros")` in `[errno](../../error/errno "c/error/errno")`, and leaves `*ps` in unspecified state.
### Example
```
#include <stdio.h>
#include <locale.h>
#include <uchar.h>
#include <stdlib.h>
mbstate_t state;
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
char32_t in[] = U"zß水🍌"; // or "z\u00df\u6c34\U0001F34C"
size_t in_sz = sizeof in / sizeof *in;
printf("Processing %zu UTF-32 code units: [ ", in_sz);
for(size_t n = 0; n < in_sz; ++n) printf("%#x ", in[n]);
puts("]");
char out[MB_CUR_MAX * in_sz];
char *p = out;
for(size_t n = 0; n < in_sz; ++n) {
size_t rc = c32rtomb(p, in[n], &state);
if(rc == (size_t)-1) break;
p += rc;
}
size_t out_sz = p - out;
printf("into %zu UTF-8 code units: [ ", out_sz);
for(size_t x = 0; x < out_sz; ++x) printf("%#x ", +(unsigned char)out[x]);
puts("]");
}
```
Output:
```
Processing 5 UTF-32 code units: [ 0x7a 0xdf 0x6c34 0x1f34c 0 ]
into 11 UTF-8 code units: [ 0x7a 0xc3 0x9f 0xe6 0xb0 0xb4 0xf0 0x9f 0x8d 0x8c 0 ]
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.28.1.4 The c32rtomb function (p: 401)
### See also
| | |
| --- | --- |
| [mbrtoc32](mbrtoc32 "c/string/multibyte/mbrtoc32")
(C11) | generates the next 32-bit wide character from a narrow multibyte string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/c32rtomb "cpp/string/multibyte/c32rtomb") for `c32rtomb` |
c char16_t char16\_t
=========
| Defined in header `<uchar.h>` | | |
| --- | --- | --- |
|
```
typedef uint_least16_t char16_t;
```
| | (since C11) |
| Defined in header `<stdint.h>` | | |
|
```
typedef /*implementation-defined*/ uint_least16_t;
```
| | (since C99) |
`char16_t` is an unsigned integer type used for 16-bit wide characters and is the same type as `[uint\_least16\_t](http://en.cppreference.com/w/c/types/integer)`.
`[uint\_least16\_t](http://en.cppreference.com/w/c/types/integer)` is the smallest unsigned integer type with width of at least 16 bits.
### Notes
On any given platform, the width of type `char16_t` can be greater than 16 bits, but the actual values stored in an object of type `char16_t` will always have a width of 16 bits.
### Example
```
#include <uchar.h>
#include <stdio.h>
int main(void)
{
char16_t wcs[] = u"zß水🍌"; // or "z\u00df\u6c34\U0001f34c"
size_t wcs_sz = sizeof wcs / sizeof *wcs;
printf("%zu UTF-16 code units: [ ", wcs_sz);
for (size_t n = 0; n < wcs_sz; ++n) printf("%#x ", wcs[n]);
printf("]\n");
}
```
Possible output:
```
6 UTF-16 code units: [ 0x7a 0xdf 0x6c34 0xd83c 0xdf4c 0 ]
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.28 Unicode utilities <uchar.h> (p: 398)
+ 7.20.1.2 Minimum-width integer types (p: 290)
* C99 standard (ISO/IEC 9899:1999):
+ 7.18.1.2 Minimum-width integer types (p: 256)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/types "cpp/language/types") for `Fundamental types` |
c wcsrtombs, wcsrtombs_s wcsrtombs, wcsrtombs\_s
=======================
| Defined in header `<wchar.h>` | | |
| --- | --- | --- |
| | (1) | |
|
```
size_t wcsrtombs( char *dst, const wchar_t **src, size_t len, mbstate_t* ps );
```
| (since C95) (until C99) |
|
```
size_t wcsrtombs( char *restrict dst, const wchar_t **restrict src, size_t len,
mbstate_t *restrict ps );
```
| (since C99) |
|
```
errno_t wcsrtombs_s( size_t *restrict retval, char *restrict dst, rsize_t dstsz,
const wchar_t **restrict src, rsize_t len,
mbstate_t *restrict ps );
```
| (2) | (since C11) |
1) Converts a sequence of wide characters from the array whose first element is pointed to by `*src` to its narrow multibyte representation that begins in the conversion state described by `*ps`. If `dst` is not null, converted characters are stored in the successive elements of the char array pointed to by `dst`. No more than `len` bytes are written to the destination array. Each character is converted as if by a call to `[wcrtomb](wcrtomb "c/string/multibyte/wcrtomb")`. The conversion stops if: * The null character `L'\0'` was converted and stored. The bytes stored in this case are the unshift sequence (if necessary) followed by `'\0'`, `*src` is set to null pointer value and `*ps` represents the initial shift state.
* A `wchar_t` was found that does not correspond to a valid character in the current C locale. `*src` is set to point at the first unconverted wide character.
* the next multibyte character to be stored would exceed `len`. `*src` is set to point at the first unconverted wide character. This condition is not checked if `dst` is a null pointer.
2) Same as (1), except that * the function returns its result as an out-parameter `retval`
* if the conversion stops without writing a null character, the function will store `'\0'` in the next byte in `dst`, which may be `dst[len]` or `dst[dstsz]`, whichever comes first (meaning up to len+1/dstsz+1 total bytes may be written). In this case, there may be no unshift sequence written before the terminating null.
* the function clobbers the destination array from the terminating null and until `dstsz`
* If `src` and `dst` overlap, the behavior is unspecified.
* the following errors are detected at runtime and call the currently installed [constraint handler](../../error/set_constraint_handler_s "c/error/set constraint handler s") function:
* `retval`, `ps`, `src`, or `*src` is a null pointer
* `dstsz` or `len` is greater than `RSIZE_MAX` (unless `dst` is null)
* `dstsz` is not zero (unless `dst` is null)
* `len` is greater than `dstsz` and the conversion does not encounter null or encoding error in the `src` array by the time `dstsz` is reached (unless `dst` is null)
As with all bounds-checked functions, `wcsrtombs_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<wchar.h>`.
### Parameters
| | | |
| --- | --- | --- |
| dst | - | pointer to narrow character array where the multibyte characters will be stored |
| src | - | pointer to pointer to the first element of a null-terminated wide string |
| len | - | number of bytes available in the array pointed to by dst |
| ps | - | pointer to the conversion state object |
| dstsz | - | max number of bytes that will be written (size of the `dst` array) |
| retval | - | pointer to a `[size\_t](../../types/size_t "c/types/size t")` object where the result will be stored |
### Return value
1) On success, returns the number of bytes (including any shift sequences, but excluding the terminating `'\0'`) written to the character array whose first element is pointed to by `dst`. If `dst` is a null pointer, returns the number of bytes that would have been written. On conversion error (if invalid wide character was encountered), returns `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1`, stores `[EILSEQ](../../error/errno_macros "c/error/errno macros")` in `[errno](../../error/errno "c/error/errno")`, and leaves `*ps` in unspecified state.
2) Returns zero on success (in which case the number of bytes excluding terminating zero that were, or would be written to `dst`, is stored in `*retval`), non-zero on error. In case of a runtime constraint violation, stores `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1` in `*retval` (unless `retval` is null) and sets `dst[0]` to `'\0'` (unless `dst` is null or `dstmax` is zero or greater than `RSIZE_MAX`) ### Example
```
#include <stdio.h>
#include <locale.h>
#include <string.h>
#include <wchar.h>
void print_wide(const wchar_t* wstr)
{
mbstate_t state;
memset(&state, 0, sizeof state);
size_t len = 1 + wcsrtombs(NULL, &wstr, 0, &state);
char mbstr[len];
wcsrtombs(mbstr, &wstr, len, &state);
printf("Multibyte string: %s\n", mbstr);
printf("Length, including '\\0': %zu\n", len);
}
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
print_wide(L"z\u00df\u6c34\U0001f34c"); // or L"zß水🍌"
}
```
Output:
```
Multibyte string: zß水🍌
Length, including '\0': 11
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.29.6.4.2 The wcsrtombs function (p: 324-325)
+ K.3.9.3.2.2 The wcsrtombs\_s function (p: 471-472)
* C11 standard (ISO/IEC 9899:2011):
+ 7.29.6.4.2 The wcsrtombs function (p: 446)
+ K.3.9.3.2.2 The wcsrtombs\_s function (p: 649-651)
* C99 standard (ISO/IEC 9899:1999):
+ 7.24.6.4.2 The wcsrtombs function (p: 392)
### See also
| | |
| --- | --- |
| [wcstombswcstombs\_s](wcstombs "c/string/multibyte/wcstombs")
(C11) | converts a wide string to narrow multibyte character string (function) |
| [wcrtombwcrtomb\_s](wcrtomb "c/string/multibyte/wcrtomb")
(C95)(C11) | converts a wide character to its multibyte representation, given state (function) |
| [mbsrtowcsmbsrtowcs\_s](mbsrtowcs "c/string/multibyte/mbsrtowcs")
(C95)(C11) | converts a narrow multibyte character string to wide string, given state (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/wcsrtombs "cpp/string/multibyte/wcsrtombs") for `wcsrtombs` |
c mbrtoc16 mbrtoc16
========
| Defined in header `<uchar.h>` | | |
| --- | --- | --- |
|
```
size_t mbrtoc16( char16_t * restrict pc16, const char * restrict s,
size_t n, mbstate_t * restrict ps );
```
| | (since C11) |
Converts a single code point from its narrow multibyte character representation to its variable-length 16-bit wide character representation (typically, UTF-16).
If `s` is not a null pointer, inspects at most `n` bytes of the multibyte character string, beginning with the byte pointed to by `s` to determine the number of bytes necessary to complete the next multibyte character (including any shift sequences, and taking into account the current multibyte conversion state `*ps`). If the function determines that the next multibyte character in `s` is complete and valid, converts it to the corresponding 16-bit wide character and stores it in `*pc16` (if `pc16` is not null).
If the multibyte character in `*s` corresponds to a multi-char16\_t sequence (e.g. a surrogate pair in UTF-16), then after the first call to this function, `*ps` is updated in such a way that the next call to `mbrtoc16` will write out the additional char16\_t, without considering `*s`.
If `s` is a null pointer, the values of `n` and `pc16` are ignored and the call is equivalent to `mbrtoc16([NULL](http://en.cppreference.com/w/c/types/NULL), "", 1, ps)`.
If the wide character produced is the null character, the conversion state `*ps` represents the initial shift state.
If the macro `__STDC_UTF_16__` is defined, the 16-bit encoding used by this function is UTF-16; otherwise, it is implementation-defined. In any case, the multibyte character encoding used by this function is specified by the currently active C locale.
### Parameters
| | | |
| --- | --- | --- |
| pc16 | - | pointer to the location where the resulting 16-bit wide character will be written |
| s | - | pointer to the multibyte character string used as input |
| n | - | limit on the number of bytes in s that can be examined |
| ps | - | pointer to the conversion state object used when interpreting the multibyte string |
### Return value
The first of the following that applies:
* `0` if the character converted from `s` (and stored in `*pc16` if non-null) was the null character
* the number of bytes `[1...n]` of the multibyte character successfully converted from `s`
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-3` if the next `char16_t` from a multi-`char16_t` character (e.g. a surrogate pair) has now been written to `*pc16`. No bytes are processed from the input in this case.
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-2` if the next `n` bytes constitute an incomplete, but so far valid, multibyte character. Nothing is written to `*pc16`.
* `([size\_t](http://en.cppreference.com/w/c/types/size_t))-1` if encoding error occurs. Nothing is written to `*pc16`, the value `[EILSEQ](../../error/errno_macros "c/error/errno macros")` is stored in `[errno](../../error/errno "c/error/errno")` and the value of `*ps` is unspecified.
### Example
```
#include <stdio.h>
#include <locale.h>
#include <uchar.h>
mbstate_t state;
int main(void)
{
setlocale(LC_ALL, "en_US.utf8");
char in[] = u8"zß水🍌"; // or "z\u00df\u6c34\U0001F34C"
size_t in_sz = sizeof in / sizeof *in;
printf("Processing %zu UTF-8 code units: [ ", in_sz);
for(size_t n = 0; n < in_sz; ++n) printf("%#x ", (unsigned char)in[n]);
puts("]");
char16_t out[in_sz];
char *p_in = in, *end = in + in_sz;
char16_t *p_out = out;
size_t rc;
while((rc = mbrtoc16(p_out, p_in, end - p_in, &state)))
{
if(rc == (size_t)-1) // invalid input
break;
else if(rc == (size_t)-2) // truncated input
break;
else if(rc == (size_t)-3) // UTF-16 high surrogate
p_out += 1;
else {
p_in += rc;
p_out += 1;
};
}
size_t out_sz = p_out - out + 1;
printf("into %zu UTF-16 code units: [ ", out_sz);
for(size_t x = 0; x < out_sz; ++x) printf("%#x ", out[x]);
puts("]");
}
```
Output:
```
Processing 11 UTF-8 code units: [ 0x7a 0xc3 0x9f 0xe6 0xb0 0xb4 0xf0 0x9f 0x8d 0x8c 0 ]
into 6 UTF-16 code units: [ 0x7a 0xdf 0x6c34 0xd83c 0xdf4c 0 ]
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.28.1.1 The mbrtoc16 function (p: 398-399)
### See also
| | |
| --- | --- |
| [c16rtomb](c16rtomb "c/string/multibyte/c16rtomb")
(C11) | converts a 16-bit wide character to narrow multibyte string (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/multibyte/mbrtoc16 "cpp/string/multibyte/mbrtoc16") for `mbrtoc16` |
c C keywords: case C keywords: case
================
### Usage
* [`switch` statement](../language/switch "c/language/switch"): as the declaration of the case labels
c C keywords: _Alignof (since C11)
C keywords: \_Alignof (since C11)
=================================
### Usage
* [`_Alignof` operator](../language/_alignof "c/language/ Alignof")
c C keywords: continue C keywords: continue
====================
### Usage
* [`continue` statement](../language/continue "c/language/continue"): as the declaration of the statement
c C keywords: union C keywords: union
=================
### Usage
* [declaration of a union type](../language/union "c/language/union")
c C keywords: restrict C keywords: restrict
====================
### Usage
* [`restrict` type qualifier](../language/restrict "c/language/restrict")
c C keywords: _Noreturn (since C11)
C keywords: \_Noreturn (since C11)
==================================
### Usage
* [`_Noreturn` function specifier](../language/_noreturn "c/language/ Noreturn")(deprecated in C23)
* [`_Noreturn` attribute-token](../language/attributes/noreturn "c/language/attributes/noreturn")(since C23)(deprecated in C23)
### Notes
Since C23, `_Noreturn` is also [attribute token](../language/attributes/noreturn "c/language/attributes/noreturn"). Its usage is deprecated and `noreturn` should be used instead.
c C keywords: default C keywords: default
===================
### Usage
* [`switch` statement](../language/switch "c/language/switch"): as the declaration of the default case label
| | |
| --- | --- |
| * [type-generic expression](../language/generic "c/language/generic"): as the declaration of the default generic association
| (since C11) |
c C keywords: volatile C keywords: volatile
====================
### Usage
* [`volatile` type qualifier](../language/volatile "c/language/volatile")
c C keywords: _Bool C keywords: \_Bool
==================
### Usage
* [boolean type](../language/arithmetic_types#Boolean_type "c/language/arithmetic types"): as the declaration of the type
c C keywords: typedef C keywords: typedef
===================
### Usage
* [`typedef` declaration](../language/typedef "c/language/typedef")
c C keywords: else C keywords: else
================
### Usage
* [`if` statement](../language/if "c/language/if"): as the declaration of the alternative branch
c C keywords: while C keywords: while
=================
### Usage
* [`while` loop](../language/while "c/language/while"): as the declaration of the loop
* [`do-while` loop](../language/do "c/language/do"): as the declaration of the terminating condition of the loop
c C keywords: short C keywords: short
=================
### Usage
* [`short` type modifier](../language/types "c/language/types")
c C keywords: _Decimal128 C keywords: \_Decimal128
========================
### Usage
* [`_Decimal128` type](../language/types "c/language/types"): as the declaration of the type
c C keywords: signed C keywords: signed
==================
### Usage
* [`signed` type modifier](../language/types "c/language/types")
c C keywords: void C keywords: void
================
### Usage
* [`void` type](../language/types "c/language/types"): as the declaration of the incomplete type
* [`void`](../language/function_declaration "c/language/function declaration"): in a function with no parameter or no return value
c C keywords: auto C keywords: auto
================
### Usage
* [automatic duration storage-class specifier](../language/storage_duration "c/language/storage duration") with no linkage.
c C keywords: int C keywords: int
===============
### Usage
* [`int` type](../language/types "c/language/types"): as the declaration of the type
| programming_docs |
c C keywords: register C keywords: register
====================
### Usage
* [automatic duration storage-class specifier](../language/storage_duration "c/language/storage duration") with no linkage. Hints that the variable will be used heavily.
c C keywords: float C keywords: float
=================
### Usage
* [`float` type](../language/types "c/language/types"): as the declaration of the type
c C keywords: long C keywords: long
================
### Usage
* [`long` type modifier](../language/types "c/language/types")
c C keywords: _Atomic C keywords: \_Atomic
====================
### Usage
* [atomic type specifier and qualifier](../language/atomic "c/language/atomic")
c C keywords: _Generic C keywords: \_Generic
=====================
### Usage
* [Type-generic expression](../language/generic "c/language/generic")
c C keywords: double C keywords: double
==================
### Usage
* [`double` type](../language/types "c/language/types"): as the declaration of the type
* [`long double` type](../language/types "c/language/types"): as the declaration of the type when combined with [`long`](long "c/keyword/long")
c C keywords: extern C keywords: extern
==================
### Usage
* [static duration storage-class specifier](../language/storage_duration "c/language/storage duration") with either internal or more usually external linkage.
c C keywords: enum C keywords: enum
================
### Usage
* [declaration of an enumeration type](../language/enum "c/language/enum")
c C keywords: char C keywords: char
================
### Usage
* *type specifier* for the [character types](../language/arithmetic_types#Character_types "c/language/arithmetic types") (`char`, `signed char`, and `unsigned char`).
c C keywords: _Static_assert C keywords: \_Static\_assert
============================
### Usage
* [static assert declaration](../language/_static_assert "c/language/ Static assert")
c C keywords: _Complex C keywords: \_Complex
=====================
### Usage
* [`_Complex` type](../language/arithmetic_types#Complex_floating_types "c/language/arithmetic types"): as the declaration of the type
c C keywords: _Imaginary C keywords: \_Imaginary
=======================
### Usage
* [imaginary floating type](../language/arithmetic_types#Imaginary_floating_types "c/language/arithmetic types") specifier
c C keywords: fortran C keywords: fortran
===================
### Usage
* conditionally-supported type specifier for Fortran language linkage. May be used with [function declarations](../language/function_declaration "c/language/function declaration") and other [external declarations](../language/extern "c/language/extern") to indicate that the calling convention and name mangling is suitable for linking with translation units written in the Fortran programming language.
c C keywords: inline (since C99)
C keywords: inline (since C99)
==============================
### Usage
* [inline function specifier](../language/inline "c/language/inline")
c C keywords: sizeof C keywords: sizeof
==================
### Usage
* [`sizeof` operator](../language/sizeof "c/language/sizeof")
c C keywords: goto C keywords: goto
================
### Usage
* [`goto` statement](../language/goto "c/language/goto"): as the declaration of the statement
c C keywords: static C keywords: static
==================
### Usage
* [static duration storage-class specifier](../language/storage_duration "c/language/storage duration") with internal linkage at file scope and no linkage at block scope.
| | |
| --- | --- |
| * static [array indices](../language/array "c/language/array") in function parameter declarations.
| (since C99) |
c C keywords: return C keywords: return
==================
### Usage
* [`return` statement](../language/return "c/language/return"): as the declaration of the statement
c C keywords: _Decimal32 C keywords: \_Decimal32
=======================
### Usage
* [`_Decimal32` type](../language/types "c/language/types"): as the declaration of the type
c C keywords: break C keywords: break
=================
### Usage
* [`break` statement](../language/break "c/language/break"): as the declaration of the statement
c C keywords: unsigned C keywords: unsigned
====================
### Usage
* [`unsigned` type modifier](../language/types "c/language/types")
c C keywords: if C keywords: if
==============
### Usage
* [`if` statement](../language/if "c/language/if"): as the declaration of the `if` statement
c C keywords: const C keywords: const
=================
### Usage
* [`const` type qualifier](../language/const "c/language/const")
c C keywords: struct C keywords: struct
==================
### Usage
* [declaration of a compound type](../language/struct "c/language/struct")
c C keywords: _Thread_local (since C11)
C keywords: \_Thread\_local (since C11)
=======================================
### Usage
* [thread storage-class specifier](../language/storage_duration "c/language/storage duration").
c C keywords: switch C keywords: switch
==================
### Usage
* [`switch` statement](../language/switch "c/language/switch"): as the declaration of the statement
c C keywords: _Decimal64 C keywords: \_Decimal64
=======================
### Usage
* [`_Decimal64` type](../language/types "c/language/types"): as the declaration of the type
c C keywords: do C keywords: do
==============
### Usage
* [`do-while` loop](../language/do "c/language/do"): as the declaration of the loop
c C keywords: for C keywords: for
===============
### Usage
* [`for` loop](../language/for "c/language/for"): as the declaration of the loop
c C keywords: _Alignas (since C11)
C keywords: \_Alignas (since C11)
=================================
### Usage
* [`_Alignas`](../language/_alignas "c/language/ Alignas") alignment specifier.
c cnd_destroy cnd\_destroy
============
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
void cnd_destroy( cnd_t* cond );
```
| | (since C11) |
Destroys the condition variable pointed to by `cond`.
If there are threads waiting on `cond`, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| cond | - | pointer to the condition variable to destroy |
### Return value
(none).
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.3.2 The cnd\_destroy function (p: 276)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.3.2 The cnd\_destroy function (p: 378-379)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/condition_variable/%7Econdition_variable "cpp/thread/condition variable/~condition variable") for `~condition_variable` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/condition_variable_any/%7Econdition_variable_any "cpp/thread/condition variable any/~condition variable any") for `~condition_variable_any` |
c thrd_create thrd\_create
============
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int thrd_create( thrd_t *thr, thrd_start_t func, void *arg );
```
| | (since C11) |
Creates a new thread executing the function `func`. The function is invoked as `func(arg)`.
If successful, the object pointed to by `thr` is set to the identifier of the new thread.
The completion of this function *synchronizes-with* the beginning of the thread.
### Parameters
| | | |
| --- | --- | --- |
| thr | - | pointer to memory location to put the identifier of the new thread |
| func | - | function to execute |
| arg | - | argument to pass to the function |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if the creation of the new thread was successful. Otherwise returns `[thrd\_nomem](thrd_errors "c/thread/thrd errors")` if there was insufficient amount of memory or `[thrd\_error](thrd_errors "c/thread/thrd errors")` if another error occurred.
### Notes
The thread identifiers may be reused for new threads once the thread has finished and joined or detached.
The type `[thrd\_start\_t](../thread "c/thread")` is a typedef of `int(*)(void*)`, which differs from the POSIX equivalent `void*(*)(void*)`.
All thread-specific storage values (see `[tss\_create](tss_create "c/thread/tss create")`) are initialized to `[NULL](../types/null "c/types/NULL")`.
Return from the function `func` is equivalent to calling `[thrd\_exit](thrd_exit "c/thread/thrd exit")` with the argument equal to the return value of `func`.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.5.1 The thrd\_create function (p: 279)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.5.1 The thrd\_create function (p: 383)
### See also
| | |
| --- | --- |
| [thrd\_detach](thrd_detach "c/thread/thrd detach")
(C11) | detaches a thread (function) |
| [thrd\_join](thrd_join "c/thread/thrd join")
(C11) | blocks until a thread terminates (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/thread/thread "cpp/thread/thread/thread") for `thread` |
c mtx_plain, mtx_recursive, mtx_timed mtx\_plain, mtx\_recursive, mtx\_timed
======================================
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
enum {
mtx_plain = /* unspecified */,
mtx_recursive = /* unspecified */,
mtx_timed = /* unspecified */
};
```
| | (since C11) |
When passed to `[mtx\_init](mtx_init "c/thread/mtx init")`, identifies the type of a mutex to create.
| Constant | Explanation |
| --- | --- |
| `mtx_plain` | plain mutex |
| `mtx_recursive` | recursive mutex |
| `mtx_timed` | timed mutex |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.1/5 mtx\_plain, mtx\_recursive, mtx\_timed (p: 274-275)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.1/5 mtx\_plain, mtx\_recursive, mtx\_timed (p: 377)
### See also
| | |
| --- | --- |
| [mtx\_init](mtx_init "c/thread/mtx init")
(C11) | creates a mutex (function) |
c mtx_lock mtx\_lock
=========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int mtx_lock( mtx_t* mutex );
```
| | (since C11) |
Blocks the current thread until the mutex pointed to by `mutex` is locked.
The behavior is undefined if the current thread has already locked the mutex and the mutex is not recursive.
Prior calls to `[mtx\_unlock](mtx_unlock "c/thread/mtx unlock")` on the same mutex *synchronize-with* this operation, and all lock/unlock operations on any given mutex form a single total order (similar to the modification order of an atomic).
### Parameters
| | | |
| --- | --- | --- |
| mutex | - | pointer to the mutex to lock |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `[thrd\_error](thrd_errors "c/thread/thrd errors")` otherwise.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.4.3 The mtx\_lock function (p: 278)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.4.3 The mtx\_lock function (p: 381)
### See also
| | |
| --- | --- |
| [mtx\_timedlock](mtx_timedlock "c/thread/mtx timedlock")
(C11) | blocks until locks a mutex or times out (function) |
| [mtx\_trylock](mtx_trylock "c/thread/mtx trylock")
(C11) | locks a mutex or returns without blocking if already locked (function) |
| [mtx\_unlock](mtx_unlock "c/thread/mtx unlock")
(C11) | unlocks a mutex (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/mutex/lock "cpp/thread/mutex/lock") for `mutex::lock` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/timed_mutex/lock "cpp/thread/timed mutex/lock") for `timed_mutex::lock` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/recursive_mutex/lock "cpp/thread/recursive mutex/lock") for `recursive_mutex::lock` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/recursive_timed_mutex/lock "cpp/thread/recursive timed mutex/lock") for `recursive_timed_mutex::lock` |
c mtx_unlock mtx\_unlock
===========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int mtx_unlock( mtx_t *mutex );
```
| | (since C11) |
Unlocks the mutex pointed to by `mutex`.
The behavior is undefined if the mutex is not locked by the calling thread.
This function *synchronizes-with* subsequent `[mtx\_lock](mtx_lock "c/thread/mtx lock")`, `[mtx\_trylock](mtx_trylock "c/thread/mtx trylock")`, or `[mtx\_timedlock](mtx_timedlock "c/thread/mtx timedlock")` on the same mutex. All lock/unlock operations on any given mutex form a single total order (similar to the modification order of an atomic).
### Parameters
| | | |
| --- | --- | --- |
| mutex | - | pointer to the mutex to unlock |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `[thrd\_error](thrd_errors "c/thread/thrd errors")` otherwise.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.4.6 The mtx\_unlock function (p: 279)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.4.6 The mtx\_unlock function (p: 382)
### See also
| | |
| --- | --- |
| [mtx\_lock](mtx_lock "c/thread/mtx lock")
(C11) | blocks until locks a mutex (function) |
| [mtx\_timedlock](mtx_timedlock "c/thread/mtx timedlock")
(C11) | blocks until locks a mutex or times out (function) |
| [mtx\_trylock](mtx_trylock "c/thread/mtx trylock")
(C11) | locks a mutex or returns without blocking if already locked (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/mutex/unlock "cpp/thread/mutex/unlock") for `mutex::unlock` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/timed_mutex/unlock "cpp/thread/timed mutex/unlock") for `timed_mutex::unlock` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/recursive_mutex/unlock "cpp/thread/recursive mutex/unlock") for `recursive_mutex::unlock` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/recursive_timed_mutex/unlock "cpp/thread/recursive timed mutex/unlock") for `recursive_timed_mutex::unlock` |
c thrd_join thrd\_join
==========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int thrd_join( thrd_t thr, int *res );
```
| | (since C11) |
Blocks the current thread until the thread identified by `thr` finishes execution.
If `res` is not a null pointer, the result code of the thread is put to the location pointed to by `res`.
The termination of the thread *synchronizes-with* the completion of this function.
The behavior is undefined if the thread was previously detached or joined by another thread.
### Parameters
| | | |
| --- | --- | --- |
| thr | - | identifier of the thread to join |
| res | - | location to put the result code to |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `[thrd\_error](thrd_errors "c/thread/thrd errors")` otherwise.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.5.6 The thrd\_join function (p: 280-281)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.5.6 The thrd\_join function (p: 384-385)
### See also
| | |
| --- | --- |
| [thrd\_detach](thrd_detach "c/thread/thrd detach")
(C11) | detaches a thread (function) |
| [thrd\_exit](thrd_exit "c/thread/thrd exit")
(C11) | terminates the calling thread (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/thread/join "cpp/thread/thread/join") for `join` |
c tss_create tss\_create
===========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int tss_create( tss_t* tss_key, tss_dtor_t destructor );
```
| | (since C11) |
Creates new thread-specific storage key and stores it in the object pointed to by `tss_key`. Although the same key value may be used by different threads, the values bound to the key by `[tss\_set](tss_set "c/thread/tss set")` are maintained on a per-thread basis and persist for the life of the calling thread.
The value `[NULL](../types/null "c/types/NULL")` is associated with the newly created key in all existing threads, and upon thread creation, the values associated with all TSS keys is initialized to `[NULL](../types/null "c/types/NULL")`.
If `destructor` is not a null pointer, then also associates the destructor which is called when the storage is released by `[thrd\_exit](thrd_exit "c/thread/thrd exit")` (but not by `[tss\_delete](tss_delete "c/thread/tss delete")` and not at program termination by `[exit](../program/exit "c/program/exit")`).
A call to `tss_create` from within a thread-specific storage destructor results in undefined behavior.
### Parameters
| | | |
| --- | --- | --- |
| tss\_key | - | pointer to memory location to store the new thread-specific storage key |
| destructor | - | pointer to a function to call at thread exit |
### Notes
The POSIX equivalent of this function is [`pthread_key_create`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_key_create.html).
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `[thrd\_error](thrd_errors "c/thread/thrd errors")` otherwise.
### Example
```
int thread_func(void *arg) {
tss_t key;
if (thrd_success == tss_create(&key, free)) {
tss_set(key, malloc(4)); // stores a pointer on TSS
// ...
}
} // calls free() for the pointer stored on TSS
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.6.1 The tss\_create function (p: 281-282)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.6.1 The tss\_create function (p: 386)
c cnd_timedwait cnd\_timedwait
==============
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int cnd_timedwait( cnd_t* restrict cond, mtx_t* restrict mutex,
const struct timespec* restrict time_point );
```
| | (since C11) |
Atomically unlocks the mutex pointed to by `mutex` and blocks on the condition variable pointed to by `cond` until the thread is signalled by `[cnd\_signal](cnd_signal "c/thread/cnd signal")` or `[cnd\_broadcast](cnd_broadcast "c/thread/cnd broadcast")`, or until the `TIME_UTC` based time point pointed to by `time_point` has been reached, or until a spurious wake-up occurs. The mutex is locked again before the function returns.
The behavior is undefined if the mutex is not already locked by the calling thread.
### Parameters
| | | |
| --- | --- | --- |
| cond | - | pointer to the condition variable to block on |
| mutex | - | pointer to the mutex to unlock for the duration of the block |
| time\_point | - | pointer to a object specifying timeout time to wait until |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `thrd_timedout` if the timeout time has been reached before the mutex is locked, or `[thrd\_error](thrd_errors "c/thread/thrd errors")` if an error occurred.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.3.5 The cnd\_timedwait function (p: 276-277)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.3.5 The cnd\_timedwait function (p: 379-380)
### See also
| | |
| --- | --- |
| [cnd\_wait](cnd_wait "c/thread/cnd wait")
(C11) | blocks on a condition variable (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/condition_variable/wait_until "cpp/thread/condition variable/wait until") for `condition_variable::wait_until` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/condition_variable_any/wait_until "cpp/thread/condition variable any/wait until") for `condition_variable_any::wait_until` |
c cnd_signal cnd\_signal
===========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int cnd_signal( cnd_t *cond );
```
| | (since C11) |
Unblocks one thread that currently waits on condition variable pointed to by `cond`. If no threads are blocked, does nothing and returns `thrd_success`.
### Parameters
| | | |
| --- | --- | --- |
| cond | - | pointer to a condition variable |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `[thrd\_error](thrd_errors "c/thread/thrd errors")` otherwise.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.3.4 The cnd\_signal function (p: 276)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.3.4 The cnd\_signal function (p: 379)
### See also
| | |
| --- | --- |
| [cnd\_broadcast](cnd_broadcast "c/thread/cnd broadcast")
(C11) | unblocks all threads blocked on a condition variable (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/condition_variable/notify_one "cpp/thread/condition variable/notify one") for `condition_variable::notify_one` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/condition_variable_any/notify_one "cpp/thread/condition variable any/notify one") for `condition_variable_any::notify_one` |
| programming_docs |
c cnd_init cnd\_init
=========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int cnd_init( cnd_t* cond );
```
| | (since C11) |
Initializes new condition variable. The object pointed to by `cond` will be set to value that identifies the condition variable.
### Parameters
| | | |
| --- | --- | --- |
| cond | - | pointer to a variable to store identifier of the condition variable to |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if the condition variable was successfully created. Otherwise returns `[thrd\_nomem](thrd_errors "c/thread/thrd errors")` if there was insufficient amount of memory or `thrd_error` if another error occurred.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.3.3 The cnd\_init function (p: 276)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.3.3 The cnd\_init function (p: 379)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/condition_variable/condition_variable "cpp/thread/condition variable/condition variable") for `condition_variable` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/condition_variable_any/condition_variable_any "cpp/thread/condition variable any/condition variable any") for `condition_variable_any` |
c tss_get tss\_get
========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
void *tss_get( tss_t tss_key );
```
| | (since C11) |
Returns the value held in thread-specific storage for the current thread identified by `tss_key`. Different threads may get different values identified by the same key.
On thread startup (see `[thrd\_create](thrd_create "c/thread/thrd create")`), the values associated with all TSS keys are NULL. Different value may be placed in the thread-specific storage with `[tss\_set](tss_set "c/thread/tss set")`.
### Parameters
| | | |
| --- | --- | --- |
| tss\_key | - | thread-specific storage key, obtained from `[tss\_create](tss_create "c/thread/tss create")` and not deleted by `[tss\_delete](tss_delete "c/thread/tss delete")` |
### Return value
The value on success, `[NULL](../types/null "c/types/NULL")` on failure.
### Notes
The POSIX equivalent for this function is [`pthread_getspecific`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_getspecific.html).
### Example
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.6.3 The tss\_get function (p: 282)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.6.3 The tss\_get function (p: 386)
### See also
| | |
| --- | --- |
| [tss\_set](tss_set "c/thread/tss set")
(C11) | write to thread-specific storage (function) |
c mtx_destroy mtx\_destroy
============
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
void mtx_destroy( mtx_t *mutex );
```
| | (since C11) |
Destroys the mutex pointed to by `mutex`.
If there are threads waiting on `mutex`, the behavior is undefined.
### Parameters
| | | |
| --- | --- | --- |
| mutex | - | pointer to the mutex to destroy |
### Return value
(none).
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.4.1 The mtx\_destroy function (p: 277)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.4.1 The mtx\_destroy function (p: 380)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/mutex/%7Emutex "cpp/thread/mutex/~mutex") for `~mutex` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/timed_mutex/%7Etimed_mutex "cpp/thread/timed mutex/~timed mutex") for `~timed_mutex` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/recursive_mutex/%7Erecursive_mutex "cpp/thread/recursive mutex/~recursive mutex") for `~recursive_mutex` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/recursive_timed_mutex/%7Erecursive_timed_mutex "cpp/thread/recursive timed mutex/~recursive timed mutex") for `~recursive_timed_mutex` |
c tss_set tss\_set
========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int tss_set( tss_t tss_id, void *val );
```
| | (since C11) |
Sets the value of the thread-specific storage identified by `tss_id` for the current thread to `val`. Different threads may set different values to the same key.
The destructor, if available, is not invoked.
### Parameters
| | | |
| --- | --- | --- |
| tss\_id | - | thread-specific storage key, obtained from `[tss\_create](tss_create "c/thread/tss create")` and not deleted by `[tss\_delete](tss_delete "c/thread/tss delete")` |
| val | - | value to set thread-specific storage to |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `[thrd\_error](thrd_errors "c/thread/thrd errors")` otherwise.
### Notes
The POSIX equivalent of this function is [`pthread_setspecific`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_setspecific.html).
Typically TSS is used to store pointers to blocks of dynamically allocated memory that have been reserved for use by the calling thread.
`tss_set` may be called in the TSS destructor. If the destructor exits with non-NULL value in the TSS storage, it will be retried by `[thrd\_exit](thrd_exit "c/thread/thrd exit")` up to `[TSS\_DTOR\_ITERATIONS](tss_dtor_iterations "c/thread/TSS DTOR ITERATIONS")` times, after which the storage will be lost.
### Example
```
int thread_func(void *arg) {
tss_t key;
if (thrd_success == tss_create(&key, free)) {
tss_set(key, malloc(4)); // stores a pointer on TSS
// ...
}
} // calls free() for the pointer stored on TSS
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.6.4 The tss\_set function (p: 282-283)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.6.4 The tss\_set function (p: 387)
### See also
| | |
| --- | --- |
| [tss\_get](tss_get "c/thread/tss get")
(C11) | reads from thread-specific storage (function) |
c thrd_exit thrd\_exit
==========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
_Noreturn void thrd_exit( int res );
```
| | (since C11) |
First, for every thread-specific storage key which was created with a non-null destructor and for which the associated value is non-null (see `[tss\_create](tss_create "c/thread/tss create")`), `thrd_exit` sets the value associated with the key to `[NULL](http://en.cppreference.com/w/c/types/NULL)` and then invokes the destructor with the previous value of the key. The order in which the destructors are invoked is unspecified.
If, after this, there remain keys with both non-null destructors and values (e.g. if a destructor executed `[tss\_set](tss_set "c/thread/tss set")`), the process is repeated up to `[TSS\_DTOR\_ITERATIONS](tss_dtor_iterations "c/thread/TSS DTOR ITERATIONS")` times.
FInally, the `thrd_exit` function terminates execution of the calling thread and sets its result code to `res`.
If the last thread in the program is terminated with `thrd_exit`, the entire program terminates as if by calling `[exit](../program/exit "c/program/exit")` with `[EXIT\_SUCCESS](../program/exit_status "c/program/EXIT status")` as the argument (so the functions registered by `[atexit](../program/atexit "c/program/atexit")` are executed in the context of that last thread).
### Parameters
| | | |
| --- | --- | --- |
| res | - | the result value to return |
### Return value
(none).
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.5.5 The thrd\_exit function (p: 280)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.5.5 The thrd\_exit function (p: 384)
### See also
| | |
| --- | --- |
| [thrd\_join](thrd_join "c/thread/thrd join")
(C11) | blocks until a thread terminates (function) |
| [thrd\_detach](thrd_detach "c/thread/thrd detach")
(C11) | detaches a thread (function) |
c cnd_wait cnd\_wait
=========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int cnd_wait( cnd_t* cond, mtx_t* mutex );
```
| | (since C11) |
Atomically unlocks the mutex pointed to by `mutex` and blocks on the condition variable pointed to by `cond` until the thread is signalled by `[cnd\_signal](cnd_signal "c/thread/cnd signal")` or `[cnd\_broadcast](cnd_broadcast "c/thread/cnd broadcast")`, or until a spurious wake-up occurs. The mutex is locked again before the function returns.
The behavior is undefined if the mutex is not already locked by the calling thread.
### Parameters
| | | |
| --- | --- | --- |
| cond | - | pointer to the condition variable to block on |
| mutex | - | pointer to the mutex to unlock for the duration of the block |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `[thrd\_error](thrd_errors "c/thread/thrd errors")` otherwise.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.3.6 The cnd\_wait function (p: 277)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.3.6 The cnd\_wait function (p: 380)
### See also
| | |
| --- | --- |
| [cnd\_timedwait](cnd_timedwait "c/thread/cnd timedwait")
(C11) | blocks on a condition variable, with a timeout (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/condition_variable/wait "cpp/thread/condition variable/wait") for `condition_variable::wait` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/condition_variable_any/wait "cpp/thread/condition variable any/wait") for `condition_variable_any::wait` |
c mtx_trylock mtx\_trylock
============
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int mtx_trylock( mtx_t *mutex );
```
| | (since C11) |
Tries to lock the mutex pointed to by `mutex` without blocking. Returns immediately if the mutex is already locked.
Prior calls to `[mtx\_unlock](mtx_unlock "c/thread/mtx unlock")` on the same mutex *synchronize-with* this operation (if this operation succeeds), and all lock/unlock operations on any given mutex form a single total order (similar to the modification order of an atomic).
### Parameters
| | | |
| --- | --- | --- |
| mutex | - | pointer to the mutex to lock |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `[thrd\_busy](thrd_errors "c/thread/thrd errors")` if the mutex has already been locked or due to a spurious failure to acquire an available mutex, `[thrd\_error](thrd_errors "c/thread/thrd errors")` if an error occurs.
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [DR 470](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_470) | C11 | `mtx_trylock` was not allowed to fail spuriously | allowed |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.4.5 The mtx\_trylock function (p: 278-279)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.4.5 The mtx\_trylock function (p: 382)
### See also
| | |
| --- | --- |
| [mtx\_lock](mtx_lock "c/thread/mtx lock")
(C11) | blocks until locks a mutex (function) |
| [mtx\_timedlock](mtx_timedlock "c/thread/mtx timedlock")
(C11) | blocks until locks a mutex or times out (function) |
| [mtx\_unlock](mtx_unlock "c/thread/mtx unlock")
(C11) | unlocks a mutex (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/mutex/try_lock "cpp/thread/mutex/try lock") for `mutex::try_lock` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/timed_mutex/try_lock "cpp/thread/timed mutex/try lock") for `timed_mutex::try_lock` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/recursive_mutex/try_lock "cpp/thread/recursive mutex/try lock") for `recursive_mutex::try_lock` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/recursive_timed_mutex/try_lock "cpp/thread/recursive timed mutex/try lock") for `recursive_timed_mutex::try_lock` |
c thrd_sleep thrd\_sleep
===========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int thrd_sleep( const struct timespec* duration,
struct timespec* remaining );
```
| | (since C11) |
Blocks the execution of the current thread for *at least* until the `TIME_UTC` based duration pointed to by `duration` has elapsed.
The sleep may resume earlier if a `[signal](../program/signal "c/program/signal")` that is not ignored is received. In such case, if `remaining` is not `[NULL](../types/null "c/types/NULL")`, the remaining time duration is stored into the object pointed to by `remaining`.
### Parameters
| | | |
| --- | --- | --- |
| duration | - | pointer to the duration to sleep for |
| remaining | - | pointer to the object to put the remaining time on interruption. May be `[NULL](../types/null "c/types/NULL")`, in which case it is ignored |
### Return value
`0` on successful sleep, `-1` if a signal occurred, other negative value if an error occurred.
### Notes
`duration` and `remaining` may point at the same object, which simplifies re-running the function after a signal.
The actual sleep time may be longer than requested because it is rounded up to the timer granularity and because of scheduling and context switching overhead.
The POSIX equivalent of this function is [`nanosleep`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html).
### Example
```
#include <threads.h>
#include <time.h>
#include <stdio.h>
int main(void)
{
printf("Time: %s", ctime(&(time_t){time(NULL)}));
thrd_sleep(&(struct timespec){.tv_sec=1}, NULL); // sleep 1 sec
printf("Time: %s", ctime(&(time_t){time(NULL)}));
}
```
Output:
```
Time: Mon Feb 2 16:18:41 2015
Time: Mon Feb 2 16:18:42 2015
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.5.7 The thrd\_sleep function (p: 281)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.5.7 The thrd\_sleep function (p: 385)
### See also
| | |
| --- | --- |
| [thrd\_yield](thrd_yield "c/thread/thrd yield")
(C11) | yields the current time slice (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/sleep_for "cpp/thread/sleep for") for `sleep_for` |
c mtx_init mtx\_init
=========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int mtx_init( mtx_t* mutex, int type );
```
| | (since C11) |
Creates a new mutex object with `type`. The object pointed to by `mutex` is set to an identifier of the newly created mutex.
`type` must have one of the following values:
* `[mtx\_plain](mtx_types "c/thread/mtx types")` - a simple, non-recursive mutex is created.
* `[mtx\_timed](mtx_types "c/thread/mtx types")` - a non-recursive mutex, that supports timeout, is created.
* `[mtx\_plain](http://en.cppreference.com/w/c/thread/mtx_types) | [mtx\_recursive](http://en.cppreference.com/w/c/thread/mtx_types)` - a recursive mutex is created.
* `[mtx\_timed](http://en.cppreference.com/w/c/thread/mtx_types) | [mtx\_recursive](http://en.cppreference.com/w/c/thread/mtx_types)` - a recursive mutex, that supports timeout, is created.
### Parameters
| | | |
| --- | --- | --- |
| mutex | - | pointer to the mutex to initialize |
| type | - | the type of the mutex |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `[thrd\_error](thrd_errors "c/thread/thrd errors")` otherwise.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.4.2 The mtx\_init function (p: 277-278)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.4.2 The mtx\_init function (p: 381)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/mutex/mutex "cpp/thread/mutex/mutex") for `mutex` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/timed_mutex/timed_mutex "cpp/thread/timed mutex/timed mutex") for `timed_mutex` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/recursive_mutex/recursive_mutex "cpp/thread/recursive mutex/recursive mutex") for `recursive_mutex` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/recursive_timed_mutex/recursive_timed_mutex "cpp/thread/recursive timed mutex/recursive timed mutex") for `recursive_timed_mutex` |
c thrd_success, thrd_timedout, thrd_busy, thrd_nomem, thrd_error thrd\_success, thrd\_timedout, thrd\_busy, thrd\_nomem, thrd\_error
===================================================================
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
enum {
thrd_success = /* unspecified */,
thrd_nomem = /* unspecified */,
thrd_timedout = /* unspecified */,
thrd_busy = /* unspecified */,
thrd_error = /* unspecified */
};
```
| | (since C11) |
Identifiers for thread states and errors.
| Constant | Explanation |
| --- | --- |
| `thrd_success` | indicates successful return value |
| `thrd_nomem` | indicates unsuccessful return value due to out of memory condition |
| `thrd_timedout` | indicates timed out return value |
| `thrd_busy` | indicates unsuccessful return value due to resource temporary unavailable |
| `thrd_error` | indicates unsuccessful return value |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.1/5 thrd\_success, thrd\_timedout, ... (p: 275)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.1/5 thrd\_success, thrd\_timedout, ... (p: 377)
c cnd_broadcast cnd\_broadcast
==============
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int cnd_broadcast( cnd_t *cond );
```
| | (since C11) |
Unblocks all thread that currently wait on condition variable pointed to by `cond`. If no threads are blocked, does nothing and returns `thrd_success`.
### Parameters
| | | |
| --- | --- | --- |
| cond | - | pointer to a condition variable |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `[thrd\_error](thrd_errors "c/thread/thrd errors")` otherwise.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.3.1 The cnd\_broadcast function (p: 275-276)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.3.1 The cnd\_broadcast function (p: 378)
### See also
| | |
| --- | --- |
| [cnd\_signal](cnd_signal "c/thread/cnd signal")
(C11) | unblocks one thread blocked on a condition variable (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/condition_variable/notify_all "cpp/thread/condition variable/notify all") for `condition_variable::notify_all` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/condition_variable_any/notify_all "cpp/thread/condition variable any/notify all") for `condition_variable_any::notify_all` |
c thread_local thread\_local
=============
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
#define thread_local _Thread_local
```
| | (since C11) |
Convenience macro which can be used to specify that an object has [thread-local storage duration](../language/storage_duration "c/language/storage duration").
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.1/3 thread\_local (p: 274)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.1/3 thread\_local (p: 376)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/keyword/thread_local "cpp/keyword/thread local") for `thread_local` |
c mtx_timedlock mtx\_timedlock
==============
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int mtx_timedlock( mtx_t *restrict mutex,
const struct timespec *restrict time_point );
```
| | (since C11) |
Blocks the current thread until the mutex pointed to by `mutex` is locked or until the `TIME_UTC` based absolute calendar time point pointed to by `time_point` has been reached.
Since this function takes an absolute time, if a duration is required, the calendar time point must be calculated manually.
The behavior is undefined if the current thread has already locked the mutex and the mutex is not recursive.
The behavior is undefined if the mutex does not support timeout.
Prior calls to `[mtx\_unlock](mtx_unlock "c/thread/mtx unlock")` on the same mutex *synchronize-with* this operation (if this operation succeeds), and all lock/unlock operations on any given mutex form a single total order (similar to the modification order of an atomic).
### Parameters
| | | |
| --- | --- | --- |
| mutex | - | pointer to the mutex to lock |
| time\_point | - | pointer to the absolute calendar time until which to wait for the timeout |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `thrd_timedout` if the timeout time has been reached before the mutex is locked, `[thrd\_error](thrd_errors "c/thread/thrd errors")` if an error occurs.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.4.4 The mtx\_timedlock function (p: 278)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.4.4 The mtx\_timedlock function (p: 381-382)
### See also
| | |
| --- | --- |
| [timespec](../chrono/timespec "c/chrono/timespec")
(C11) | time in seconds and nanoseconds (struct) |
| [mtx\_lock](mtx_lock "c/thread/mtx lock")
(C11) | blocks until locks a mutex (function) |
| [mtx\_trylock](mtx_trylock "c/thread/mtx trylock")
(C11) | locks a mutex or returns without blocking if already locked (function) |
| [mtx\_unlock](mtx_unlock "c/thread/mtx unlock")
(C11) | unlocks a mutex (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/timed_mutex/try_lock_until "cpp/thread/timed mutex/try lock until") for `timed_mutex::try_lock_until` |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/recursive_timed_mutex/try_lock_until "cpp/thread/recursive timed mutex/try lock until") for `recursive_timed_mutex::try_lock_until` |
### External links
* [GNU GCC Libc Manual: ISO-C-Mutexes](https://www.gnu.org/software/libc/manual/html_node/ISO-C-Mutexes.html)
| programming_docs |
c TSS_DTOR_ITERATIONS TSS\_DTOR\_ITERATIONS
=====================
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
#define TSS_DTOR_ITERATIONS /* unspecified */
```
| | (since C11) |
Expands to a positive integral [constant expression](../language/constant_expression "c/language/constant expression") defining the maximum number of times a destructor for thread-local storage pointer will be called by `[thrd\_exit](thrd_exit "c/thread/thrd exit")`.
This constant is equivalent to the POSIX `PTHREAD_DESTRUCTOR_ITERATIONS`.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.1/3 TSS\_DTOR\_ITERATIONS (p: 274)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.1/3 TSS\_DTOR\_ITERATIONS (p: 376)
c thrd_yield thrd\_yield
===========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
void thrd_yield(void);
```
| | (since C11) |
Provides a hint to the implementation to reschedule the execution of threads, allowing other threads to run.
### Parameters
(none).
### Return value
(none).
### Notes
The exact behavior of this function depends on the implementation, in particular on the mechanics of the OS scheduler in use and the state of the system. For example, a first-in-first-out realtime scheduler (`SCHED_FIFO` in Linux) would suspend the current thread and put it on the back of the queue of the same-priority threads that are ready to run (and if there are no other threads at the same priority, `yield` has no effect).
The POSIX equivalent of this function is [`sched_yield`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sched_yield.html).
### Example
```
#include <stdio.h>
#include <time.h>
#include <threads.h>
// utility function: difference between timespecs in microseconds
double usdiff(struct timespec s, struct timespec e)
{
double sdiff = difftime(e.tv_sec, s.tv_sec);
long nsdiff = e.tv_nsec - s.tv_nsec;
if(nsdiff < 0) return 1000000*(sdiff-1) + (1000000000L+nsdiff)/1000.0;
else return 1000000*(sdiff) + nsdiff/1000.0;
}
// busy wait while yielding
void sleep_100us()
{
struct timespec start, end;
timespec_get(&start, TIME_UTC);
do {
thrd_yield();
timespec_get(&end, TIME_UTC);
} while(usdiff(start, end) < 100.0);
}
int main()
{
struct timespec start, end;
timespec_get(&start, TIME_UTC);
sleep_100us();
timespec_get(&end, TIME_UTC);
printf("Waited for %.3f us\n", usdiff(start, end));
}
```
Possible output:
```
Waited for 100.344 us
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.5.8 The thrd\_yield function (p: 281)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.5.8 The thrd\_yield function (p: 385)
### See also
| | |
| --- | --- |
| [thrd\_sleep](thrd_sleep "c/thread/thrd sleep")
(C11) | suspends execution of the calling thread for the given period of time (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/yield "cpp/thread/yield") for `yield` |
c tss_delete tss\_delete
===========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
void tss_delete( tss_t tss_id );
```
| | (since C11) |
Destroys the thread-specific storage identified by `tss_id`.
The destructor, if one was registered by `[tss\_create](tss_create "c/thread/tss create")`, is not called (they are only called at thread exit, either by `[thrd\_exit](thrd_exit "c/thread/thrd exit")` or by returning from the thread function), it is the responsibility of the programmer to ensure that every thread that is aware of `tss_id` performed all necessary cleanup, before the call to `tss_delete` is made.
If `tss_delete` is called while another thread is executing destructors for `tss_id`, it's unspecified whether this changes the number of invocations to the associated destructor.
If `tss_delete` is called while the calling thread is executing destructors, then the destructor associated with `tss_id` will not be executed again on this thread.
### Parameters
| | | |
| --- | --- | --- |
| tss\_id | - | thread-specific storage key previously returned by `[tss\_create](tss_create "c/thread/tss create")` and not yet deleted by `tss_delete` |
### Return value
(none).
### Notes
The POSIX equivalent of this function is [`pthread_key_delete`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_key_delete.html).
The reason `tss_delete` never calls destructors is that the destructors (called at thread exit) are normally intended to be executed by the same thread that originally set the value (via `[tss\_set](tss_set "c/thread/tss set")`) that the destructor will be dealing with, and may even rely on the values of that or other thread-specific data as seen by that thread. The thread executing `tss_delete` has no access to other threads' TSS. Even if it were possible to call the destructor for each thread's own value associated with `tss_id`, `tss_delete` would have to synchronize with every thread if only to examine whether the value of this TSS in that thread is null (destructors are only called against non-null values).
### Example
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.6.2 The tss\_delete function (p: 282)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.6.2 The tss\_delete function (p: 386)
c thrd_equal thrd\_equal
===========
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int thrd_equal( thrd_t lhs, thrd_t rhs );
```
| | (since C11) |
Checks whether `lhs` and `rhs` refer to the same thread.
### Parameters
| | | |
| --- | --- | --- |
| lhs, rhs | - | threads to compare |
### Return value
Non-zero value if `lhs` and `rhs` refer to the same value, `0` otherwise.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.5.4 The thrd\_equal function (p: 280)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.5.4 The thrd\_equal function (p: 384)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/thread/id/operator_cmp "cpp/thread/thread/id/operator cmp") for `operator_cmp` |
c call_once, once_flag, ONCE_FLAG_INIT call\_once, once\_flag, ONCE\_FLAG\_INIT
========================================
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
void call_once( once_flag* flag, void (*func)(void) );
```
| (1) | (since C11) |
|
```
typedef /* unspecified */ once_flag
```
| (2) | (since C11) |
|
```
#define ONCE_FLAG_INIT /* unspecified */
```
| (3) | (since C11) |
1) Calls function `func` exactly once, even if invoked from several threads. The completion of the function `func` synchronizes with all previous or subsequent calls to `call_once` with the same `flag` variable.
2) Complete object type capable of holding a flag used by `call_once`.
3) Expands to a value that can be used to initialize an object of type `once_flag`. ### Parameters
| | | |
| --- | --- | --- |
| flag | - | pointer to an object of type `call_once` that is used to ensure `func` is called only once |
| func | - | the function to execute only once |
### Return value
(none).
### Notes
The POSIX equivalent of this function is [`pthread_once`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_once.html).
### Example
```
#include <stdio.h>
#include <threads.h>
void do_once(void) {
puts("called once");
}
static once_flag flag = ONCE_FLAG_INIT;
int func(void* data)
{
call_once(&flag, do_once);
}
int main(void)
{
thrd_t t1, t2, t3, t4;
thrd_create(&t1, func, NULL);
thrd_create(&t2, func, NULL);
thrd_create(&t3, func, NULL);
thrd_create(&t4, func, NULL);
thrd_join(t1, NULL);
thrd_join(t2, NULL);
thrd_join(t3, NULL);
thrd_join(t4, NULL);
}
```
Output:
```
called once
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.2.1 The call\_once function (p: 275)
+ 7.26.1/3 ONCE\_FLAG\_INIT (p: 274)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.2.1 The call\_once function (p: 378)
+ 7.26.1/3 ONCE\_FLAG\_INIT (p: 376)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/call_once "cpp/thread/call once") for `call_once` |
c thrd_current thrd\_current
=============
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
thrd_t thrd_current( void );
```
| | (since C11) |
Returns the identifier of the calling thread.
### Parameters
(none).
### Return value
The identifier of the calling thread.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.5.2 The thrd\_current function (p: 279)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.5.2 The thrd\_current function (p: 383)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/get_id "cpp/thread/get id") for `get_id` |
c thrd_detach thrd\_detach
============
| Defined in header `<threads.h>` | | |
| --- | --- | --- |
|
```
int thrd_detach( thrd_t thr );
```
| | (since C11) |
Detaches the thread identified by `thr` from the current environment. The resources held by the thread will be freed automatically once the thread exits.
### Parameters
| | | |
| --- | --- | --- |
| thr | - | identifier of the thread to detach |
### Return value
`[thrd\_success](thrd_errors "c/thread/thrd errors")` if successful, `[thrd\_error](thrd_errors "c/thread/thrd errors")` otherwise.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.26.5.3 The thrd\_detach function (p: 280)
* C11 standard (ISO/IEC 9899:2011):
+ 7.26.5.3 The thrd\_detach function (p: 383-384)
### See also
| | |
| --- | --- |
| [thrd\_join](thrd_join "c/thread/thrd join")
(C11) | blocks until a thread terminates (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread/thread/detach "cpp/thread/thread/detach") for `detach` |
c set_constraint_handler_s, constraint_handler_t set\_constraint\_handler\_s, constraint\_handler\_t
===================================================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
constraint_handler_t set_constraint_handler_s( constraint_handler_t handler );
```
| | (since C11) |
Configures the handler to be called by all [bounds-checked functions](../error#Bounds_checking "c/error") on a runtime constraint violation or restores the default handler (if `handler` is a null pointer).
The handler must be a pointer to function of type `constraint_handler_t`, which is defined as.
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
typedef void (*constraint_handler_t)( const char *restrict msg,
void *restrict ptr,
errno_t error);
```
| | (since C11) |
On a runtime constraint violation, it is called with the following arguments:
1) pointer to character string that describes the error
2) pointer to an implementation-defined object or a null pointer. Examples of implementation-defined objects are objects that give the name of the function that detected the violation and the line number when the violation was detected
3) the error about to be returned by the calling function, if it happens to be one of the functions that return `errno_t`
If `set_constraint_handler_s` is never called, the default handler is implementation-defined: it may be `abort_handler_s`, `ignore_handler_s`, or some other implementation-defined handler. As with all bounds-checked functions, `set_constraint_handler_s` and `constraint_handler_t` are only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<stdlib.h>`.
### Parameters
| | | |
| --- | --- | --- |
| handler | - | pointer to function of type `constraint_handler_t` or a null pointer |
### Return value
A pointer to the previously-installed runtime constraints handler. (note: this pointer is never a null pointer because calling `set_constraint_handler_s([NULL](http://en.cppreference.com/w/c/types/NULL))` sets up the system default handler).
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
#ifdef __STDC_LIB_EXT1__
char dst[2];
set_constraint_handler_s(ignore_handler_s);
int r = strcpy_s(dst, sizeof dst, "Too long!");
printf("dst = \"%s\", r = %d\n", dst, r);
set_constraint_handler_s(abort_handler_s);
r = strcpy_s(dst, sizeof dst, "Too long!");
printf("dst = \"%s\", r = %d\n", dst, r);
#endif
}
```
Possible output:
```
dst = "", r = 22
abort_handler_s was called in response to a runtime-constraint violation.
The runtime-constraint violation was caused by the following expression in strcpy_s:
(s1max <= (s2_len=strnlen_s(s2, s1max)) ) (in string_s.c:62)
Note to end users: This program was terminated as a result
of a bug present in the software. Please reach out to your
software's vendor to get more help.
Aborted
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ K.3.6/2 constraint\_handler\_t (p: 604)
+ K.3.6.1.1 The set\_constraint\_handler\_s function (p: 604-605)
### See also
| | |
| --- | --- |
| [abort\_handler\_s](abort_handler_s "c/error/abort handler s")
(C11) | abort callback for the bounds-checked functions (function) |
| [ignore\_handler\_s](ignore_handler_s "c/error/ignore handler s")
(C11) | ignore callback for the bounds-checked functions (function) |
c Error numbers Error numbers
=============
Each of the macros defined in `<errno.h>` expands to an integer constant expression with type `int` and with a unique positive value. The following constants are defined by ISO C. The implementation may define more, as long as they begin with `'E'` followed by digits or uppercase letters.
| Defined in header `<errno.h>` |
| --- |
| EDOM | Mathematics argument out of domain of function (macro constant) |
| EILSEQ
(C95) | Illegal byte sequence (macro constant) |
| ERANGE | Result too large (macro constant) |
### Notes
Many additional errno constants are [defined by POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/errno.h.html) and by the [C++ standard library](https://en.cppreference.com/w/cpp/error/errno_macros "cpp/error/errno macros"), and individual implementations may define even more, e.g. `errno(3)` on Linux or `intro(2)` on BSD and OS X.
### Example
```
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <string.h>
int main(void)
{
errno = 0;
printf("log(-1.0) = %f\n", log(-1.0));
printf("%s\n\n",strerror(errno));
errno = 0;
printf("log(0.0) = %f\n", log(0.0));
printf("%s\n",strerror(errno));
}
```
Possible output:
```
log(-1.0) = nan
Numerical argument out of domain
log(0.0) = -inf
Numerical result out of range
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.5/2 Errors <errno.h> (p: 205)
* C99 standard (ISO/IEC 9899:1999):
+ 7.5/2 Errors <errno.h> (p: 186)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.1.3 Errors <errno.h>
### See also
| | |
| --- | --- |
| [errno](errno "c/error/errno") | macro which expands to POSIX-compatible thread-local error number variable(macro variable) |
| [perror](../io/perror "c/io/perror") | displays a character string corresponding of the current error to `[stderr](../io/std_streams "c/io/std streams")` (function) |
| [strerrorstrerror\_sstrerrorlen\_s](../string/byte/strerror "c/string/byte/strerror")
(C11)(C11) | returns a text version of a given error code (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/error/errno_macros "cpp/error/errno macros") for Error numbers |
c errno errno
=====
| Defined in header `<errno.h>` | | |
| --- | --- | --- |
|
```
#define errno /*implementation-defined*/
```
| | |
`errno` is a preprocessor macro (but see note below) that expands to a thread-local (since C11) modifiable lvalue of type `int`. Several standard library functions indicate errors by writing positive integers to `errno`. Typically, the value of `errno` is set to one of the error codes listed in `<errno.h>` as macro constants beginning with the letter `E` followed by uppercase letters or digits.
The value of `errno` is `0` at program startup, and although library functions are allowed to write positive integers to `errno` whether or not an error occurred, library functions never store `0` in `errno`.
Library functions `[perror](../io/perror "c/io/perror")` and `[strerror](../string/byte/strerror "c/string/byte/strerror")` can be used to obtain textual descriptions of the error conditions that correspond to the current `errno` value.
Note: Until C11, the C standards had contradictory requirements, in that they said that `errno` is a macro but *also* that "it is unspecified whether `errno` is a macro or an identifier declared with external linkage". C11 fixes this, requiring that it be defined as a macro (see also WG14 [N1338](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1338.htm)).
### Example
```
#include <stdio.h>
#include <math.h>
#include <errno.h>
void show_errno(void)
{
const char *err_info = "unknown error";
switch (errno) {
case EDOM:
err_info = "domain error";
break;
case EILSEQ:
err_info = "illegal sequence";
break;
case ERANGE:
err_info = "pole or range error";
break;
case 0:
err_info = "no error";
}
fputs(err_info, stdout);
puts(" occurred");
}
int main(void)
{
fputs("MATH_ERRNO is ", stdout);
puts(math_errhandling & MATH_ERRNO ? "set" : "not set");
errno = 0;
1.0/0.0;
show_errno();
errno = 0;
acos(+1.1);
show_errno();
errno = 0;
log(0.0);
show_errno();
errno = 0;
sin(0.0);
show_errno();
}
```
Possible output:
```
MATH_ERRNO is set
no error occurred
domain error occurred
pole or range error occurred
no error occurred
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.5 Errors <errno.h> (p: 205)
+ K.3.1.3 Use of errno (p: 584)
+ K.3.2 Errors <errno.h> (p: 585)
* C99 standard (ISO/IEC 9899:1999):
+ 7.5 Errors <errno.h> (p: 186)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.1.3 Errors <errno.h>
### See also
| | |
| --- | --- |
| [E2BIG, EACCES, ..., EXDEV](errno_macros "c/error/errno macros") | macros for standard POSIX-compatible error conditions (macro constant) |
| [perror](../io/perror "c/io/perror") | displays a character string corresponding of the current error to `[stderr](../io/std_streams "c/io/std streams")` (function) |
| [strerrorstrerror\_sstrerrorlen\_s](../string/byte/strerror "c/string/byte/strerror")
(C11)(C11) | returns a text version of a given error code (function) |
| [math\_errhandlingMATH\_ERRNOMATH\_ERREXCEPT](../numeric/math/math_errhandling "c/numeric/math/math errhandling")
(C99)(C99)(C99) | defines the error handling mechanism used by the common mathematical functions (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/error/errno "cpp/error/errno") for `errno` |
c assert assert
======
| Defined in header `<assert.h>` | | |
| --- | --- | --- |
|
```
#ifdef NDEBUG
#define assert(condition) ((void)0)
#else
#define assert(condition) /*implementation defined*/
#endif
```
| | |
The definition of the macro `assert` depends on another macro, `NDEBUG`, which is not defined by the standard library.
If `NDEBUG` is defined as a macro name at the point in the source code where `<assert.h>` is included, then `assert` does nothing.
If `NDEBUG` is not defined, then `assert` checks if its argument (which must have scalar type) compares equal to zero. If it does, `assert` outputs implementation-specific diagnostic information on the standard error output and calls `[abort](http://en.cppreference.com/w/c/program/abort)()`. The diagnostic information is required to include the text of `expression`, as well as the values of the [predefined variable](../language/function_definition "c/language/function definition") `__func__` and of (since C99) the [predefined macros](../preprocessor/replace "c/preprocessor/replace") `__FILE__` and `__LINE__`.
### Parameters
| | | |
| --- | --- | --- |
| condition | - | expression of scalar type |
### Return value
(none).
### Notes
There is no standardized interface to add an additional message to `assert` errors. A portable way to include one is to use a [comma operator](../language/operator_other#Comma_operator "c/language/operator other"):
```
assert(("There are five lights", 2 + 2 == 5));
```
The implementation of `assert` in [Microsoft CRT](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/assert-macro-assert-wassert?view=msvc-160) does not conform to C99 and later revisions, because its underlying function (`_wassert`) takes neither `__func__` nor an equivalent replacement.
### Example
```
#include <stdio.h>
// uncomment to disable assert()
// #define NDEBUG
#include <assert.h>
#include <math.h>
int main(void)
{
double x = -1.0;
assert(x >= 0.0);
printf("sqrt(x) = %f\n", sqrt(x));
return 0;
}
```
Output:
```
output with NDEBUG not defined:
a.out: main.cpp:10: main: Assertion `x >= 0.0' failed.
output with NDEBUG defined:
sqrt(x) = -nan
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 7.2.1.1 The assert macro (p: 135)
* C11 standard (ISO/IEC 9899:2011):
+ 7.2.1.1 The assert macro (p: 186-187)
* C99 standard (ISO/IEC 9899:1999):
+ 7.2.1.1 The assert macro (p: 169)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.2.1.1 The assert macro
### See also
| | |
| --- | --- |
| [abort](../program/abort "c/program/abort") | causes abnormal program termination (without cleaning up) (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/error/assert "cpp/error/assert") for `assert` |
| programming_docs |
c abort_handler_s abort\_handler\_s
=================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
void abort_handler_s( const char * restrict msg,
void * restrict ptr,
errno_t error
);
```
| | (since C11) |
Writes an implementation-defined message to `[stderr](../io/std_streams "c/io/std streams")` which must include the string pointed to by `msg` and calls `[abort()](../program/abort "c/program/abort")`.
A pointer to this function can be passed to [set\_constraint\_handler\_s](set_constraint_handler_s "c/error/set constraint handler s") to establish a runtime constraints violation handler. As with all bounds-checked functions, `abort_handler_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<stdlib.h>`.
### Parameters
| | | |
| --- | --- | --- |
| msg | - | pointer to the message written to the standard error stream |
| ptr | - | pointer to an implementation-defined object or a null pointer. Examples of implementation-defined objects are objects that give the name of the function that detected the violation and the line number when the violation was detected |
| error | - | a positive value of type errno\_t |
### Return value
none; this function does not return to its caller.
### Notes
If `set_constraint_handler_s` is never called, the default handler is implementation-defined: it may be `abort_handler_s`, `ignore_handler_s`, or some other implementation-defined handler.
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
#ifdef __STDC_LIB_EXT1__
char dst[2];
set_constraint_handler_s(ignore_handler_s);
int r = strcpy_s(dst, sizeof dst, "Too long!");
printf("dst = \"%s\", r = %d\n", dst, r);
set_constraint_handler_s(abort_handler_s);
r = strcpy_s(dst, sizeof dst, "Too long!");
printf("dst = \"%s\", r = %d\n", dst, r);
#endif
}
```
Possible output:
```
dst = "", r = 22
abort_handler_s was called in response to a runtime-constraint violation.
The runtime-constraint violation was caused by the following expression in strcpy_s:
(s1max <= (s2_len=strnlen_s(s2, s1max)) ) (in string_s.c:62)
Note to end users: This program was terminated as a result
of a bug present in the software. Please reach out to your
software's vendor to get more help.
Aborted
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ K.3.6.1.2 The abort\_handler\_s function (p: 605)
### See also
| | |
| --- | --- |
| [ignore\_handler\_s](ignore_handler_s "c/error/ignore handler s")
(C11) | ignore callback for the bounds-checked functions (function) |
| [set\_constraint\_handler\_s](set_constraint_handler_s "c/error/set constraint handler s")
(C11) | set the error callback for bounds-checked functions (function) |
c static_assert static\_assert
==============
| Defined in header `<assert.h>` | | |
| --- | --- | --- |
|
```
#define static_assert _Static_assert
```
| | |
This convenience macro expands to the keyword [\_Static\_assert](../keyword/_static_assert "c/keyword/ Static assert").
### Example
```
#include <assert.h>
int main(void)
{
static_assert(2 + 2 == 4, "2+2 isn't 4"); // well-formed
static_assert(sizeof(int) < sizeof(char),
"this program requires that int is less than char"); // compile-time error
}
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ 7.2/3 Diagnostics <assert.h> (p: 186)
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/static_assert "cpp/language/static assert") for `Static Assertion` |
c ignore_handler_s ignore\_handler\_s
==================
| Defined in header `<stdlib.h>` | | |
| --- | --- | --- |
|
```
void ignore_handler_s( const char * restrict msg,
void * restrict ptr,
errno_t error
);
```
| | (since C11) |
The function simply returns to the caller without performing any other action.
A pointer to this function can be passed to [set\_constraint\_handler\_s](set_constraint_handler_s "c/error/set constraint handler s") to establish a runtime constraints violation handler that does nothing. As with all bounds-checked functions, `ignore_handler_s` is only guaranteed to be available if `__STDC_LIB_EXT1__` is defined by the implementation and if the user defines `__STDC_WANT_LIB_EXT1__` to the integer constant `1` before including `<stdlib.h>`.
### Parameters
| | | |
| --- | --- | --- |
| msg | - | pointer to character string that describes the error |
| ptr | - | pointer to an implementation-defined object or a null pointer. Examples of implementation-defined objects are objects that give the name of the function that detected the violation and the line number when the violation was detected |
| error | - | the error about to be returned by the calling function, if it happens to be one of the functions that return errno\_t |
### Return value
(none).
### Notes
If `ignore_handler_s` is used as a the runtime constraints handler, the violations may be detected by examining the results of the bounds-checked function calls, which may be different for different functions (non-zero `errno_t`, null character written to the first byte of the output string, etc).
If `set_constraint_handler_s` is never called, the default handler is implementation-defined: it may be `abort_handler_s`, `ignore_handler_s`, or some other implementation-defined handler.
### Example
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
#ifdef __STDC_LIB_EXT1__
char dst[2];
set_constraint_handler_s(ignore_handler_s);
int r = strcpy_s(dst, sizeof dst, "Too long!");
printf("dst = \"%s\", r = %d\n", dst, r);
set_constraint_handler_s(abort_handler_s);
r = strcpy_s(dst, sizeof dst, "Too long!");
printf("dst = \"%s\", r = %d\n", dst, r);
#endif
}
```
Possible output:
```
dst = "", r = 22
abort_handler_s was called in response to a runtime-constraint violation.
The runtime-constraint violation was caused by the following expression in strcpy_s:
(s1max <= (s2_len=strnlen_s(s2, s1max)) ) (in string_s.c:62)
Note to end users: This program was terminated as a result
of a bug present in the software. Please reach out to your
software's vendor to get more help.
Aborted
```
### References
* C11 standard (ISO/IEC 9899:2011):
+ K.3.6.1.3 The ignore\_handler\_s function (p: 606)
### See also
| | |
| --- | --- |
| [abort\_handler\_s](abort_handler_s "c/error/abort handler s")
(C11) | abort callback for the bounds-checked functions (function) |
| [set\_constraint\_handler\_s](set_constraint_handler_s "c/error/set constraint handler s")
(C11) | set the error callback for bounds-checked functions (function) |
c Source file inclusion Source file inclusion
=====================
Includes another source file into the current source file at the line immediately after the directive.
### Syntax
| | | |
| --- | --- | --- |
| `#include <`filename`>` | (1) | |
| `#include "`filename`"` | (2) | |
### Explanation
Includes source file, identified by filename, into the current source file at the line immediately after the directive.
1) Searches for the file in implementation-defined manner. The intent of this syntax is to search for the files under control of the implementation. Typical implementations search only standard include directories. The standard C++ library and the standard C library are implicitly included in these standard include directories. The standard include directories usually can be controlled by the user through compiler options.
2) Searches for the file in implementation-defined manner. The intent of this syntax is to search for the files that are not controlled by the implementation. Typical implementations first search the directory where the current file resides and, only if the file is not found, search the standard include directories as with (1).
In the case the file is not found, the program is ill-formed.
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.10.2 Source file inclusion (p: 119-120)
* C11 standard (ISO/IEC 9899:2011):
+ 6.10.2 Source file inclusion (p: 164-166)
* C99 standard (ISO/IEC 9899:1999):
+ 6.10.2 Source file inclusion (p: 149-151)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.8.2 Source file inclusion
### See also
| |
| --- |
| [A list of C Standard Library header files](../index "c/header") |
| [C++ documentation](https://en.cppreference.com/w/cpp/preprocessor/include "cpp/preprocessor/include") for Source file inclusion |
c Replacing text macros Replacing text macros
=====================
The preprocessor supports text macro replacement and function-like text macro replacement.
### Syntax
| | | |
| --- | --- | --- |
| `#define` identifier replacement-list(optional) | (1) | |
| `#define` identifier`(` parameters `)` replacement-list | (2) | |
| `#define` identifier`(` parameters`, ... )` replacement-list | (3) | (since C99) |
| `#define` identifier`( ... )` replacement-list | (4) | (since C99) |
| `#undef` identifier | (5) | |
### Explanation
#### `#define` directives
The `#define` directives define the identifier as a macro, that is they instruct the compiler to replace all successive occurrences of identifier with replacement-list, which can be optionally additionally processed. If the identifier is already defined as any type of macro, the program is ill-formed unless the definitions are identical.
##### Object-like macros
Object-like macros replace every occurrence of a defined identifier with replacement-list. Version (1) of the `#define` directive behaves exactly like that.
##### Function-like macros
Function-like macros replace each occurrence of a defined identifier with replacement-list, additionally taking a number of arguments, which then replace corresponding occurrences of any of the parameters in the replacement-list.
The syntax of a function-like macro invocation is similar to the syntax of a function call: each instance of the macro name followed by a ( as the next preprocessing token introduces the sequence of tokens that is replaced by the replacement-list. The sequence is terminated by the matching ) token, skipping intervening matched pairs of left and right parentheses.
The number of arguments must be the same as the number of arguments in the macro definition (parameters) or the program is ill-formed. If the identifier is not in functional-notation, i.e. does not have parentheses after itself, it is not replaced at all.
Version (2) of the `#define` directive defines a simple function-like macro.
Version (3) of the `#define` directive defines a function-like macro with variable number of arguments. The additional arguments can be accessed using `__VA_ARGS__` identifier, which is then replaced with arguments, supplied with the identifier to be replaced.
Version (4) of the `#define` directive defines a function-like macro with variable number of arguments, but no regular arguments. The arguments can be accessed only with `__VA_ARGS__` identifier, which is then replaced with arguments, supplied with identifier to be replaced.
Note: if an argument of a function-like macro includes commas that are not protected by matched pairs of left and right parentheses (such as `macro(array[x = y, x + 1])` or `[atomic\_store](http://en.cppreference.com/w/c/atomic/atomic_store) (p, (struct S){ a, b });`), the comma is interpreted as macro argument separator, causing a compilation failure due to argument count mismatch.
#### `#` and `##` operators
In function-like macros, a `#` operator before an identifier in the replacement-list runs the identifier through parameter replacement and encloses the result in quotes, effectively creating a string literal. In addition, the preprocessor adds backslashes to escape the quotes surrounding embedded string literals, if any, and doubles the backslashes within the string as necessary. All leading and trailing whitespace is removed, and any sequence of whitespace in the middle of the text (but not inside embedded string literals) is collapsed to a single space. This operation is called "stringification". If the result of stringification is not a valid string literal, the behavior is undefined.
| | |
| --- | --- |
| When `#` appears before `__VA_ARGS__`, the entire expanded \_\_VA\_ARGS\_\_ is enclosed in quotes:
```
#define showlist(...) puts(#__VA_ARGS__)
showlist(); // expands to puts("")
showlist(1, "x", int); // expands to puts("1, \"x\", int")
```
| (since C99) |
A `##` operator between any two successive identifiers in the replacement-list runs parameter replacement on the two identifiers and then concatenates the result. This operation is called "concatenation" or "token pasting". Only tokens that form a valid token together may be pasted: identifiers that form a longer identifier, digits that form a number, or operators `+` and `=` that form a `+=`. A comment cannot be created by pasting `/` and `*` because comments are removed from text before macro substitution is considered. If the result of concatenation is not a valid token, the behavior is undefined.
Note: Some compilers offer an extension that allows ## to appear after a comma and before \_\_VA\_ARGS\_\_, in which case the ## does nothing when \_\_VA\_ARGS\_\_ is non-empty, but removes the comma when \_\_VA\_ARGS\_\_ is empty: this makes it possible to define macros such as `fprintf (stderr, format, ##__VA_ARGS__)`.
The order of evaluation of # and ## operators is unspecified.
#### `#undef` directive
The `#undef` directive undefines the identifier, that is it cancels the previous definition of the identifier by `#define` directive. If the identifier does not have an associated macro, the directive is ignored.
### Predefined macros
The following macro names are predefined in any translation unit:
| | |
| --- | --- |
| \_\_STDC\_\_ | expands to the integer constant `1`. This macro is intended to indicate a conforming implementation (macro constant) |
| \_\_STDC\_VERSION\_\_
(C95) | expands to an integer constant of type `long` whose value increases with each version of the C standard: * `199409L` (C95)
* `199901L` (C99)
* `201112L` (C11)
* `201710L` (C17) (macro constant)
|
| \_\_STDC\_HOSTED\_\_
(C99) | expands to the integer constant `1` if the implementation is hosted (runs under an OS), `0` if freestanding (runs without an OS) (macro constant) |
| \_\_FILE\_\_ | expands to the name of the current file, as a character string literal, can be changed by the [#line](line "c/preprocessor/line") directive (macro constant) |
| \_\_LINE\_\_ | expands to the source file line number, an integer constant, can be changed by the [#line](line "c/preprocessor/line") directive (macro constant) |
| \_\_DATE\_\_ | expands to the date of translation, a character string literal of the form "Mmm dd yyyy". The name of the month is as if generated by `[asctime](../chrono/asctime "c/chrono/asctime")` and the first character of "dd" is a space if the day of the month is less than 10 (macro constant) |
| \_\_TIME\_\_ | expands to the time of translation, a character string literal of the form "hh:mm:ss", as in the time generated by `[asctime](http://en.cppreference.com/w/c/chrono/asctime)()` (macro constant) |
The following additional macro names may be predefined by an implementation:
| | |
| --- | --- |
| \_\_STDC\_ISO\_10646\_\_
(C99) | expands to an integer constant of the form `yyyymmL`, if `wchar_t` uses Unicode; the date indicates the latest revision of Unicode supported (macro constant) |
| \_\_STDC\_IEC\_559\_\_
(C99) | expands to `1` if IEC 60559 is supported (deprecated) (since C23) (macro constant) |
| \_\_STDC\_IEC\_559\_COMPLEX\_\_
(C99) | expands to `1` if IEC 60559 complex arithmetic is supported (deprecated) (since C23) (macro constant) |
| \_\_STDC\_UTF\_16\_\_
(C11) | expands to `1` if `char16_t` use UTF-16 encoding (macro constant) |
| \_\_STDC\_UTF\_32\_\_
(C11) | expands to `1` if `char32_t` use UTF-32 encoding (macro constant) |
| \_\_STDC\_MB\_MIGHT\_NEQ\_WC\_\_
(C99) | expands to `1` if `'x' == L'x'` might be false for a member of the basic character set, such as on EBCDIC-based systems that use Unicode for `wchar_t` (macro constant) |
| \_\_STDC\_ANALYZABLE\_\_
(C11) | expands to `1` if [analyzability](../language/analyzability "c/language/analyzability") is supported (macro constant) |
| \_\_STDC\_LIB\_EXT1\_\_
(C11) | expands to an integer constant `201112L` if [bounds-checking interfaces](../error "c/error") are supported (macro constant) |
| \_\_STDC\_NO\_ATOMICS\_\_
(C11) | expands to `1` if [atomic](../language/atomic "c/language/atomic") types and [atomic operations library](../thread#Atomic_operations "c/thread") are not supported (macro constant) |
| \_\_STDC\_NO\_COMPLEX\_\_
(C11) | expands to `1` if [complex types](../language/arithmetic_types#Complex_floating_types "c/language/arithmetic types") and [complex math library](../numeric/complex "c/numeric/complex") are not supported (macro constant) |
| \_\_STDC\_NO\_THREADS\_\_
(C11) | expands to `1` if [multithreading](../thread "c/thread") is not supported (macro constant) |
| \_\_STDC\_NO\_VLA\_\_
(C11) | expands to `1` if [variable-length arrays](../language/array#Variable-length_arrays "c/language/array") and variably-modified types (until C23)of automatic storage duration (since C23) are not supported (macro constant) |
| \_\_STDC\_IEC\_60559\_BFP\_\_
(C23) | expands to `202ymmL` (date to be determined) if IEC 60559 binary floating-point arithmetic is supported (macro constant) |
| \_\_STDC\_IEC\_60559\_DFP\_\_
(C23) | expands to `202ymmL` (date to be determined) if IEC 60559 decimal floating-point arithmetic is supported (macro constant) |
| \_\_STDC\_IEC\_60559\_COMPLEX\_\_
(C23) | expands to `202ymmL` (date to be determined) if IEC 60559 complex arithmetic is supported (macro constant) |
The values of these macros (except for `__FILE__` and `__LINE__`) remain constant throughout the translation unit. Attempts to redefine or undefine these macros result in undefined behavior.
| | |
| --- | --- |
| The predefined variable `__func__` (see [function definition](../language/function_definition#func "c/language/function definition") for details) is not a preprocessor macro, even though it is sometimes used together with `__FILE__` and `__LINE__`, e.g. by `[assert](../error/assert "c/error/assert")`. | (since C99) |
### Example
```
#include <stdio.h>
//make function factory and use it
#define FUNCTION(name, a) int fun_##name(int x) { return (a)*x;}
FUNCTION(quadruple, 4)
FUNCTION(double, 2)
#undef FUNCTION
#define FUNCTION 34
#define OUTPUT(a) puts( #a )
int main(void)
{
printf("quadruple(13): %d\n", fun_quadruple(13) );
printf("double(21): %d\n", fun_double(21) );
printf("%d\n", FUNCTION);
OUTPUT(million); //note the lack of quotes
}
```
Output:
```
quadruple(13): 52
double(21): 42
34
million
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [DR 321](https://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_321.htm) | C99 | it was unclear if `L'x' == 'x'` always holdsamong the basic character set | `__STDC_MB_MIGHT_NEQ_WC__` added for the purpose |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.10.3 Macro replacement (p: 121-126)
+ 6.10.8 Predefined macro names (p: 127-129)
* C11 standard (ISO/IEC 9899:2011):
+ 6.10.3 Macro replacement (p: 166-173)
+ 6.10.8 Predefined macro names (p: 175-176)
* C99 standard (ISO/IEC 9899:1999):
+ 6.10.3 Macro replacement (p: 151-158)
+ 6.10.8 Predefined macro names (p: 160-161)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.8.3 Macro replacement
+ 3.8.8 Predefined macro names
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/preprocessor/replace "cpp/preprocessor/replace") for Replacing text macros |
| programming_docs |
c Implementation defined behavior control Implementation defined behavior control
=======================================
Implementation defined behavior is controlled by `#pragma` directive.
### Syntax
| | | |
| --- | --- | --- |
| `#pragma` pragma\_params | (1) | |
| `_Pragma` `(` string-literal `)` | (2) | (since C99) |
1) Behaves in an implementation-defined manner (unless pragma\_params is one of the standard pragmas shown below.
2) Removes the encoding prefix (if any), the outer quotes, and leading/trailing whitespace from string-literal, replaces each `\"` with `"` and each `\\` with `\`, then tokenizes the result (as in [translation stage 3](../language/translation_phases "c/language/translation phases")), and then uses the result as if the input to `#pragma` in (1). ### Explanation
The pragma directive controls implementation-specific behavior of the compiler, such as disabling compiler warnings or changing alignment requirements. Any pragma that is not recognized is ignored.
### Standard pragmas
The following three pragmas are defined by the language standard:
| | | |
| --- | --- | --- |
| `#pragma STDC FENV_ACCESS` arg | (1) | (since C99) |
| `#pragma STDC FP_CONTRACT` arg | (2) | (since C99) |
| `#pragma STDC CX_LIMITED_RANGE` arg | (3) | (since C99) |
where arg is either `ON` or `OFF` or `DEFAULT`.
1) If set to `ON`, informs the compiler that the program will access or modify [floating-point environment](../numeric/fenv "c/numeric/fenv"), which means that optimizations that could subvert flag tests and mode changes (e.g., global common subexpression elimination, code motion, and constant folding) are prohibited. The default value is implementation-defined, usually `OFF`.
2) Allows *contracting* of floating-point expressions, that is optimizations that omit rounding errors and floating-point exceptions that would be observed if the expression was evaluated exactly as written. For example, allows the implementation of `(x*y) + z` with a single fused multiply-add CPU instruction. The default value is implementation-defined, usually `ON`.
3) Informs the compiler that multiplication, division, and absolute value of complex numbers may use simplified mathematical formulas (x+iy)×(u+iv) = (xu-yv)+i(yu+xv), (x+iy)/(u+iv) = [(xu+yv)+i(yu-xv)]/(u2
+v2
), and |x+iy| = √x2
+y2
, despite the possibility of intermediate overflow. In other words, the programmer guarantees that the range of the values that will be passed to those function is limited. The default value is `OFF`
Note: compilers that do not support these pragmas may provide equivalent compile-time options, such as gcc's `-fcx-limited-range` and `-ffp-contract`.
### Non-standard pragmas
#### #pragma once
`#pragma once` is a non-standard pragma that is supported by the [vast majority of modern compilers](https://en.wikipedia.org/wiki/Pragma_once#Portability "enwiki:Pragma once"). If it appears in a header file, it indicates that it is only to be parsed once, even if it is (directly or indirectly) included multiple times in the same source file.
Standard approach to preventing multiple inclusion of the same header is by using [include guards](https://en.wikipedia.org/wiki/Include_guard "enwiki:Include guard"):
```
#ifndef LIBRARY_FILENAME_H
#define LIBRARY_FILENAME_H
// contents of the header
#endif /* LIBRARY_FILENAME_H */
```
So that all but the first inclusion of the header in any translation unit are excluded from compilation. All modern compilers record the fact that a header file uses an include guard and do not re-parse the file if it is encountered again, as long as the guard is still defined. (see e.g. [gcc](https://gcc.gnu.org/onlinedocs/cpp/Once-Only-Headers.html)).
With `#pragma once`, the same header appears as.
```
#pragma once
// contents of the header
```
Unlike header guards, this pragma makes it impossible to erroneously use the same macro name in more than one file. On the other hand, since with `#pragma once` files are excluded based on their filesystem-level identity, this can't protect against including a header twice if it exists in more than one location in a project.
#### #pragma pack
This family of pragmas control the maximum alignment for subsequently defined structure and union members.
| | | |
| --- | --- | --- |
| `#pragma pack(arg)` | (1) | |
| `#pragma pack()` | (2) | |
| `#pragma pack(push)` | (3) | |
| `#pragma pack(push, arg)` | (4) | |
| `#pragma pack(pop)` | (5) | |
where arg is a small power of two and specifies the new alignment in bytes.
1) Sets the current alignment to value arg.
2) Sets the current alignment to the default value (specified by a command-line option).
3) Pushes the value of the current alignment on an internal stack.
4) Pushes the value of the current alignment on the internal stack and then sets the current alignment to value arg.
5) Pops the top entry from the internal stack and then sets (restores) the current alignment to that value. `#pragma pack` may decrease the alignment of a structure, however, it cannot make a structure overaligned.
See also specific details for [GCC](https://gcc.gnu.org/onlinedocs/gcc/Structure-Layout-Pragmas.html) and [MSVC](https://docs.microsoft.com/en-us/cpp/preprocessor/pack).
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.10.9 Pragma operator (p: 129)
* C11 standard (ISO/IEC 9899:2011):
+ 6.10.9 Pragma operator (p: 178)
* C99 standard (ISO/IEC 9899:1999):
+ 6.10.6 Pragma directive (p: 159)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.8.6 Pragma directive
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/preprocessor/impl "cpp/preprocessor/impl") for Implementation defined behavior control |
### External links
* [C++ pragmas in Visual Studio 2019](https://docs.microsoft.com/en-us/cpp/preprocessor/pragma-directives-and-the-pragma-keyword?view=vs-2019)
* [Pragmas](https://gcc.gnu.org/onlinedocs/gcc/Pragmas.html) accepted by GCC
* [Individual pragma descriptions](https://www.ibm.com/support/knowledgecenter/en/SSGH3R_16.1.0/com.ibm.xlcpp161.aix.doc/compiler_ref/pragma_descriptions.html) and [Standard pragmas](https://www.ibm.com/support/knowledgecenter/en/SSGH3R_16.1.0/com.ibm.xlcpp161.aix.doc/language_ref/std_pragmas.html) in IBM AIX XL C 16.1
* [Appendix B. Pragmas](http://download.oracle.com/docs/cd/E19422-01/819-3690/Pragmas_App.html#73499) in Sun Studio 11 C++ User's Guide
* [Intel C++ compiler pragmas](https://software.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/pragmas.html)
* [HP aCC compiler pragmas](http://h21007.www2.hp.com/portal/download/files/unprot/aCxx/Online_Help/pragmas.htm)
c Diagnostic directives Diagnostic directives
=====================
Shows the given error message and renders the program ill-formed, or given warning message without affect the validity of the program (since C23).
### Syntax
| | | |
| --- | --- | --- |
| `#error` diagnostic-message | (1) | |
| `#warning` diagnostic-message | (2) | (since C23) |
### Explanation
1) After encountering the `#error` directive, an implementation displays the message diagnostic-message and renders the program ill-formed (the compilation stops).
2) Same as (1), except that the validity of the program is not affected and the compilation continues. diagnostic-message can consist of several words not necessarily in quotes.
### Notes
Before its standardization in C23, `#warning` has been provided by many compilers in all modes as a conforming extension.
### Example
```
#if __STDC__ != 1
# error "Not a standard compliant compiler"
#endif
#if __STDC_VERSION__ >= 202302L
# warning "Using #warning as a standard feature"
#endif
#include <stdio.h>
int main (void)
{
printf("The compiler used conforms to the ISO C Standard !!");
}
```
Possible output:
```
The compiler used conforms to the ISO C Standard !!
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.10.5 Error directive (p: 126-127)
* C11 standard (ISO/IEC 9899:2011):
+ 6.10.5 Error directive (p: 174)
* C99 standard (ISO/IEC 9899:1999):
+ 6.10.5 Error directive (p: 159)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.8.5 Error directive
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/preprocessor/error "cpp/preprocessor/error") for Diagnostic directives |
c Conditional inclusion Conditional inclusion
=====================
The preprocessor supports conditional compilation of parts of source file. This behavior is controlled by `#if`, `#else`, `#elif`, `#ifdef`, `#ifndef`, `#elifdef`, `#elifndef` (since C23), and `#endif` directives.
### Syntax
| | | |
| --- | --- | --- |
| `#if` expression | | |
| `#ifdef` identifier | | |
| `#ifndef` identifier | | |
| `#elif` expression | | |
| `#elifdef` identifier | | (since C23) |
| `#elifndef` identifier | | (since C23) |
| `#else` | | |
| `#endif` | | |
### Explanation
The conditional preprocessing block starts with `#if`, `#ifdef` or `#ifndef` directive, then optionally includes any number of `#elif`, `#elifdef`, or `#elifndef` (since C23) directives, then optionally includes at most one `#else` directive and is terminated with `#endif` directive. Any inner conditional preprocessing blocks are processed separately.
Each of `#if`, `#ifdef`, `#ifndef`, `#elif`, `#elifdef`, `#elifndef` (since C23), and `#else` directives control code block until first `#elif`, `#elifdef`, `#elifndef` (since C23), `#else`, `#endif` directive not belonging to any inner conditional preprocessing blocks.
`#if`, `#ifdef` and `#ifndef` directives test the specified condition (see below) and if it evaluates to true, compiles the controlled code block. In that case subsequent `#else`, `#elifdef`, `#elifndef`, (since C23) and `#elif` directives are ignored. Otherwise, if the specified condition evaluates false, the controlled code block is skipped and the subsequent `#else`, `#elifdef`, `#elifndef`, (since C23) or `#elif` directive (if any) is processed. If the subsequent directive is `#else`, the code block controlled by the `#else` directive is unconditionally compiled. Otherwise, the `#elif`, `#elifdef`, or `#elifndef` (since C23) directive acts as if it was `#if` directive: checks for condition, compiles or skips the controlled code block based on the result, and in the latter case processes subsequent `#elif`, `#elifdef`, `#elifndef`, (since C23) and `#else` directives. The conditional preprocessing block is terminated by `#endif` directive.
### Conditional evaluation
#### `#if, #elif`
The expression is a constant expression, using only [constants](../language/expressions#Constants_and_literals "c/language/expressions") and identifiers, defined using [`#define`](replace "c/preprocessor/replace") directive. Any identifier, which is not literal, non defined using [`#define`](replace "c/preprocessor/replace") directive, evaluates to *0*.
The expression may contain unary operators in form `defined` identifier or `defined (`identifier`)` which return `1` if the identifier was defined using [`#define`](replace "c/preprocessor/replace") directive and *0* otherwise. If the expression evaluates to nonzero value, the controlled code block is included and skipped otherwise. If any used identifier is not a constant, it is replaced with `0`.
| | |
| --- | --- |
| In context of a preprocessor directive, a `__has_c_attribute` expression detects whether a given attribute token is supported and its supported version. See [Attribute testing](../language/attributes#Attribute_testing "c/language/attributes"). | (since C23) |
Note: Until DR 412, `#if cond1` ... `#elif cond2` is different from `#if cond1` ... `#else` followed by `#if cond3` because if `cond1` is true, the second `#if` is skipped and `cond3` does not need to be well-formed, while #elif's `cond2` must be a valid expression. As of DR 412, #elif that leads the skipped code block is also skipped.
#### Combined directives
Checks if the identifier was [defined as a macro name](replace "c/preprocessor/replace").
`#ifdef` identifier is essentially equivalent to `#if defined` identifier.
`#ifndef` identifier is essentially equivalent to `#if !defined` identifier.
| | |
| --- | --- |
| `#elifdef` identifier is essentially equivalent to `#elif defined` identifier.
`#elifndef` identifier is essentially equivalent to `#elif !defined` identifier. | (since C23) |
### Notes
While `#elifdef` and `#elifndef` directives target C23, implementations may backport them to the older language modes as conforming extensions.
### Example
```
#define ABCD 2
#include <stdio.h>
int main(void)
{
#ifdef ABCD
printf("1: yes\n");
#else
printf("1: no\n");
#endif
#ifndef ABCD
printf("2: no1\n");
#elif ABCD == 2
printf("2: yes\n");
#else
printf("2: no2\n");
#endif
#if !defined(DCBA) && (ABCD < 2*4-3)
printf("3: yes\n");
#endif
// C23 directives #elifdef/#elifndef
#ifdef CPU
printf("4: no1\n");
#elifdef GPU
printf("4: no2\n");
#elifndef RAM
printf("4: yes\n"); // selected in C23 mode, may be selected in pre-C23 mode
#else
printf("4: no3\n"); // may be selected in pre-C23 mode
#endif
}
```
Possible output:
```
1: yes
2: yes
3: yes
4: yes
```
### Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C standards.
| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| [DR 412](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_412) | C89 | failed `#elif`'s expression was required to be valid | failed `#elif` is skipped |
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.10.1 Conditional inclusion (p: 118-119)
* C11 standard (ISO/IEC 9899:2011):
+ 6.10.1 Conditional inclusion (p: 162-164)
* C99 standard (ISO/IEC 9899:1999):
+ 6.10.1 Conditional inclusion (p: 147-149)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.8.1 Conditional inclusion
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/preprocessor/conditional "cpp/preprocessor/conditional") for Conditional inclusion |
c Filename and line information Filename and line information
=============================
Changes the current line number and file name in the preprocessor.
### Syntax
| | | |
| --- | --- | --- |
| `#line` lineno | (1) | |
| `#line` lineno `"`filename`"` | (2) | |
### Explanation
1) Changes the current preprocessor line number to lineno. Occurrences of the macro `__LINE__` beyond this point will expand to lineno plus the number of actual source code lines encountered since.
2) Also changes the current preprocessor file name to filename. Occurrences of the macro `__FILE__` beyond this point will produce filename. Any preprocessing tokens (macro constants or expressions) are permitted as arguments to `#line` as long as they expand to a valid decimal integer optionally following a valid character string.
lineno must be a sequence of at least one decimal digit (the program is ill-formed, otherwise) and is always interpreted as decimal (even if it starts with `0`).
If lineno is `0` or greater than `32767` (until C99)`2147483647` (since C99), the behavior is undefined.
### Notes
This directive is used by some automatic code generation tools which produce C source files from a file written in another language. In that case, `#line` directives may be inserted in the generated C file referencing line numbers and the file name of the original (human-editable) source file.
The line number following the directive `#line __LINE__` is unspecified (there are two possible values that `__LINE__` can expand to in this case: number of endlines seen so far, or number of endlines seen so far plus the endline that ends the `#line` directive). This is the result of [DR 464](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2257.htm#dr_464), which applies retroactively.
### Example
```
#include <assert.h>
#define FNAME "test.c"
int main(void)
{
#line 777 FNAME
assert(2+2 == 5);
}
```
Possible output:
```
test: test.c:777: int main(): Assertion `2+2 == 5' failed.
```
### References
* C17 standard (ISO/IEC 9899:2018):
+ 6.10.4 Line control (p: 126)
+ J.1 Unspecified behavior
* C11 standard (ISO/IEC 9899:2011):
+ 6.10.4 Line control (p: 173)
* C99 standard (ISO/IEC 9899:1999):
+ 6.10.4 Line control (p: 158)
* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.8.4 Line control
### See also
| |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/preprocessor/line "cpp/preprocessor/line") for Filename and line information |
prettier Plugins Plugins
=======
Plugins are ways of adding new languages or formatting rules to Prettier. Prettier’s own implementations of all languages are expressed using the plugin API. The core `prettier` package contains JavaScript and other web-focused languages built in. For additional languages you’ll need to install a plugin.
Using Plugins
--------------
Plugins are automatically loaded if you have them installed in the same `node_modules` directory where `prettier` is located. Plugin package names must start with `@prettier/plugin-` or `prettier-plugin-` or `@<scope>/prettier-plugin-` to be registered.
> `<scope>` should be replaced by a name, read more about [NPM scope](https://docs.npmjs.com/misc/scope.html).
>
>
When plugins cannot be found automatically, you can load them with:
* The [CLI](cli), via `--plugin-search-dir` and `--plugin`:
```
prettier --write main.foo --plugin-search-dir=./dir-with-plugins --plugin=prettier-plugin-foo
```
> Tip: You can set `--plugin-search-dir` or `--plugin` options multiple times.
>
>
* The [API](api), via the `pluginSearchDirs` and `plugins` options:
```
prettier.format("code", {
parser: "foo",
pluginSearchDirs: ["./dir-with-plugins"],
plugins: ["prettier-plugin-foo"],
});
```
* The [Configuration File](configuration):
```
{
"pluginSearchDirs": ["./dir-with-plugins"],
"plugins": ["prettier-plugin-foo"]
}
```
`pluginSearchDirs` and `plugins` are independent and one does not require the other.
The paths that are provided to `pluginSearchDirs` will be searched for `@prettier/plugin-*`, `prettier-plugin-*`, and `@*/prettier-plugin-*`. For instance, these can be your project directory, a `node_modules` directory, the location of global npm modules, or any arbitrary directory that contains plugins.
Strings provided to `plugins` are ultimately passed to `require()`, so you can provide a module/package name, a path, or anything else `require()` takes. (`pluginSearchDirs` works the same way. That is, valid plugin paths that it finds are passed to `require()`.)
To turn off plugin autoloading, use `--no-plugin-search` when using Prettier CLI or add `{ pluginSearchDirs: false }` to options in `prettier.format()` or to the config file.
Official Plugins
-----------------
* [`@prettier/plugin-php`](https://github.com/prettier/plugin-php)
* [`@prettier/plugin-pug`](https://github.com/prettier/plugin-pug) by [**@Shinigami92**](https://github.com/Shinigami92)
* [`@prettier/plugin-ruby`](https://github.com/prettier/plugin-ruby)
* [`@prettier/plugin-xml`](https://github.com/prettier/plugin-xml)
Community Plugins
------------------
* [`prettier-plugin-apex`](https://github.com/dangmai/prettier-plugin-apex) by [**@dangmai**](https://github.com/dangmai)
* [`prettier-plugin-astro`](https://github.com/withastro/prettier-plugin-astro) by [**@withastro contributors**](https://github.com/withastro/prettier-plugin-astro/graphs/contributors)
* [`prettier-plugin-elm`](https://github.com/gicentre/prettier-plugin-elm) by [**@giCentre**](https://github.com/gicentre)
* [`prettier-plugin-erb`](https://github.com/adamzapasnik/prettier-plugin-erb) by [**@adamzapasnik**](https://github.com/adamzapasnik)
* [`prettier-plugin-glsl`](https://github.com/NaridaL/glsl-language-toolkit/tree/main/packages/prettier-plugin-glsl) by [**@NaridaL**](https://github.com/NaridaL)
* [`prettier-plugin-go-template`](https://github.com/NiklasPor/prettier-plugin-go-template) by [**@NiklasPor**](https://github.com/NiklasPor)
* [`prettier-plugin-java`](https://github.com/jhipster/prettier-java) by [**@JHipster**](https://github.com/jhipster)
* [`prettier-plugin-jsonata`](https://github.com/Stedi/prettier-plugin-jsonata) by [**@Stedi**](https://github.com/Stedi)
* [`prettier-plugin-kotlin`](https://github.com/Angry-Potato/prettier-plugin-kotlin) by [**@Angry-Potato**](https://github.com/Angry-Potato)
* [`prettier-plugin-motoko`](https://github.com/dfinity/prettier-plugin-motoko) by [**@dfinity**](https://github.com/dfinity)
* [`prettier-plugin-nginx`](https://github.com/joedeandev/prettier-plugin-nginx) by [**@joedeandev**](https://github.com/joedeandev)
* [`prettier-plugin-prisma`](https://github.com/umidbekk/prettier-plugin-prisma) by [**@umidbekk**](https://github.com/umidbekk)
* [`prettier-plugin-properties`](https://github.com/eemeli/prettier-plugin-properties) by [**@eemeli**](https://github.com/eemeli)
* [`prettier-plugin-sh`](https://github.com/un-ts/prettier/tree/master/packages/sh) by [**@JounQin**](https://github.com/JounQin)
* [`prettier-plugin-sql`](https://github.com/un-ts/prettier/tree/master/packages/sql) by [**@JounQin**](https://github.com/JounQin)
* [`prettier-plugin-solidity`](https://github.com/prettier-solidity/prettier-plugin-solidity) by [**@mattiaerre**](https://github.com/mattiaerre)
* [`prettier-plugin-svelte`](https://github.com/UnwrittenFun/prettier-plugin-svelte) by [**@UnwrittenFun**](https://github.com/UnwrittenFun)
* [`prettier-plugin-toml`](https://github.com/bd82/toml-tools/tree/master/packages/prettier-plugin-toml) by [**@bd82**](https://github.com/bd82)
Developing Plugins
-------------------
Prettier plugins are regular JavaScript modules with five exports:
* `languages`
* `parsers`
* `printers`
* `options`
* `defaultOptions`
###
`languages`
Languages is an array of language definitions that your plugin will contribute to Prettier. It can include all of the fields specified in [`prettier.getSupportInfo()`](api#prettiergetsupportinfo).
It **must** include `name` and `parsers`.
```
export const languages = [
{
// The language name
name: "InterpretedDanceScript",
// Parsers that can parse this language.
// This can be built-in parsers, or parsers you have contributed via this plugin.
parsers: ["dance-parse"],
},
];
```
###
`parsers`
Parsers convert code as a string into an [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree).
The key must match the name in the `parsers` array from `languages`. The value contains a parse function, an AST format name, and two location extraction functions (`locStart` and `locEnd`).
```
export const parsers = {
"dance-parse": {
parse,
// The name of the AST that
astFormat: "dance-ast",
hasPragma,
locStart,
locEnd,
preprocess,
},
};
```
The signature of the `parse` function is:
```
function parse(text: string, parsers: object, options: object): AST;
```
The location extraction functions (`locStart` and `locEnd`) return the starting and ending locations of a given AST node:
```
function locStart(node: object): number;
```
*(Optional)* The pragma detection function (`hasPragma`) should return if the text contains the pragma comment.
```
function hasPragma(text: string): boolean;
```
*(Optional)* The preprocess function can process the input text before passing into `parse` function.
```
function preprocess(text: string, options: object): string;
```
###
`printers`
Printers convert ASTs into a Prettier intermediate representation, also known as a Doc.
The key must match the `astFormat` that the parser produces. The value contains an object with a `print` function. All other properties (`embed`, `preprocess`, etc.) are optional.
```
export const printers = {
"dance-ast": {
print,
embed,
preprocess,
insertPragma,
canAttachComment,
isBlockComment,
printComment,
getCommentChildNodes,
handleComments: {
ownLine,
endOfLine,
remaining,
},
},
};
```
####
The printing process
Prettier uses an intermediate representation, called a Doc, which Prettier then turns into a string (based on options like `printWidth`). A *printer*'s job is to take the AST generated by `parsers[<parser name>].parse` and return a Doc. A Doc is constructed using [builder commands](https://github.com/prettier/prettier/blob/main/commands.md):
```
const { join, line, ifBreak, group } = require("prettier").doc.builders;
```
The printing process works as follows:
1. `preprocess(ast: AST, options: object): AST`, if available, is called. It is passed the AST from the *parser*. The AST returned by `preprocess` will be used by Prettier. If `preprocess` is not defined, the AST returned from the *parser* will be used.
2. Comments are attached to the AST (see *Handling comments in a printer* for details).
3. A Doc is recursively constructed from the AST. i) `embed(path: AstPath, print, textToDoc, options: object): Doc | null` is called on each AST node. If `embed` returns a Doc, that Doc is used. ii) If `embed` is undefined or returns a falsy value, `print(path: AstPath, options: object, print): Doc` is called on each AST node.
####
`print`
Most of the work of a plugin's printer will take place in its `print` function, whose signature is:
```
function print(
// Path to the AST node to print
path: AstPath,
options: object,
// Recursively print a child node
print: (selector?: string | number | Array<string | number> | AstPath) => Doc
): Doc;
```
The `print` function is passed the following parameters:
* **`path`**: An object, which can be used to access nodes in the AST. It’s a stack-like data structure that maintains the current state of the recursion. It is called “path” because it represents the path to the current node from the root of the AST. The current node is returned by `path.getValue()`.
* **`options`**: A persistent object, which contains global options and which a plugin may mutate to store contextual data.
* **`print`**: A callback for printing sub-nodes. This function contains the core printing logic that consists of steps whose implementation is provided by plugins. In particular, it calls the printer’s `print` function and passes itself to it. Thus, the two `print` functions – the one from the core and the one from the plugin – call each other while descending down the AST recursively.
Here’s a simplified example to give an idea of what a typical implementation of `print` looks like:
```
const {
builders: { group, indent, join, line, softline },
} = require("prettier").doc;
function print(path, options, print) {
const node = path.getValue();
switch (node.type) {
case "list":
return group([
"(",
indent([softline, join(line, path.map(print, "elements"))]),
softline,
")",
]);
case "pair":
return group([
"(",
indent([softline, print("left"), line, ". ", print("right")]),
softline,
")",
]);
case "symbol":
return node.name;
}
throw new Error(`Unknown node type: ${node.type}`);
}
```
Check out [prettier-python's printer](https://github.com/prettier/prettier-python/blob/034ba8a9551f3fa22cead41b323be0b28d06d13b/src/printer.js#L174) for some examples of what is possible.
####
(optional) `embed`
The `embed` function is called when the plugin needs to print one language inside another. Examples of this are printing CSS-in-JS or fenced code blocks in Markdown. Its signature is:
```
function embed(
// Path to the current AST node
path: AstPath,
// Print a node with the current printer
print: (selector?: string | number | Array<string | number> | AstPath) => Doc,
// Parse and print some text using a different parser.
// You should set `options.parser` to specify which parser to use.
textToDoc: (text: string, options: object) => Doc,
// Current options
options: object
): Doc | null;
```
The `embed` function acts like the `print` function, except that it is passed an additional `textToDoc` function, which can be used to render a doc using a different plugin. The `embed` function returns a Doc or a falsy value. If a falsy value is returned, the `print` function is called with the current `path`. If a Doc is returned, that Doc is used in printing and the `print` function is not called.
For example, a plugin that had nodes with embedded JavaScript might have the following `embed` function:
```
function embed(path, print, textToDoc, options) {
const node = path.getValue();
if (node.type === "javascript") {
return textToDoc(node.javaScriptText, { ...options, parser: "babel" });
}
return false;
}
```
####
(optional) `preprocess`
The preprocess function can process the AST from parser before passing into `print` function.
```
function preprocess(ast: AST, options: object): AST;
```
####
(optional) `insertPragma`
A plugin can implement how a pragma comment is inserted in the resulting code when the `--insert-pragma` option is used, in the `insertPragma` function. Its signature is:
```
function insertPragma(text: string): string;
```
####
Handling comments in a printer
Comments are often not part of a language's AST and present a challenge for pretty printers. A Prettier plugin can either print comments itself in its `print` function or rely on Prettier's comment algorithm.
By default, if the AST has a top-level `comments` property, Prettier assumes that `comments` stores an array of comment nodes. Prettier will then use the provided `parsers[<plugin>].locStart`/`locEnd` functions to search for the AST node that each comment "belongs" to. Comments are then attached to these nodes **mutating the AST in the process**, and the `comments` property is deleted from the AST root. The `*Comment` functions are used to adjust Prettier's algorithm. Once the comments are attached to the AST, Prettier will automatically call the `printComment(path, options): Doc` function and insert the returned doc into the (hopefully) correct place.
####
(optional) `getCommentChildNodes`
By default, Prettier searches all object properties (except for a few predefined ones) of each node recursively. This function can be provided to override that behavior. It has the signature:
```
function getCommentChildNodes(
// The node whose children should be returned.
node: AST,
// Current options
options: object
): AST[] | undefined;
```
Return `[]` if the node has no children or `undefined` to fall back on the default behavior.
####
(optional) `printComment`
Called whenever a comment node needs to be printed. It has the signature:
```
function printComment(
// Path to the current comment node
commentPath: AstPath,
// Current options
options: object
): Doc;
```
####
(optional) `canAttachComment`
```
function canAttachComment(node: AST): boolean;
```
This function is used for deciding whether a comment can be attached to a particular AST node. By default, *all* AST properties are traversed searching for nodes that comments can be attached to. This function is used to prevent comments from being attached to a particular node. A typical implementation looks like
```
function canAttachComment(node) {
return node.type && node.type !== "comment";
}
```
####
(optional) `isBlockComment`
```
function isBlockComment(node: AST): boolean;
```
Returns whether or not the AST node is a block comment.
####
(optional) `handleComments`
The `handleComments` object contains three optional functions, each with signature
```
function(
// The AST node corresponding to the comment
comment: AST,
// The full source code text
text: string,
// The global options object
options: object,
// The AST
ast: AST,
// Whether this comment is the last comment
isLastComment: boolean
): boolean
```
These functions are used to override Prettier's default comment attachment algorithm. `ownLine`/`endOfLine`/`remaining` is expected to either manually attach a comment to a node and return `true`, or return `false` and let Prettier attach the comment.
Based on the text surrounding a comment node, Prettier dispatches:
* `ownLine` if a comment has only whitespace preceding it and a newline afterwards,
* `endOfLine` if a comment has a newline afterwards but some non-whitespace preceding it,
* `remaining` in all other cases.
At the time of dispatching, Prettier will have annotated each AST comment node (i.e., created new properties) with at least one of `enclosingNode`, `precedingNode`, or `followingNode`. These can be used to aid a plugin's decision process (of course the entire AST and original text is also passed in for making more complicated decisions).
####
Manually attaching a comment
The `util.addTrailingComment`/`addLeadingComment`/`addDanglingComment` functions can be used to manually attach a comment to an AST node. An example `ownLine` function that ensures a comment does not follow a "punctuation" node (made up for demonstration purposes) might look like:
```
const { util } = require("prettier");
function ownLine(comment, text, options, ast, isLastComment) {
const { precedingNode } = comment;
if (precedingNode && precedingNode.type === "punctuation") {
util.addTrailingComment(precedingNode, comment);
return true;
}
return false;
}
```
Nodes with comments are expected to have a `comments` property containing an array of comments. Each comment is expected to have the following properties: `leading`, `trailing`, `printed`.
The example above uses `util.addTrailingComment`, which automatically sets `comment.leading`/`trailing`/`printed` to appropriate values and adds the comment to the AST node's `comments` array.
The `--debug-print-comments` CLI flag can help with debugging comment attachment issues. It prints a detailed list of comments, which includes information on how every comment was classified (`ownLine`/`endOfLine`/`remaining`, `leading`/`trailing`/`dangling`) and to which node it was attached. For Prettier’s built-in languages, this information is also available on the Playground (the 'show comments' checkbox in the Debug section).
###
`options`
`options` is an object containing the custom options your plugin supports.
Example:
```
options: {
openingBraceNewLine: {
type: "boolean",
category: "Global",
default: true,
description: "Move open brace for code blocks onto new line."
}
}
```
###
`defaultOptions`
If your plugin requires different default values for some of Prettier’s core options, you can specify them in `defaultOptions`:
```
defaultOptions: {
tabWidth: 4
}
```
###
Utility functions
A `util` module from Prettier core is considered a private API and is not meant to be consumed by plugins. Instead, the `util-shared` module provides the following limited set of utility functions for plugins:
```
type Quote = '"' | "'";
type SkipOptions = { backwards?: boolean };
function getMaxContinuousCount(str: string, target: string): number;
function getStringWidth(text: string): number;
function getAlignmentSize(value: string, tabWidth: number, startIndex?: number): number;
function getIndentSize(value: string, tabWidth: number): number;
function skip(chars: string | RegExp): (text: string, index: number | false, opts?: SkipOptions) => number | false;
function skipWhitespace(text: string, index: number | false, opts?: SkipOptions): number | false;
function skipSpaces(text: string, index: number | false, opts?: SkipOptions): number | false;
function skipToLineEnd(text: string, index: number | false, opts?: SkipOptions): number | false;
function skipEverythingButNewLine(text: string, index: number | false, opts?: SkipOptions): number | false;
function skipInlineComment(text: string, index: number | false): number | false;
function skipTrailingComment(text: string, index: number | false): number | false;
function skipNewline(text: string, index: number | false, opts?: SkipOptions): number | false;
function hasNewline(text: string, index: number, opts?: SkipOptions): boolean;
function hasNewlineInRange(text: string, start: number, end: number): boolean;
function hasSpaces(text: string, index: number, opts?: SkipOptions): boolean;
function makeString(rawContent: string, enclosingQuote: Quote, unescapeUnnecessaryEscapes?: boolean): string;
function getNextNonSpaceNonCommentCharacterIndex<N>(text: string, node: N, locEnd: (node: N) => number): number | false;
function isNextLineEmptyAfterIndex(text: string, index: number): boolean;
function isNextLineEmpty<N>(text: string, node: N, locEnd: (node: N) => number): boolean;
function isPreviousLineEmpty<N>(text: string, node: N, locStart: (node: N) => number): boolean;
```
###
Tutorials
* [How to write a plugin for Prettier](https://medium.com/@fvictorio/how-to-write-a-plugin-for-prettier-a0d98c845e70): Teaches you how to write a very basic Prettier plugin for TOML.
Testing Plugins
----------------
Since plugins can be resolved using relative paths, when working on one you can do:
```
const prettier = require("prettier");
const code = "(add 1 2)";
prettier.format(code, {
parser: "lisp",
plugins: ["."],
});
```
This will resolve a plugin relative to the current working directory.
| programming_docs |
prettier Option Philosophy Option Philosophy
=================
> Prettier has a few options because of history. **But we won’t add more of them.**
>
> Read on to learn more.
>
>
Prettier is not a kitchen-sink code formatter that attempts to print your code in any way you wish. It is *opinionated.* Quoting the [Why Prettier?](why-prettier) page:
> By far the biggest reason for adopting Prettier is to stop all the ongoing debates over styles.
>
>
Yet the more options Prettier has, the further from the above goal it gets. **The debates over styles just turn into debates over which Prettier options to use.** Formatting wars break out with renewed vigour: “Which option values are better? Why? Did we make the right choices?”
And it’s not the only cost options have. To learn more about their downsides, see the [issue about resisting adding configuration](https://github.com/prettier/prettier/issues/40), which has more 👍s than any option request issue.
So why are there any options at all?
* A few were added during Prettier’s infancy to make it take off at all. 🚀
* A couple were added after “great demand.” 🤔
* Some were added for compatibility reasons. 👍
Options that are easier to motivate include:
* `--trailing-comma es5` lets you use trailing commas in most environments without having to transpile (trailing function commas were added in ES2017).
* `--prose-wrap` is important to support all quirky Markdown renderers in the wild.
* `--html-whitespace-sensitivity` is needed due to the unfortunate whitespace rules of HTML.
* `--end-of-line` makes it easier for teams to keep CRLFs out of their git repositories.
* `--quote-props` is important for advanced usage of the Google Closure Compiler.
But other options are harder to motivate in hindsight: `--arrow-parens`, `--jsx-single-quote`, `--bracket-same-line` and `--no-bracket-spacing` are not the type of options we’re happy to have. They cause a lot of [bike-shedding](https://en.wikipedia.org/wiki/Law_of_triviality) in teams, and we’re sorry for that. Difficult to remove now, these options exist as a historical artifact and should not motivate adding more options (“If *those* options exist, why can’t this one?”).
For a long time, we left option requests open in order to let discussions play out and collect feedback. What we’ve learned during those years is that it’s really hard to measure demand. Prettier has grown a lot in usage. What was “great demand” back in the day is not as much today. GitHub reactions and Twitter polls became unrepresentative. What about all silent users? It looked easy to add “just one more” option. But where should we have stopped? When is one too many? Even after adding “that one final option”, there would always be a “top issue” in the issue tracker.
However, the time to stop has come. Now that Prettier is mature enough and we see it adopted by so many organizations and projects, the research phase is over. We have enough confidence to conclude that Prettier reached a point where the set of options should be “frozen”. **Option requests aren’t accepted anymore.** We’re thankful to everyone who participated in this difficult journey.
Please note that as option requests are out of scope for Prettier, they will be closed without discussion. The same applies to requests to preserve elements of input formatting (e.g. line breaks) since that’s nothing else but an option in disguise with all the downsides of “real” options. There may be situations where adding an option can’t be avoided because of technical necessity (e.g. compatibility), but for formatting-related options, this is final.
prettier Install Install
=======
First, install Prettier locally:
npm
yarn
```
npm install --save-dev --save-exact prettier
```
```
yarn add --dev --exact prettier
```
Then, create an empty config file to let editors and other tools know you are using Prettier:
```
echo {}> .prettierrc.json
```
Next, create a [.prettierignore](ignore) file to let the Prettier CLI and editors know which files to *not* format. Here’s an example:
```
# Ignore artifacts:
build
coverage
```
> Tip! Base your .prettierignore on .gitignore and .eslintignore (if you have one).
>
>
> Another tip! If your project isn’t ready to format, say, HTML files yet, add `*.html`.
>
>
Now, format all files with Prettier:
npm
yarn
```
npx prettier --write .
```
> What is that `npx` thing? `npx` ships with `npm` and lets you run locally installed tools. We’ll leave off the `npx` part for brevity throughout the rest of this file!
>
> Note: If you forget to install Prettier first, `npx` will temporarily download the latest version. That’s not a good idea when using Prettier, because we change how code is formatted in each release! It’s important to have a locked down version of Prettier in your `package.json`. And it’s faster, too.
>
>
```
yarn prettier --write .
```
> What is `yarn` doing at the start? `yarn prettier` runs the locally installed version of Prettier. We’ll leave off the `yarn` part for brevity throughout the rest of this file!
>
>
`prettier --write .` is great for formatting everything, but for a big project it might take a little while. You may run `prettier --write app/` to format a certain directory, or `prettier --write app/components/Button.js` to format a certain file. Or use a *glob* like `prettier --write "app/**/*.test.js"` to format all tests in a directory (see [fast-glob](https://github.com/mrmlnc/fast-glob#pattern-syntax) for supported glob syntax).
If you have a CI setup, run the following as part of it to make sure that everyone runs Prettier. This avoids merge conflicts and other collaboration issues!
```
npx prettier --check .
```
`--check` is like `--write`, but only checks that files are already formatted, rather than overwriting them. `prettier --write` and `prettier --check` are the most common ways to run Prettier.
Set up your editor
-------------------
Formatting from the command line is a good way to get started, but you get the most from Prettier by running it from your editor, either via a keyboard shortcut or automatically whenever you save a file. When a line has gotten so long while coding that it won’t fit your screen, just hit a key and watch it magically be wrapped into multiple lines! Or when you paste some code and the indentation gets all messed up, let Prettier fix it up for you without leaving your editor.
See [Editor Integration](editors) for how to set up your editor. If your editor does not support Prettier, you can instead [run Prettier with a file watcher](watching-files).
> **Note:** Don’t skip the regular local install! Editor plugins will pick up your local version of Prettier, making sure you use the correct version in every project. (You wouldn’t want your editor accidentally causing lots of changes because it’s using a newer version of Prettier than your project!)
>
> And being able to run Prettier from the command line is still a good fallback, and needed for CI setups.
>
>
ESLint (and other linters)
---------------------------
If you use ESLint, install [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier#installation) to make ESLint and Prettier play nice with each other. It turns off all ESLint rules that are unnecessary or might conflict with Prettier. There’s a similar config for Stylelint: [stylelint-config-prettier](https://github.com/prettier/stylelint-config-prettier)
(See [Prettier vs. Linters](comparison) to learn more about formatting vs linting, [Integrating with Linters](integrating-with-linters) for more in-depth information on configuring your linters, and [Related projects](related-projects) for even more integration possibilities, if needed.)
Git hooks
----------
In addition to running Prettier from the command line (`prettier --write`), checking formatting in CI, and running Prettier from your editor, many people like to run Prettier as a pre-commit hook as well. This makes sure all your commits are formatted, without having to wait for your CI build to finish.
For example, you can do the following to have Prettier run before each commit:
1. Install [husky](https://github.com/typicode/husky) and [lint-staged](https://github.com/okonet/lint-staged):
npm
yarn
```
npm install --save-dev husky lint-staged
npx husky install
npm pkg set scripts.prepare="husky install"
npx husky add .husky/pre-commit "npx lint-staged"
```
```
yarn add --dev husky lint-staged
npx husky install
npm pkg set scripts.prepare="husky install"
npx husky add .husky/pre-commit "npx lint-staged"
```
> If you use Yarn 2, see <https://typicode.github.io/husky/#/?id=yarn-2>
>
>
2. Add the following to your `package.json`:
```
{
"lint-staged": {
"\*\*/\*": "prettier --write --ignore-unknown"
}
}
```
> Note: If you use ESLint, make sure lint-staged runs it before Prettier, not after.
>
>
See [Pre-commit Hook](precommit) for more information.
Summary
--------
To summarize, we have learned to:
* Install an exact version of Prettier locally in your project. This makes sure that everyone in the project gets the exact same version of Prettier. Even a patch release of Prettier can result in slightly different formatting, so you wouldn’t want different team members using different versions and formatting each other’s changes back and forth.
* Add a `.prettierrc.json` to let your editor know that you are using Prettier.
* Add a `.prettierignore` to let your editor know which files *not* to touch, as well as for being able to run `prettier --write .` to format the entire project (without mangling files you don’t want, or choking on generated files).
* Run `prettier --check .` in CI to make sure that your project stays formatted.
* Run Prettier from your editor for the best experience.
* Use [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) to make Prettier and ESLint play nice together.
* Set up a pre-commit hook to make sure that every commit is formatted.
prettier Browser Browser
=======
Run Prettier in the browser using its **standalone** version. This version doesn’t depend on Node.js. It only formats the code and has no support for config files, ignore files, CLI usage, or automatic loading of plugins.
The standalone version comes as:
* ES modules: `esm/standalone.mjs`, starting in version 2.2
* UMD: `standalone.js`, starting in version 1.13
The [`browser` field](https://github.com/defunctzombie/package-browser-field-spec) in Prettier’s `package.json` points to `standalone.js`. That’s why you can just `import` or `require` the `prettier` module to access Prettier’s API, and your code can stay compatible with both Node and the browser as long as webpack or another bundler that supports the `browser` field is used. This is especially convenient for <plugins>.
###
`prettier.format(code, options)`
Required options:
* **[`parser`](options#parser) (or [`filepath`](options#file-path))**: One of these options has to be specified for Prettier to know which parser to use.
* **`plugins`**: Unlike the `format` function from the [Node.js-based API](api#prettierformatsource--options), this function doesn’t load plugins automatically. The `plugins` option is required because all the parsers included in the Prettier package come as plugins (for reasons of file size). These plugins are files named
+ `parser-*.js` in <https://unpkg.com/browse/[email protected]/> and
+ `parser-*.mjs` in <https://unpkg.com/browse/[email protected]/esm/>You need to load the ones that you’re going to use and pass them to `prettier.format` using the `plugins` option.
See below for examples.
Usage
------
###
Global
```
<script src="https://unpkg.com/[email protected]/standalone.js"></script>
<script src="https://unpkg.com/[email protected]/parser-graphql.js"></script>
<script>
prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins: prettierPlugins,
});
</script>
```
Note that the [`unpkg` field](https://unpkg.com/#examples) in Prettier’s `package.json` points to `standalone.js`, that’s why `https://unpkg.com/prettier` can also be used instead of `https://unpkg.com/prettier/standalone.js`.
###
ES Modules
```
<script type="module">
import prettier from "https://unpkg.com/[email protected]/esm/standalone.mjs";
import parserGraphql from "https://unpkg.com/[email protected]/esm/parser-graphql.mjs";
prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins: [parserGraphql],
});
</script>
```
###
AMD
```
define([
"https://unpkg.com/[email protected]/standalone.js",
"https://unpkg.com/[email protected]/parser-graphql.js",
], (prettier, ...plugins) => {
prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins,
});
});
```
###
CommonJS
```
const prettier = require("prettier/standalone");
const plugins = [require("prettier/parser-graphql")];
prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins,
});
```
This syntax doesn’t necessarily work in the browser, but it can be used when bundling the code with browserify, Rollup, webpack, or another bundler.
###
Worker
```
importScripts("https://unpkg.com/[email protected]/standalone.js");
importScripts("https://unpkg.com/[email protected]/parser-graphql.js");
prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins: prettierPlugins,
});
```
Parser plugins for embedded code
---------------------------------
If you want to format [embedded code](options#embedded-language-formatting), you need to load related plugins too. For example:
```
<script type="module">
import prettier from "https://unpkg.com/[email protected]/esm/standalone.mjs";
import parserBabel from "https://unpkg.com/[email protected]/esm/parser-babel.mjs";
console.log(
prettier.format("const html=/\* HTML \*/ `<DIV> </DIV>`", {
parser: "babel",
plugins: [parserBabel],
})
);
// Output: const html = /\* HTML \*/ `<DIV> </DIV>`;
</script>
```
The HTML code embedded in JavaScript stays unformatted because the `html` parser hasn’t been loaded. Correct usage:
```
<script type="module">
import prettier from "https://unpkg.com/[email protected]/esm/standalone.mjs";
import parserBabel from "https://unpkg.com/[email protected]/esm/parser-babel.mjs";
import parserHtml from "https://unpkg.com/[email protected]/esm/parser-html.mjs";
console.log(
prettier.format("const html=/\* HTML \*/ `<DIV> </DIV>`", {
parser: "babel",
plugins: [parserBabel, parserHtml],
})
);
// Output: const html = /\* HTML \*/ `<div></div>`;
</script>
```
prettier Watching For Changes Watching For Changes
====================
You can have Prettier watch for changes from the command line by using [onchange](https://www.npmjs.com/package/onchange). For example:
```
npx onchange "\*\*/\*" -- npx prettier --write --ignore-unknown {{changed}}
```
Or add the following to your `package.json`:
```
{
"scripts": {
"prettier-watch": "onchange \"\*\*/\*\" -- prettier --write --ignore-unknown {{changed}}"
}
}
```
prettier What is Prettier? What is Prettier?
=================
Prettier is an opinionated code formatter with support for:
* JavaScript (including experimental features)
* [JSX](https://facebook.github.io/jsx/)
* [Angular](https://angular.io/)
* [Vue](https://vuejs.org/)
* [Flow](https://flow.org/)
* [TypeScript](https://www.typescriptlang.org/)
* CSS, [Less](http://lesscss.org/), and [SCSS](https://sass-lang.com)
* [HTML](https://en.wikipedia.org/wiki/HTML)
* [Ember/Handlebars](https://handlebarsjs.com/)
* [JSON](https://json.org/)
* [GraphQL](https://graphql.org/)
* [Markdown](https://commonmark.org/), including [GFM](https://github.github.com/gfm/) and [MDX](https://mdxjs.com/)
* [YAML](https://yaml.org/)
It removes all original styling[\*](#footnotes) and ensures that all outputted code conforms to a consistent style. (See this [blog post](https://jlongster.com/A-Prettier-Formatter))
Prettier takes your code and reprints it from scratch by taking the line length into account.
For example, take the following code:
```
foo(arg1, arg2, arg3, arg4);
```
It fits in a single line so it’s going to stay as is. However, we've all run into this situation:
```
foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());
```
Suddenly our previous format for calling function breaks down because this is too long. Prettier is going to do the painstaking work of reprinting it like that for you:
```
foo(
reallyLongArg(),
omgSoManyParameters(),
IShouldRefactorThis(),
isThereSeriouslyAnotherOne()
);
```
Prettier enforces a consistent code **style** (i.e. code formatting that won’t affect the AST) across your entire codebase because it disregards the original styling[\*](#footnotes) by parsing it away and re-printing the parsed AST with its own rules that take the maximum line length into account, wrapping code when necessary.
If you want to learn more, these two conference talks are great introductions:
####
Footnotes
\* *Well actually, some original styling is preserved when practical—see [empty lines](rationale#empty-lines) and [multi-line objects](rationale#multi-line-objects).*
prettier Editor Integration Editor Integration
==================
To get the most out of Prettier, it’s recommended to run it from your editor.
If your editor does not support Prettier, you can instead [run Prettier with a file watcher](watching-files).
**Note!** It’s important to <install> Prettier locally in every project, so each project gets the correct Prettier version.
Visual Studio Code
-------------------
`prettier-vscode` can be installed using the extension sidebar – it’s called “Prettier - Code formatter.” [Check its repository for configuration and shortcuts](https://github.com/prettier/prettier-vscode).
If you’d like to toggle the formatter on and off, install [`vscode-status-bar-format-toggle`](https://marketplace.visualstudio.com/items?itemName=tombonnike.vscode-status-bar-format-toggle).
Emacs
------
Check out the [prettier-emacs](https://github.com/prettier/prettier-emacs) repo, or [prettier.el](https://github.com/jscheid/prettier.el). The package [Apheleia](https://github.com/raxod502/apheleia) supports multiple code formatters, including Prettier.
Vim
----
[vim-prettier](https://github.com/prettier/vim-prettier) is a Prettier-specific Vim plugin. [Neoformat](https://github.com/sbdchd/neoformat), [ALE](https://github.com/w0rp/ale), and [coc-prettier](https://github.com/neoclide/coc-prettier) are multi-language Vim linter/formatter plugins that support Prettier.
For more details see [the Vim setup guide](vim).
Sublime Text
-------------
Sublime Text support is available through Package Control and the [JsPrettier](https://packagecontrol.io/packages/JsPrettier) plug-in.
JetBrains WebStorm, PHPStorm, PyCharm...
-----------------------------------------
See the [WebStorm setup guide](webstorm).
Visual Studio
--------------
Install the [JavaScript Prettier extension](https://github.com/madskristensen/JavaScriptPrettier).
Atom
-----
Atom users can install the [prettier-atom](https://github.com/prettier/prettier-atom) package, or one of the more minimalistic [mprettier](https://github.com/t9md/atom-mprettier) and [miniprettier](https://github.com/duailibe/atom-miniprettier) packages.
Espresso
---------
Espresso users can install the [espresso-prettier](https://github.com/eablokker/espresso-prettier) plugin.
prettier Related Projects Related Projects
================
ESLint Integrations
--------------------
* [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) turns off all ESLint rules that are unnecessary or might conflict with Prettier
* [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier) runs Prettier as an ESLint rule and reports differences as individual ESLint issues
* [prettier-eslint](https://github.com/prettier/prettier-eslint) passes `prettier` output to `eslint --fix`
* [prettier-standard](https://github.com/sheerun/prettier-standard) uses `prettierx` and `prettier-eslint` to format code with `standard` rules
stylelint Integrations
-----------------------
* [stylelint-config-prettier](https://github.com/prettier/stylelint-config-prettier) turns off all rules that are unnecessary or might conflict with Prettier.
* [stylelint-prettier](https://github.com/prettier/stylelint-prettier) runs Prettier as a stylelint rule and reports differences as individual stylelint issues
* [prettier-stylelint](https://github.com/hugomrdias/prettier-stylelint) passes `prettier` output to `stylelint --fix`
Forks
------
* [prettierx](https://github.com/brodybits/prettierx) less opinionated fork of Prettier
Misc
-----
* [parallel-prettier](https://github.com/microsoft/parallel-prettier) is an alternative CLI that formats files in parallel to speed up large projects
* [prettier\_d](https://github.com/josephfrazier/prettier_d.js) runs Prettier as a server to avoid Node.js startup delay
* [pretty-quick](https://github.com/azz/pretty-quick) formats changed files with Prettier
* [rollup-plugin-prettier](https://github.com/mjeanroy/rollup-plugin-prettier) allows you to use Prettier with Rollup
* [jest-runner-prettier](https://github.com/keplersj/jest-runner-prettier) is Prettier as a Jest runner
* [prettier-chrome](https://github.com/u3u/prettier-chrome) is an extension that runs Prettier in the browser
* [spotless](https://github.com/diffplug/spotless) lets you run prettier from [gradle](https://github.com/diffplug/spotless/tree/main/plugin-gradle#prettier) or [maven](https://github.com/diffplug/spotless/tree/main/plugin-maven#prettier).
* [csharpier](https://github.com/belav/csharpier) is a port of Prettier for C#
| programming_docs |
prettier Ignoring Code Ignoring Code
=============
Use `.prettierignore` to ignore (i.e. not reformat) certain files and folders completely.
Use “prettier-ignore” comments to ignore parts of files.
Ignoring Files: .prettierignore
--------------------------------
To exclude files from formatting, create a `.prettierignore` file in the root of your project. `.prettierignore` uses [gitignore syntax](https://git-scm.com/docs/gitignore#_pattern_format).
Example:
```
# Ignore artifacts:
build
coverage
# Ignore all HTML files:
\*.html
```
It’s recommended to have a `.prettierignore` in your project! This way you can run `prettier --write .` to make sure that everything is formatted (without mangling files you don’t want, or choking on generated files). And – your editor will know which files *not* to format!
By default prettier ignores files in version control systems directories (".git", ".svn" and ".hg") and `node_modules` (if [`--with-node-modules` CLI option](cli#--with-node-modules) not specified)
So by default it will be
```
\*\*/.git
\*\*/.svn
\*\*/.hg
\*\*/node_modules
```
and
```
\*\*/.git
\*\*/.svn
\*\*/.hg
```
if [`--with-node-modules` CLI option](cli#--with-node-modules) provided
(See also the [`--ignore-path` CLI option](cli#--ignore-path).)
JavaScript
-----------
A JavaScript comment of `// prettier-ignore` will exclude the next node in the abstract syntax tree from formatting.
For example:
```
matrix(
1, 0, 0,
0, 1, 0,
0, 0, 1
)
// prettier-ignore
matrix(
1, 0, 0,
0, 1, 0,
0, 0, 1
)
```
will be transformed to:
```
matrix(1, 0, 0, 0, 1, 0, 0, 0, 1);
// prettier-ignore
matrix(
1, 0, 0,
0, 1, 0,
0, 0, 1
)
```
JSX
----
```
<div>{/\* prettier-ignore \*/}<span ugly format='' /></div>
```
HTML
-----
```
<!-- prettier-ignore -->
<div class="x" >hello world</div >
<!-- prettier-ignore-attribute -->
<div
(mousedown)=" onStart ( ) "
(mouseup)=" onEnd ( ) "
></div>
<!-- prettier-ignore-attribute (mouseup) -->
<div
(mousedown)="onStart()"
(mouseup)=" onEnd ( ) "
></div>
```
CSS
----
```
/\* prettier-ignore \*/
.my ugly rule
{
}
```
Markdown
---------
```
<!-- prettier-ignore -->
Do not format this
```
###
Range Ignore
*available in v1.12.0+*
This type of ignore is only allowed to be used in top-level and aimed to disable formatting for auto-generated content, e.g. [`all-contributors`](https://github.com/kentcdodds/all-contributors), [`markdown-toc`](https://github.com/jonschlinkert/markdown-toc), etc.
```
<!-- prettier-ignore-start -->
<!-- SOMETHING AUTO-GENERATED BY TOOLS - START -->
| MY | AWESOME | AUTO-GENERATED | TABLE |
|-|-|-|-|
| a | b | c | d |
<!-- SOMETHING AUTO-GENERATED BY TOOLS - END -->
<!-- prettier-ignore-end -->
```
YAML
-----
To ignore a part of a YAML file, `# prettier-ignore` should be placed on the line immediately above the ignored node:
```
# prettier-ignore
key : value
hello: world
```
GraphQL
--------
```
{
# prettier-ignore
addReaction(input:{superLongInputFieldName:"MDU6SXNzdWUyMzEzOTE1NTE=",content:HOORAY}) {
reaction {content}
}
}
```
Handlebars
-----------
```
{{! prettier-ignore }}
<div>
"hello! my parent was ignored"
{{#my-crazy-component "shall" be="preserved"}}
<This
is = "also preserved as is"
/>
{{/my-crazy-component}}
</div>
```
Command Line File Patterns
---------------------------
For one-off commands, when you want to exclude some files without adding them to `.prettierignore`, negative patterns can come in handy:
```
prettier --write . '!\*\*/\*.{js,jsx,vue}'
```
See [fast-glob](cli#file-patterns) to learn more about advanced glob syntax.
prettier Configuration File Configuration File
==================
Prettier uses [cosmiconfig](https://github.com/davidtheclark/cosmiconfig) for configuration file support. This means you can configure Prettier via (in order of precedence):
* A `"prettier"` key in your `package.json` file.
* A `.prettierrc` file written in JSON or YAML.
* A `.prettierrc.json`, `.prettierrc.yml`, `.prettierrc.yaml`, or `.prettierrc.json5` file.
* A `.prettierrc.js`, `.prettierrc.cjs`, `prettier.config.js`, or `prettier.config.cjs` file that exports an object using `module.exports`.
* A `.prettierrc.toml` file.
The configuration file will be resolved starting from the location of the file being formatted, and searching up the file tree until a config file is (or isn’t) found.
Prettier intentionally doesn’t support any kind of global configuration. This is to make sure that when a project is copied to another computer, Prettier’s behavior stays the same. Otherwise, Prettier wouldn’t be able to guarantee that everybody in a team gets the same consistent results.
The options you can use in the configuration file are the same as the [API options](options).
Basic Configuration
--------------------
JSON:
```
{
"trailingComma": "es5",
"tabWidth": 4,
"semi": false,
"singleQuote": true
}
```
JS:
```
// prettier.config.js or .prettierrc.js
module.exports = {
trailingComma: "es5",
tabWidth: 4,
semi: false,
singleQuote: true,
};
```
YAML:
```
# .prettierrc or .prettierrc.yaml
trailingComma: "es5"
tabWidth: 4
semi: false
singleQuote: true
```
TOML:
```
# .prettierrc.toml
trailingComma = "es5"
tabWidth = 4
semi = false
singleQuote = true
```
Configuration Overrides
------------------------
Overrides let you have different configuration for certain file extensions, folders and specific files.
Prettier borrows ESLint’s [override format](https://eslint.org/docs/latest/user-guide/configuring/configuration-files#how-do-overrides-work).
JSON:
```
{
"semi": false,
"overrides": [
{
"files": "\*.test.js",
"options": {
"semi": true
}
},
{
"files": ["\*.html", "legacy/\*\*/\*.js"],
"options": {
"tabWidth": 4
}
}
]
}
```
YAML:
```
semi: false
overrides:
- files: "\*.test.js"
options:
semi: true
- files:
- "\*.html"
- "legacy/\*\*/\*.js"
options:
tabWidth: 4
```
`files` is required for each override, and may be a string or array of strings. `excludeFiles` may be optionally provided to exclude files for a given rule, and may also be a string or array of strings.
Sharing configurations
-----------------------
Sharing a Prettier configuration is simple: just publish a module that exports a configuration object, say `@company/prettier-config`, and reference it in your `package.json`:
```
{
"name": "my-cool-library",
"version": "9000.0.1",
"prettier": "@company/prettier-config"
}
```
If you don’t want to use `package.json`, you can use any of the supported extensions to export a string, e.g. `.prettierrc.json`:
```
"@company/prettier-config"
```
An example configuration repository is available [here](https://github.com/azz/prettier-config).
> Note: This method does **not** offer a way to *extend* the configuration to overwrite some properties from the shared configuration. If you need to do that, import the file in a `.prettierrc.js` file and export the modifications, e.g:
>
>
> ```
> module.exports = {
> ...require("@company/prettier-config"),
> semi: false,
> };
>
> ```
>
Setting the [parser](options#parser) option
--------------------------------------------
By default, Prettier automatically infers which parser to use based on the input file extension. Combined with `overrides` you can teach Prettier how to parse files it does not recognize.
For example, to get Prettier to format its own `.prettierrc` file, you can do:
```
{
"overrides": [
{
"files": ".prettierrc",
"options": { "parser": "json" }
}
]
}
```
You can also switch to the `flow` parser instead of the default `babel` for .js files:
```
{
"overrides": [
{
"files": "\*.js",
"options": {
"parser": "flow"
}
}
]
}
```
**Note:** *Never* put the `parser` option at the top level of your configuration. *Only* use it inside `overrides`. Otherwise you effectively disable Prettier’s automatic file extension based parser inference. This forces Prettier to use the parser you specified for *all* types of files – even when it doesn’t make sense, such as trying to parse a CSS file as JavaScript.
Configuration Schema
---------------------
If you’d like a JSON schema to validate your configuration, one is available here: <http://json.schemastore.org/prettierrc>.
EditorConfig
-------------
If `options.editorconfig` is `true` and an [`.editorconfig` file](https://editorconfig.org/) is in your project, Prettier will parse it and convert its properties to the corresponding Prettier configuration. This configuration will be overridden by `.prettierrc`, etc.
Here’s an annotated description of how different properties map to Prettier’s behavior:
```
# Stop the editor from looking for .editorconfig files in the parent directories
# root = true
[\*]
# Non-configurable Prettier behaviors
charset = utf-8
insert\_final\_newline = true
# Caveat: Prettier won’t trim trailing whitespace inside template strings, but your editor might.
# trim\_trailing\_whitespace = true
# Configurable Prettier behaviors
# (change these if your Prettier config differs)
end\_of\_line = lf
indent\_style = space
indent\_size = 2
max\_line\_length = 80
```
Here’s a copy+paste-ready `.editorconfig` file if you use the default options:
```
[\*]
charset = utf-8
insert\_final\_newline = true
end\_of\_line = lf
indent\_style = space
indent\_size = 2
max\_line\_length = 80
```
prettier Prettier vs. Linters Prettier vs. Linters
====================
How does it compare to ESLint/TSLint/stylelint, etc.?
------------------------------------------------------
Linters have two categories of rules:
**Formatting rules**: eg: [max-len](https://eslint.org/docs/rules/max-len), [no-mixed-spaces-and-tabs](https://eslint.org/docs/rules/no-mixed-spaces-and-tabs), [keyword-spacing](https://eslint.org/docs/rules/keyword-spacing), [comma-style](https://eslint.org/docs/rules/comma-style)…
Prettier alleviates the need for this whole category of rules! Prettier is going to reprint the entire program from scratch in a consistent way, so it’s not possible for the programmer to make a mistake there anymore :)
**Code-quality rules**: eg [no-unused-vars](https://eslint.org/docs/rules/no-unused-vars), [no-extra-bind](https://eslint.org/docs/rules/no-extra-bind), [no-implicit-globals](https://eslint.org/docs/rules/no-implicit-globals), [prefer-promise-reject-errors](https://eslint.org/docs/rules/prefer-promise-reject-errors)…
Prettier does nothing to help with those kind of rules. They are also the most important ones provided by linters as they are likely to catch real bugs with your code!
In other words, use **Prettier for formatting** and **linters for catching bugs!**
prettier CLI CLI
===
Use the `prettier` command to run Prettier from the command line.
```
prettier [options] [file/dir/glob ...]
```
> To run your locally installed version of Prettier, prefix the command with `npx` or `yarn` (if you use Yarn), i.e. `npx prettier --help`, or `yarn prettier --help`.
>
>
To format a file in-place, use `--write`. (Note: This overwrites your files!)
In practice, this may look something like:
```
prettier --write .
```
This command formats all files supported by Prettier in the current directory and its subdirectories.
It’s recommended to always make sure that `prettier --write .` only formats what you want in your project. Use a [`.prettierignore`](ignore) file to ignore things that should not be formatted.
A more complicated example:
```
prettier --single-quote --trailing-comma all --write docs package.json "{app,\_\_{tests,mocks}\_\_}/\*\*/\*.js"
```
> Don’t forget the **quotes** around the globs! The quotes make sure that Prettier CLI expands the globs rather than your shell, which is important for cross-platform usage.
>
>
> It’s better to use a [configuration file](configuration) for formatting options like `--single-quote` and `--trailing-comma` instead of passing them as CLI flags. This way the Prettier CLI, [editor integrations](editors), and other tooling can all know what options you use.
>
>
File patterns
--------------
Given a list of paths/patterns, the Prettier CLI first treats every entry in it as a literal path.
* If the path points to an existing file, Prettier CLI proceeds with that file and doesn’t resolve the path as a glob pattern.
* If the path points to an existing directory, Prettier CLI recursively finds supported files in that directory. This resolution process is based on file extensions and well-known file names that Prettier and its <plugins> associate with supported languages.
* Otherwise, the entry is resolved as a glob pattern using the [glob syntax from the `fast-glob` module](https://github.com/mrmlnc/fast-glob#pattern-syntax).
Prettier CLI will ignore files located in `node_modules` directory. To opt out from this behavior, use `--with-node-modules` flag.
To escape special characters in globs, one of the two escaping syntaxes can be used: `prettier "\[my-dir]/*.js"` or `prettier "[[]my-dir]/*.js"`. Both match all JS files in a directory named `[my-dir]`, however the latter syntax is preferable as the former doesn’t work on Windows, where backslashes are treated as path separators.
`--check`
----------
When you want to check if your files are formatted, you can run Prettier with the `--check` flag (or `-c`). This will output a human-friendly message and a list of unformatted files, if any.
```
prettier --check "src/\*\*/\*.js"
```
Console output if all files are formatted:
```
Checking formatting...
All matched files use Prettier code style!
```
Console output if some of the files require re-formatting:
```
Checking formatting...
[warn] src/fileA.js
[warn] src/fileB.js
[warn] Code style issues found in 2 files. Forgot to run Prettier?
```
The command will return exit code `1` in the second case, which is helpful inside the CI pipelines. Human-friendly status messages help project contributors react on possible problems. To minimise the number of times `prettier --check` finds unformatted files, you may be interested in configuring a [pre-commit hook](precommit) in your repo. Applying this practice will minimise the number of times the CI fails because of code formatting problems.
If you need to pipe the list of unformatted files to another command, you can use [`--list-different`](cli#--list-different) flag instead of `--check`.
###
Exit codes
| Code | Information |
| --- | --- |
| `0` | Everything formatted properly |
| `1` | Something wasn’t formatted properly |
| `2` | Something’s wrong with Prettier |
`--debug-check`
----------------
If you're worried that Prettier will change the correctness of your code, add `--debug-check` to the command. This will cause Prettier to print an error message if it detects that code correctness might have changed. Note that `--write` cannot be used with `--debug-check`.
`--find-config-path` and `--config`
------------------------------------
If you are repeatedly formatting individual files with `prettier`, you will incur a small performance cost when Prettier attempts to look up a [configuration file](configuration). In order to skip this, you may ask Prettier to find the config file once, and re-use it later on.
```
prettier --find-config-path ./my/file.js
./my/.prettierrc
```
This will provide you with a path to the configuration file, which you can pass to `--config`:
```
prettier --config ./my/.prettierrc --write ./my/file.js
```
You can also use `--config` if your configuration file lives somewhere where Prettier cannot find it, such as a `config/` directory.
If you don’t have a configuration file, or want to ignore it if it does exist, you can pass `--no-config` instead.
`--ignore-path`
----------------
Path to a file containing patterns that describe files to ignore. By default, Prettier looks for `./.prettierignore`.
`--list-different`
-------------------
Another useful flag is `--list-different` (or `-l`) which prints the filenames of files that are different from Prettier formatting. If there are differences the script errors out, which is useful in a CI scenario.
```
prettier --single-quote --list-different "src/\*\*/\*.js"
```
You can also use [`--check`](cli#--check) flag, which works the same way as `--list-different`, but also prints a human-friendly summary message to stdout.
`--no-config`
--------------
Do not look for a configuration file. The default settings will be used.
`--config-precedence`
----------------------
Defines how config file should be evaluated in combination of CLI options.
**cli-override (default)**
CLI options take precedence over config file
**file-override**
Config file take precedence over CLI options
**prefer-file**
If a config file is found will evaluate it and ignore other CLI options. If no config file is found, CLI options will evaluate as normal.
This option adds support to editor integrations where users define their default configuration but want to respect project specific configuration.
`--no-editorconfig`
--------------------
Don’t take `.editorconfig` into account when parsing configuration. See the [`prettier.resolveConfig` docs](api) for details.
`--with-node-modules`
----------------------
Prettier CLI will ignore files located in `node_modules` directory. To opt out from this behavior, use `--with-node-modules` flag.
`--write`
----------
This rewrites all processed files in place. This is comparable to the `eslint --fix` workflow. You can also use `-w` alias.
`--loglevel`
-------------
Change the level of logging for the CLI. Valid options are:
* `error`
* `warn`
* `log` (default)
* `debug`
* `silent`
`--stdin-filepath`
-------------------
A path to the file that the Prettier CLI will treat like stdin. For example:
*abc.css*
```
.name {
display: none;
}
```
*shell*
```
$ cat abc.css | prettier --stdin-filepath abc.css
.name {
display: none;
}
```
`--ignore-unknown`
-------------------
With `--ignore-unknown` (or `-u`), prettier will ignore unknown files matched by patterns.
```
$ prettier "\*\*/\*" --write --ignore-unknown
```
`--no-error-on-unmatched-pattern`
----------------------------------
Prevent errors when pattern is unmatched.
`--no-plugin-search`
---------------------
Disable plugin autoloading.
`--cache`
----------
If this option is enabled, the following values are used as cache keys and the file is formatted only if one of them is changed.
* Prettier version
* Options
* Node.js version
* (if `--cache-strategy` is `metadata`) file metadata, such as timestamps
* (if `--cache-strategy` is `content`) content of the file
```
prettier --write --cache src
```
Running Prettier without `--cache` will delete the cache.
Also, since the cache file is stored in `./node_modules/.cache/prettier/.prettier-cache`, so you can use `rm ./node_modules/.cache/prettier/.prettier-cache` to remove it manually.
> Plugins version and implementation are not used as cache keys. We recommend that you delete the cache when updating plugins.
>
>
`--cache-location`
-------------------
Path to the cache file location used by `--cache` flag. If you don't explicit `--cache-location`, Prettier saves cache file at `./node_modules/.cache/prettier/.prettier-cache`.
If a file path is passed, that file is used as the cache file.
```
prettier --write --cache --cache-location=my_cache_file src
```
`--cache-strategy`
-------------------
Strategy for the cache to use for detecting changed files. Can be either `metadata` or `content`.
In general, `metadata` is faster. However, `content` is useful for updating the timestamp without changing the file content. This can happen, for example, during git operations such as `git clone`, because it does not track file modification times.
If no strategy is specified, `content` will be used.
```
prettier --write --cache --cache-strategy metadata src
```
| programming_docs |
prettier Technical Details Technical Details
=================
This printer is a fork of [recast](https://github.com/benjamn/recast)’s printer with its algorithm replaced by the one described by Wadler in "[A prettier printer](https://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf)". There still may be leftover code from recast that needs to be cleaned up.
The basic idea is that the printer takes an AST and returns an intermediate representation of the output, and the printer uses that to generate a string. The advantage is that the printer can "measure" the IR and see if the output is going to fit on a line, and break if not.
This means that most of the logic of printing an AST involves generating an abstract representation of the output involving certain commands. For example, `["(", line, arg, line, ")"]` would represent a concatenation of opening parens, an argument, and closing parens. But if that doesn’t fit on one line, the printer can break where `line` is specified.
The [Playground](https://prettier.io/playground) has a special mode for exploring how Prettier’s intermediate representation is printed. To get there, open the sidebar (the "Show options" button) and set the `parser` option to the special value `doc-explorer`.
More (rough) details can be found in [commands.md](https://github.com/prettier/prettier/blob/main/commands.md).
prettier Pre-commit Hook Pre-commit Hook
===============
You can use Prettier with a pre-commit tool. This can re-format your files that are marked as “staged” via `git add` before you commit.
Option 1. [lint-staged](https://github.com/okonet/lint-staged)
---------------------------------------------------------------
**Use Case:** Useful for when you want to use other code quality tools along with Prettier (e.g. ESLint, Stylelint, etc.) or if you need support for partially staged files (`git add --patch`).
*Make sure Prettier is installed and is in your [`devDependencies`](https://docs.npmjs.com/specifying-dependencies-and-devdependencies-in-a-package-json-file) before you proceed.*
```
npx mrm@2 lint-staged
```
This will install [husky](https://github.com/typicode/husky) and [lint-staged](https://github.com/okonet/lint-staged), then add a configuration to the project’s `package.json` that will automatically format supported files in a pre-commit hook.
Read more at the [lint-staged](https://github.com/okonet/lint-staged#configuration) repo.
Option 2. [pretty-quick](https://github.com/azz/pretty-quick)
--------------------------------------------------------------
**Use Case:** Great for when you want an entire file formatting on your changed/staged files.
Install it along with [husky](https://github.com/typicode/husky):
npm
yarn
```
npx husky-init
npm install --save-dev pretty-quick
npx husky set .husky/pre-commit "npx pretty-quick --staged"
```
```
npx husky-init # add --yarn2 for Yarn 2
yarn add --dev pretty-quick
yarn husky set .husky/pre-commit "npx pretty-quick --staged"
```
Read more at the [pretty-quick](https://github.com/azz/pretty-quick) repo.
Option 3. [pre-commit](https://github.com/pre-commit/pre-commit)
-----------------------------------------------------------------
**Use Case:** Great when working with multi-language projects.
Copy the following config into your `.pre-commit-config.yaml` file:
```
- repo: https://github.com/pre-commit/mirrors-prettier
rev: "" # Use the sha or tag you want to point at
hooks:
- id: prettier
```
Read more at [mirror of prettier package for pre-commit](https://github.com/pre-commit/mirrors-prettier) and the [pre-commit](https://pre-commit.com) website.
Option 4. [Husky.Net](https://github.com/alirezanet/Husky.Net)
---------------------------------------------------------------
**Use Case:** A dotnet solution to use Prettier along with other code quality tools (e.g. dotnet-format, ESLint, Stylelint, etc.). It supports multiple file states (staged - last-commit, git-files etc.)
```
dotnet tool install husky
dotnet husky install
dotnet husky add .husky/pre-commit
```
after installation you can add prettier task to the `task-runner.json`.
```
{
"command": "npx",
"args": ["prettier", "--ignore-unknown", "--write", "${staged}"],
"pathMode": "absolute"
}
```
Option 5. [git-format-staged](https://github.com/hallettj/git-format-staged)
-----------------------------------------------------------------------------
**Use Case:** Great for when you want to format partially-staged files, and other options do not provide a good fit for your project.
Git-format-staged is used to run any formatter that can accept file content via stdin. It operates differently than other tools that format partially-staged files: it applies the formatter directly to objects in the git object database, and merges changes back to the working tree. This procedure provides several guarantees:
1. Changes in commits are always formatted.
2. Unstaged changes are never, under any circumstances staged during the formatting process.
3. If there are conflicts between formatted, staged changes and unstaged changes then your working tree files are left untouched - your work won’t be overwritten, and there are no stashes to clean up.
4. Unstaged changes are not formatted.
Git-format-staged requires Python v3 or v2.7. Python is usually pre-installed on Linux and macOS, but not on Windows. Use git-format-staged with [husky](https://github.com/typicode/husky):
npm
yarn
```
npx husky-init
npm install --save-dev git-format-staged
npx husky set .husky/pre-commit "git-format-staged -f 'prettier --ignore-unknown --stdin --stdin-filepath \"{}\"' ."
```
```
npx husky-init # add --yarn2 for Yarn 2
yarn add --dev git-format-staged
yarn husky set .husky/pre-commit "git-format-staged -f 'prettier --ignore-unknown --stdin --stdin-filepath \"{}\"' ."
```
Add or remove file extensions to suit your project. Note that regardless of which extensions you list formatting will respect any `.prettierignore` files in your project.
To read about how git-format-staged works see [Automatic Code Formatting for Partially-Staged Files](https://www.olioapps.com/blog/automatic-code-formatting/).
Option 6. Shell script
-----------------------
Alternately you can save this script as `.git/hooks/pre-commit` and give it execute permission:
```
#!/bin/sh
FILES=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g')
[ -z "$FILES" ] && exit 0
# Prettify all selected files
echo "$FILES" | xargs ./node_modules/.bin/prettier --ignore-unknown --write
# Add back the modified/prettified files to staging
echo "$FILES" | xargs git add
exit 0
```
If git is reporting that your prettified files are still modified after committing, you may need to add a [post-commit script to update git’s index](https://github.com/prettier/prettier/issues/2978#issuecomment-334408427).
Add something like the following to `.git/hooks/post-commit`:
```
#!/bin/sh
git update-index -g
```
prettier Options Options
=======
Prettier ships with a handful of format options.
**To learn more about Prettier’s stance on options – see the [Option Philosophy](option-philosophy).**
If you change any options, it’s recommended to do it via a [configuration file](configuration). This way the Prettier CLI, [editor integrations](editors) and other tooling knows what options you use.
Print Width
------------
Specify the line length that the printer will wrap on.
> **For readability we recommend against using more than 80 characters:**
>
> In code styleguides, maximum line length rules are often set to 100 or 120. However, when humans write code, they don’t strive to reach the maximum number of columns on every line. Developers often use whitespace to break up long lines for readability. In practice, the average line length often ends up well below the maximum.
>
> Prettier’s printWidth option does not work the same way. It is not the hard upper allowed line length limit. It is a way to say to Prettier roughly how long you’d like lines to be. Prettier will make both shorter and longer lines, but generally strive to meet the specified printWidth.
>
> Remember, computers are dumb. You need to explicitly tell them what to do, while humans can make their own (implicit) judgements, for example on when to break a line.
>
> In other words, don’t try to use printWidth as if it was ESLint’s [max-len](https://eslint.org/docs/rules/max-len) – they’re not the same. max-len just says what the maximum allowed line length is, but not what the generally preferred length is – which is what printWidth specifies.
>
>
| Default | CLI Override | API Override |
| --- | --- | --- |
| `80` | `--print-width <int>` | `printWidth: <int>` |
Setting `max_line_length` in an [`.editorconfig` file](https://editorconfig.org/) will configure Prettier’s print width, unless overridden.
(If you don’t want line wrapping when formatting Markdown, you can set the [Prose Wrap](#prose-wrap) option to disable it.)
Tab Width
----------
Specify the number of spaces per indentation-level.
| Default | CLI Override | API Override |
| --- | --- | --- |
| `2` | `--tab-width <int>` | `tabWidth: <int>` |
Setting `indent_size` or `tab_width` in an [`.editorconfig` file](https://editorconfig.org/) will configure Prettier’s tab width, unless overridden.
Tabs
-----
Indent lines with tabs instead of spaces.
| Default | CLI Override | API Override |
| --- | --- | --- |
| `false` | `--use-tabs` | `useTabs: <bool>` |
Setting `indent_style` in an [`.editorconfig` file](https://editorconfig.org/) will configure Prettier’s tab usage, unless overridden.
(Tabs will be used for *indentation* but Prettier uses spaces to *align* things, such as in ternaries.)
Semicolons
-----------
Print semicolons at the ends of statements.
Valid options:
* `true` - Add a semicolon at the end of every statement.
* `false` - Only add semicolons at the beginning of lines that [may introduce ASI failures](rationale#semicolons).
| Default | CLI Override | API Override |
| --- | --- | --- |
| `true` | `--no-semi` | `semi: <bool>` |
Quotes
-------
Use single quotes instead of double quotes.
Notes:
* JSX quotes ignore this option – see [jsx-single-quote](#jsx-quotes).
* If the number of quotes outweighs the other quote, the quote which is less used will be used to format the string - Example: `"I'm double quoted"` results in `"I'm double quoted"` and `"This \"example\" is single quoted"` results in `'This "example" is single quoted'`.
See the [strings rationale](rationale#strings) for more information.
| Default | CLI Override | API Override |
| --- | --- | --- |
| `false` | `--single-quote` | `singleQuote: <bool>` |
Quote Props
------------
Change when properties in objects are quoted.
Valid options:
* `"as-needed"` - Only add quotes around object properties where required.
* `"consistent"` - If at least one property in an object requires quotes, quote all properties.
* `"preserve"` - Respect the input use of quotes in object properties.
| Default | CLI Override | API Override |
| --- | --- | --- |
| `"as-needed"` | `--quote-props <as-needed|consistent|preserve>` | `quoteProps: "<as-needed|consistent|preserve>"` |
Note that Prettier never unquotes numeric property names in Angular expressions, TypeScript, and Flow because the distinction between string and numeric keys is significant in these languages. See: [Angular](https://codesandbox.io/s/hungry-morse-foj87?file=/src/app/app.component.html), [TypeScript](https://www.typescriptlang.org/play?#code/DYUwLgBAhhC8EG8IEYBcKA0EBM7sQF8AoUSAIzkQgHJlr1ktrt6dCiiATEAY2CgBOICKWhR0AaxABPAPYAzCGGkAHEAugBuLr35CR4CGTKSZG5Wo1ltRKDHjHtQA), [Flow](https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVBjOA7AzgFzAA8wBeMAb1TDAAYAuMARlQF8g). Also Prettier doesn’t unquote numeric properties for Vue (see the [issue](https://github.com/prettier/prettier/issues/10127) about that).
If this option is set to `preserve`, `singleQuote` to `false` (default value), and `parser` to `json5`, double quotes are always used for strings. This effectively allows using the `json5` parser for “JSON with comments and trailing commas”.
JSX Quotes
-----------
Use single quotes instead of double quotes in JSX.
| Default | CLI Override | API Override |
| --- | --- | --- |
| `false` | `--jsx-single-quote` | `jsxSingleQuote: <bool>` |
Trailing Commas
----------------
*Default value changed from `none` to `es5` in v2.0.0*
Print trailing commas wherever possible in multi-line comma-separated syntactic structures. (A single-line array, for example, never gets trailing commas.)
Valid options:
* `"es5"` - Trailing commas where valid in ES5 (objects, arrays, etc.). No trailing commas in type parameters in TypeScript.
* `"none"` - No trailing commas.
* `"all"` - Trailing commas wherever possible (including [function parameters and calls](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Trailing_commas#Trailing_commas_in_functions)). To run, JavaScript code formatted this way needs an engine that supports ES2017 (Node.js 8+ or a modern browser) or [downlevel compilation](https://babeljs.io/docs/en/index). This also enables trailing commas in type parameters in TypeScript (supported since TypeScript 2.7 released in January 2018).
| Default | CLI Override | API Override |
| --- | --- | --- |
| `"es5"` | `--trailing-comma <es5|none|all>` | `trailingComma: "<es5|none|all>"` |
Bracket Spacing
----------------
Print spaces between brackets in object literals.
Valid options:
* `true` - Example: `{ foo: bar }`.
* `false` - Example: `{foo: bar}`.
| Default | CLI Override | API Override |
| --- | --- | --- |
| `true` | `--no-bracket-spacing` | `bracketSpacing: <bool>` |
Bracket Line
-------------
Put the `>` of a multi-line HTML (HTML, JSX, Vue, Angular) element at the end of the last line instead of being alone on the next line (does not apply to self closing elements).
Valid options:
* `true` - Example:
```
<button
className="prettier-class"
id="prettier-id"
onClick={this.handleClick}>
Click Here
</button>
```
* `false` - Example:
```
<button
className="prettier-class"
id="prettier-id"
onClick={this.handleClick}
>
Click Here
</button>
```
| Default | CLI Override | API Override |
| --- | --- | --- |
| `false` | `--bracket-same-line` | `bracketSameLine: <bool>` |
[Deprecated] JSX Brackets
--------------------------
*This option has been deprecated in v2.4.0, use --bracket-same-line instead*
Put the `>` of a multi-line JSX element at the end of the last line instead of being alone on the next line (does not apply to self closing elements).
Valid options:
* `true` - Example:
```
<button
className="prettier-class"
id="prettier-id"
onClick={this.handleClick}>
Click Here
</button>
```
* `false` - Example:
```
<button
className="prettier-class"
id="prettier-id"
onClick={this.handleClick}
>
Click Here
</button>
```
| Default | CLI Override | API Override |
| --- | --- | --- |
| `false` | `--jsx-bracket-same-line` | `jsxBracketSameLine: <bool>` |
Arrow Function Parentheses
---------------------------
*First available in v1.9.0, default value changed from `avoid` to `always` in v2.0.0*
Include parentheses around a sole arrow function parameter.
Valid options:
* `"always"` - Always include parens. Example: `(x) => x`
* `"avoid"` - Omit parens when possible. Example: `x => x`
| Default | CLI Override | API Override |
| --- | --- | --- |
| `"always"` | `--arrow-parens <always|avoid>` | `arrowParens: "<always|avoid>"` |
At first glance, avoiding parentheses may look like a better choice because of less visual noise. However, when Prettier removes parentheses, it becomes harder to add type annotations, extra arguments or default values as well as making other changes. Consistent use of parentheses provides a better developer experience when editing real codebases, which justifies the default value for the option.
Range
------
Format only a segment of a file.
These two options can be used to format code starting and ending at a given character offset (inclusive and exclusive, respectively). The range will extend:
* Backwards to the start of the first line containing the selected statement.
* Forwards to the end of the selected statement.
These options cannot be used with `cursorOffset`.
| Default | CLI Override | API Override |
| --- | --- | --- |
| `0` | `--range-start <int>` | `rangeStart: <int>` |
| `Infinity` | `--range-end <int>` | `rangeEnd: <int>` |
Parser
-------
Specify which parser to use.
Prettier automatically infers the parser from the input file path, so you shouldn’t have to change this setting.
Both the `babel` and `flow` parsers support the same set of JavaScript features (including Flow type annotations). They might differ in some edge cases, so if you run into one of those you can try `flow` instead of `babel`. Almost the same applies to `typescript` and `babel-ts`. `babel-ts` might support JavaScript features (proposals) not yet supported by TypeScript, but it’s less permissive when it comes to invalid code and less battle-tested than the `typescript` parser.
Valid options:
* `"babel"` (via [@babel/parser](https://github.com/babel/babel/tree/main/packages/babel-parser)) *Named `"babylon"` until v1.16.0*
* `"babel-flow"` (same as `"babel"` but enables Flow parsing explicitly to avoid ambiguity) *First available in v1.16.0*
* `"babel-ts"` (similar to `"typescript"` but uses Babel and its TypeScript plugin) *First available in v2.0.0*
* `"flow"` (via [flow-parser](https://github.com/facebook/flow/tree/master/src/parser))
* `"typescript"` (via [@typescript-eslint/typescript-estree](https://github.com/typescript-eslint/typescript-eslint)) *First available in v1.4.0*
* `"espree"` (via [espree](https://github.com/eslint/espree)) *First available in v2.2.0*
* `"meriyah"` (via [meriyah](https://github.com/meriyah/meriyah)) *First available in v2.2.0*
* `"acorn"` (via [acorn](https://github.com/acornjs/acorn)) *First available in v2.6.0*
* `"css"` (via [postcss-scss](https://github.com/postcss/postcss-scss) and [postcss-less](https://github.com/shellscape/postcss-less), autodetects which to use) *First available in v1.7.1*
* `"scss"` (same parsers as `"css"`, prefers postcss-scss) *First available in v1.7.1*
* `"less"` (same parsers as `"css"`, prefers postcss-less) *First available in v1.7.1*
* `"json"` (via [@babel/parser parseExpression](https://babeljs.io/docs/en/next/babel-parser.html#babelparserparseexpressioncode-options)) *First available in v1.5.0*
* `"json5"` (same parser as `"json"`, but outputs as [json5](https://json5.org/)) *First available in v1.13.0*
* `"json-stringify"` (same parser as `"json"`, but outputs like `JSON.stringify`) *First available in v1.13.0*
* `"graphql"` (via [graphql/language](https://github.com/graphql/graphql-js/tree/master/src/language)) *First available in v1.5.0*
* `"markdown"` (via [remark-parse](https://github.com/wooorm/remark/tree/main/packages/remark-parse)) *First available in v1.8.0*
* `"mdx"` (via [remark-parse](https://github.com/wooorm/remark/tree/main/packages/remark-parse) and [@mdx-js/mdx](https://github.com/mdx-js/mdx/tree/master/packages/mdx)) *First available in v1.15.0*
* `"html"` (via [angular-html-parser](https://github.com/ikatyang/angular-html-parser/tree/master/packages/angular-html-parser)) *First available in 1.15.0*
* `"vue"` (same parser as `"html"`, but also formats vue-specific syntax) *First available in 1.10.0*
* `"angular"` (same parser as `"html"`, but also formats angular-specific syntax via [angular-estree-parser](https://github.com/ikatyang/angular-estree-parser)) *First available in 1.15.0*
* `"lwc"` (same parser as `"html"`, but also formats LWC-specific syntax for unquoted template attributes) *First available in 1.17.0*
* `"yaml"` (via [yaml](https://github.com/eemeli/yaml) and [yaml-unist-parser](https://github.com/ikatyang/yaml-unist-parser)) *First available in 1.14.0*
[Custom parsers](api#custom-parser-api) are also supported. *First available in v1.5.0. Deprecated. Will be removed in v3.0.0 (superseded by the Plugin API)*
| Default | CLI Override | API Override |
| --- | --- | --- |
| None | `--parser <string>``--parser ./my-parser` | `parser: "<string>"``parser: require("./my-parser")` |
Note: the default value was `"babylon"` until v1.13.0.
File Path
----------
Specify the file name to use to infer which parser to use.
For example, the following will use the CSS parser:
```
cat foo | prettier --stdin-filepath foo.css
```
This option is only useful in the CLI and API. It doesn’t make sense to use it in a configuration file.
| Default | CLI Override | API Override |
| --- | --- | --- |
| None | `--stdin-filepath <string>` | `filepath: "<string>"` |
Require Pragma
---------------
*First available in v1.7.0*
Prettier can restrict itself to only format files that contain a special comment, called a pragma, at the top of the file. This is very useful when gradually transitioning large, unformatted codebases to Prettier.
A file with the following as its first comment will be formatted when `--require-pragma` is supplied:
```
/\*\*
\* @prettier
\*/
```
or
```
/\*\*
\* @format
\*/
```
| Default | CLI Override | API Override |
| --- | --- | --- |
| `false` | `--require-pragma` | `requirePragma: <bool>` |
Insert Pragma
--------------
*First available in v1.8.0*
Prettier can insert a special `@format` marker at the top of files specifying that the file has been formatted with Prettier. This works well when used in tandem with the `--require-pragma` option. If there is already a docblock at the top of the file then this option will add a newline to it with the `@format` marker.
Note that “in tandem” doesn’t mean “at the same time”. When the two options are used simultaneously, `--require-pragma` has priority, so `--insert-pragma` is ignored. The idea is that during an incremental adoption of Prettier in a big codebase, the developers participating in the transition process use `--insert-pragma` whereas `--require-pragma` is used by the rest of the team and automated tooling to process only files already transitioned. The feature has been inspired by Facebook’s [adoption strategy](https://prettier.io/blog/2017/05/03/1.3.0.html#facebook-adoption-update).
| Default | CLI Override | API Override |
| --- | --- | --- |
| `false` | `--insert-pragma` | `insertPragma: <bool>` |
Prose Wrap
-----------
*First available in v1.8.2*
By default, Prettier will not change wrapping in markdown text since some services use a linebreak-sensitive renderer, e.g. GitHub comments and BitBucket. To have Prettier wrap prose to the print width, change this option to "always". If you want Prettier to force all prose blocks to be on a single line and rely on editor/viewer soft wrapping instead, you can use `"never"`.
Valid options:
* `"always"` - Wrap prose if it exceeds the print width.
* `"never"` - Un-wrap each block of prose into one line.
* `"preserve"` - Do nothing, leave prose as-is. *First available in v1.9.0*
| Default | CLI Override | API Override |
| --- | --- | --- |
| `"preserve"` | `--prose-wrap <always|never|preserve>` | `proseWrap: "<always|never|preserve>"` |
HTML Whitespace Sensitivity
----------------------------
*First available in v1.15.0. First available for Handlebars in 2.3.0*
Specify the global whitespace sensitivity for HTML, Vue, Angular, and Handlebars. See [whitespace-sensitive formatting](https://prettier.io/blog/2018/11/07/1.15.0.html#whitespace-sensitive-formatting) for more info.
Valid options:
* `"css"` - Respect the default value of CSS `display` property. For Handlebars treated same as `strict`.
* `"strict"` - Whitespace (or the lack of it) around all tags is considered significant.
* `"ignore"` - Whitespace (or the lack of it) around all tags is considered insignificant.
| Default | CLI Override | API Override |
| --- | --- | --- |
| `"css"` | `--html-whitespace-sensitivity <css|strict|ignore>` | `htmlWhitespaceSensitivity: "<css|strict|ignore>"` |
Vue files script and style tags indentation
--------------------------------------------
*First available in v1.19.0*
Whether or not to indent the code inside `<script>` and `<style>` tags in Vue files.
Valid options:
* `false` - Do not indent script and style tags in Vue files.
* `true` - Indent script and style tags in Vue files.
| Default | CLI Override | API Override |
| --- | --- | --- |
| `false` | `--vue-indent-script-and-style` | `vueIndentScriptAndStyle: <bool>` |
End of Line
------------
*First available in v1.15.0, default value changed from `auto` to `lf` in v2.0.0*
For historical reasons, there exist two common flavors of line endings in text files. That is `\n` (or `LF` for *Line Feed*) and `\r\n` (or `CRLF` for *Carriage Return + Line Feed*). The former is common on Linux and macOS, while the latter is prevalent on Windows. Some details explaining why it is so [can be found on Wikipedia](https://en.wikipedia.org/wiki/Newline).
When people collaborate on a project from different operating systems, it becomes easy to end up with mixed line endings in a shared git repository. It is also possible for Windows users to accidentally change line endings in a previously committed file from `LF` to `CRLF`. Doing so produces a large `git diff` and thus makes the line-by-line history for a file (`git blame`) harder to explore.
If you want to make sure that your entire git repository only contains Linux-style line endings in files covered by Prettier:
1. Ensure Prettier’s `endOfLine` option is set to `lf` (this is a default value since v2.0.0)
2. Configure [a pre-commit hook](precommit) that will run Prettier
3. Configure Prettier to run in your CI pipeline using [`--check` flag](cli#--check). If you use Travis CI, set [the `autocrlf` option](https://docs.travis-ci.com/user/customizing-the-build#git-end-of-line-conversion-control) to `input` in `.travis.yml`.
4. Add `* text=auto eol=lf` to the repo’s `.gitattributes` file. You may need to ask Windows users to re-clone your repo after this change to ensure git has not converted `LF` to `CRLF` on checkout.
All modern text editors in all operating systems are able to correctly display line endings when `\n` (`LF`) is used. However, old versions of Notepad for Windows will visually squash such lines into one as they can only deal with `\r\n` (`CRLF`).
Valid options:
* `"lf"` – Line Feed only (`\n`), common on Linux and macOS as well as inside git repos
* `"crlf"` - Carriage Return + Line Feed characters (`\r\n`), common on Windows
* `"cr"` - Carriage Return character only (`\r`), used very rarely
* `"auto"` - Maintain existing line endings (mixed values within one file are normalised by looking at what’s used after the first line)
| Default | CLI Override | API Override |
| --- | --- | --- |
| `"lf"` | `--end-of-line <lf|crlf|cr|auto>` | `endOfLine: "<lf|crlf|cr|auto>"` |
Setting `end_of_line` in an [`.editorconfig` file](https://editorconfig.org/) will configure Prettier’s end of line usage, unless overridden.
Embedded Language Formatting
-----------------------------
*First available in v2.1.0*
Control whether Prettier formats quoted code embedded in the file.
When Prettier identifies cases where it looks like you've placed some code it knows how to format within a string in another file, like in a tagged template in JavaScript with a tag named `html` or in code blocks in Markdown, it will by default try to format that code.
Sometimes this behavior is undesirable, particularly in cases where you might not have intended the string to be interpreted as code. This option allows you to switch between the default behavior (`auto`) and disabling this feature entirely (`off`).
Valid options:
* `"auto"` – Format embedded code if Prettier can automatically identify it.
* `"off"` - Never automatically format embedded code.
| Default | CLI Override | API Override |
| --- | --- | --- |
| `"auto"` | `--embedded-language-formatting=off` | `embeddedLanguageFormatting: "off"` |
Single Attribute Per Line
--------------------------
*First available in v2.6.0*
Enforce single attribute per line in HTML, Vue and JSX.
Valid options:
* `false` - Do not enforce single attribute per line.
* `true` - Enforce single attribute per line.
| Default | CLI Override | API Override |
| --- | --- | --- |
| `false` | `--single-attribute-per-line` | `singleAttributePerLine: <bool>` |
| programming_docs |
prettier For Enterprise For Enterprise
==============
Available as part of the Tidelift Subscription
-----------------------------------------------
Tidelift is working with the maintainers of Prettier and thousands of other open source projects to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use.
[Learn more](https://tidelift.com/subscription/pkg/npm-prettier?utm_source=npm-prettier&utm_medium=referral&utm_campaign=enterprise) [Request a demo](https://tidelift.com/subscription/request-a-demo?utm_source=npm-prettier&utm_medium=referral&utm_campaign=enterprise)
###
Enterprise-ready open source software—managed for you
The Tidelift Subscription is a managed open source subscription for application dependencies covering millions of open source projects across JavaScript, Python, Java, PHP, Ruby, .NET, and more.
Your subscription includes:
**Security updates**
Tidelift’s security response team coordinates patches for new breaking security vulnerabilities and alerts immediately through a private channel, so your software supply chain is always secure.
**Licensing verification and indemnification**
Tidelift verifies license information to enable easy policy enforcement and adds intellectual property indemnification to cover creators and users in case something goes wrong. You always have a 100% up-to-date bill of materials for your dependencies to share with your legal team, customers, or partners.
**Maintenance and code improvement**
Tidelift ensures the software you rely on keeps working as long as you need it to work. Your managed dependencies are actively maintained and we recruit additional maintainers where required.
**Package selection and version guidance**
We help you choose the best open source packages from the start—and then guide you through updates to stay on the best releases as new issues arise.
**Roadmap input**
Take a seat at the table with the creators behind the software you use. Tidelift’s participating maintainers earn more income as their software is used by more subscribers, so they’re interested in knowing what you need.
**Tooling and cloud integration**
Tidelift works with GitHub, GitLab, BitBucket, and more. We support every cloud platform (and other deployment targets, too).
The end result? All of the capabilities you expect from commercial-grade software, for the full breadth of open source you use. That means less time grappling with esoteric open source trivia, and more time building your own applications—and your business.
[Learn more](https://tidelift.com/subscription/pkg/npm-prettier?utm_source=npm-prettier&utm_medium=referral&utm_campaign=enterprise) [Request a demo](https://tidelift.com/subscription/request-a-demo?utm_source=npm-prettier&utm_medium=referral&utm_campaign=enterprise)
prettier Integrating with Linters Integrating with Linters
========================
Linters usually contain not only code quality rules, but also stylistic rules. Most stylistic rules are unnecessary when using Prettier, but worse – they might conflict with Prettier! Use Prettier for code formatting concerns, and linters for code-quality concerns, as outlined in [Prettier vs. Linters](comparison).
Luckily it’s easy to turn off rules that conflict or are unnecessary with Prettier, by using these pre-made configs:
* [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier)
* [stylelint-config-prettier](https://github.com/prettier/stylelint-config-prettier)
Check out the above links for instructions on how to install and set things up.
Notes
------
When searching for both Prettier and your linter on the Internet you’ll probably find more related projects. These are **generally not recommended,** but can be useful in certain circumstances.
First, we have plugins that let you run Prettier as if it was a linter rule:
* [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier)
* [stylelint-prettier](https://github.com/prettier/stylelint-prettier)
These plugins were especially useful when Prettier was new. By running Prettier inside your linters, you didn’t have to set up any new infrastructure and you could re-use your editor integrations for the linters. But these days you can run `prettier --check .` and most editors have Prettier support.
The downsides of those plugins are:
* You end up with a lot of red squiggly lines in your editor, which gets annoying. Prettier is supposed to make you forget about formatting – and not be in your face about it!
* They are slower than running Prettier directly.
* They’re yet one layer of indirection where things may break.
Finally, we have tools that run `prettier` and then immediately lint files by running, for example, `eslint --fix` on them.
* [prettier-eslint](https://github.com/prettier/prettier-eslint)
* [prettier-stylelint](https://github.com/hugomrdias/prettier-stylelint)
Those are useful if some aspect of Prettier’s output makes Prettier completely unusable to you. Then you can have for example `eslint --fix` fix that up for you. The downside is that these tools are much slower than just running Prettier.
prettier API API
===
If you want to run Prettier programmatically, check this page out.
```
const prettier = require("prettier");
```
`prettier.format(source, options)`
-----------------------------------
`format` is used to format text using Prettier. `options.parser` must be set according to the language you are formatting (see the [list of available parsers](options#parser)). Alternatively, `options.filepath` can be specified for Prettier to infer the parser from the file extension. Other <options> may be provided to override the defaults.
```
prettier.format("foo ( );", { semi: false, parser: "babel" });
// -> "foo()"
```
`prettier.check(source [, options])`
-------------------------------------
`check` checks to see if the file has been formatted with Prettier given those options and returns a `Boolean`. This is similar to the `--check` or `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios.
`prettier.formatWithCursor(source [, options])`
------------------------------------------------
`formatWithCursor` both formats the code, and translates a cursor position from unformatted code to formatted code. This is useful for editor integrations, to prevent the cursor from moving when code is formatted.
The `cursorOffset` option should be provided, to specify where the cursor is. This option cannot be used with `rangeStart` and `rangeEnd`.
```
prettier.formatWithCursor(" 1", { cursorOffset: 2, parser: "babel" });
// -> { formatted: '1;\n', cursorOffset: 1 }
```
`prettier.resolveConfig(filePath [, options])`
-----------------------------------------------
`resolveConfig` can be used to resolve configuration for a given source file, passing its path as the first argument. The config search will start at the file path and continue to search up the directory (you can use `process.cwd()` to start searching from the current directory). Or you can pass directly the path of the config file as `options.config` if you don’t wish to search for it. A promise is returned which will resolve to:
* An options object, providing a [config file](configuration) was found.
* `null`, if no file was found.
The promise will be rejected if there was an error parsing the configuration file.
If `options.useCache` is `false`, all caching will be bypassed.
```
const text = fs.readFileSync(filePath, "utf8");
prettier.resolveConfig(filePath).then((options) => {
const formatted = prettier.format(text, options);
});
```
If `options.editorconfig` is `true` and an [`.editorconfig` file](https://editorconfig.org/) is in your project, Prettier will parse it and convert its properties to the corresponding Prettier configuration. This configuration will be overridden by `.prettierrc`, etc. Currently, the following EditorConfig properties are supported:
* `end_of_line`
* `indent_style`
* `indent_size`/`tab_width`
* `max_line_length`
Use `prettier.resolveConfig.sync(filePath [, options])` if you’d like to use sync version.
`prettier.resolveConfigFile([filePath])`
-----------------------------------------
`resolveConfigFile` can be used to find the path of the Prettier configuration file that will be used when resolving the config (i.e. when calling `resolveConfig`). A promise is returned which will resolve to:
* The path of the configuration file.
* `null`, if no file was found.
The promise will be rejected if there was an error parsing the configuration file.
The search starts at `process.cwd()`, or at `filePath` if provided. Please see the [cosmiconfig docs](https://github.com/davidtheclark/cosmiconfig#explorersearch) for details on how the resolving works.
```
prettier.resolveConfigFile(filePath).then((configFile) => {
// you got the path of the configuration file
});
```
Use `prettier.resolveConfigFile.sync([filePath])` if you’d like to use sync version.
`prettier.clearConfigCache()`
------------------------------
When Prettier loads configuration files and plugins, the file system structure is cached for performance. This function will clear the cache. Generally this is only needed for editor integrations that know that the file system has changed since the last format took place.
`prettier.getFileInfo(filePath [, options])`
---------------------------------------------
`getFileInfo` can be used by editor extensions to decide if a particular file needs to be formatted. This method returns a promise, which resolves to an object with the following properties:
```
{
ignored: boolean,
inferredParser: string | null,
}
```
The promise will be rejected if the type of `filePath` is not `string`.
Setting `options.ignorePath` (`string`) and `options.withNodeModules` (`boolean`) influence the value of `ignored` (`false` by default).
If the given `filePath` is ignored, the `inferredParser` is always `null`.
Providing [plugin](plugins) paths in `options.plugins` (`string[]`) helps extract `inferredParser` for files that are not supported by Prettier core.
When setting `options.resolveConfig` (`boolean`, default `false`), Prettier will resolve the configuration for the given `filePath`. This is useful, for example, when the `inferredParser` might be overridden for a subset of files.
Use `prettier.getFileInfo.sync(filePath [, options])` if you’d like to use sync version.
`prettier.getSupportInfo()`
----------------------------
Returns an object representing the options, parsers, languages and file types Prettier supports.
The support information looks like this:
```
{
languages: Array<{
name: string;
since?: string;
parsers: string[];
group?: string;
tmScope?: string;
aceMode?: string;
codemirrorMode?: string;
codemirrorMimeType?: string;
aliases?: string[];
extensions?: string[];
filenames?: string[];
linguistLanguageId?: number;
vscodeLanguageIds?: string[];
}>;
}
```
Custom Parser API (deprecated)
-------------------------------
*Will be removed in v3.0.0 (superseded by the Plugin API)*
Before <plugins> were a thing, Prettier had a similar but more limited feature called custom parsers. It will be removed in v3.0.0 as its functionality is a subset of what the Plugin API does. If you used it, please check the example below on how to migrate.
❌ Custom parser API (deprecated):
```
import { format } from "prettier";
format("lodash ( )", {
parser(text, { babel }) {
const ast = babel(text);
ast.program.body[0].expression.callee.name = "\_";
return ast;
},
});
// -> "\_();\n"
```
✔️ Plugin API:
```
import { format } from "prettier";
import parserBabel from "prettier/parser-babel.js";
const myCustomPlugin = {
parsers: {
"my-custom-parser": {
parse(text) {
const ast = parserBabel.parsers.babel.parse(text);
ast.program.body[0].expression.callee.name = "\_";
return ast;
},
astFormat: "estree",
},
},
};
format("lodash ( )", {
parser: "my-custom-parser",
plugins: [myCustomPlugin],
});
// -> "\_();\n"
```
> Note: Overall, doing codemods this way isn’t recommended. Prettier uses the location data of AST nodes for many things like preserving blank lines and attaching comments. When the AST is modified after the parsing, the location data often gets out of sync, which may lead to unpredictable results. Consider using [jscodeshift](https://github.com/facebook/jscodeshift) if you need codemods.
>
>
As part of the deprecated Custom parser API, it is possible to pass a path to a module exporting a `parse` function via the `--parser` option. Use the `--plugin` CLI option or the `plugins` API option instead to [load plugins](plugins#using-plugins).
prettier WebStorm Setup WebStorm Setup
==============
JetBrains IDEs (WebStorm, IntelliJ IDEA, PyCharm, etc.)
--------------------------------------------------------
WebStorm comes with built-in support for Prettier. If you’re using other JetBrains IDE like IntelliJ IDEA, PhpStorm, or PyCharm, make sure you have this [plugin](https://plugins.jetbrains.com/plugin/10456-prettier) installed and enabled in *Preferences / Settings | Plugins*.
First, you need to install and configure Prettier. You can find instructions on how to do it [here](https://www.jetbrains.com/help/webstorm/prettier.html#ws_prettier_install).
Once it’s done, you can do a few things in your IDE. You can use the **Reformat with Prettier** action (*Opt+Shift+Cmd+P* on macOS or *Alt+Shift+Ctrl+P* on Windows and Linux) to format the selected code, a file, or a whole directory.
You can also configure WebStorm to run Prettier on save (*Cmd+S/Ctrl+S*) or use it as the default formatter (*Opt+Cmd+L/Ctrl+Alt+L*). For this, open *Preferences / Settings | Languages & Frameworks | JavaScript | Prettier* and tick the corresponding checkbox: **On save** and/or **On ‘Reformat Code’** action.
By default, WebStorm will apply formatting to all *.js, .ts, .jsx*, and *.tsx* files that you’ve edited in your project. To apply the formatting to other file types, or to limit formatting to files located only in specific directories, you can customize the default configuration by using [glob patterns](https://github.com/isaacs/node-glob).
For more information, see [WebStorm online help](https://www.jetbrains.com/help/webstorm/prettier.html).
prettier Why Prettier? Why Prettier?
=============
Building and enforcing a style guide
-------------------------------------
By far the biggest reason for adopting Prettier is to stop all the on-going debates over styles. [It is generally accepted that having a common style guide is valuable for a project and team](https://www.smashingmagazine.com/2012/10/why-coding-style-matters/) but getting there is a very painful and unrewarding process. People get very emotional around particular ways of writing code and nobody likes spending time writing and receiving nits.
So why choose the “Prettier style guide” over any other random style guide? Because Prettier is the only “style guide” that is fully automatic. Even if Prettier does not format all code 100% the way you’d like, it’s worth the “sacrifice” given the unique benefits of Prettier, don’t you think?
* “We want to free mental threads and end discussions around style. While sometimes fruitful, these discussions are for the most part wasteful.”
* “Literally had an engineer go through a huge effort of cleaning up all of our code because we were debating ternary style for the longest time and were inconsistent about it. It was dumb, but it was a weird on-going “great debate” that wasted lots of little back and forth bits. It’s far easier for us all to agree now: just run Prettier, and go with that style.”
* “Getting tired telling people how to style their product code.”
* “Our top reason was to stop wasting our time debating style nits.”
* “Having a githook set up has reduced the amount of style issues in PRs that result in broken builds due to ESLint rules or things I have to nit-pick or clean up later.”
* “I don’t want anybody to nitpick any other person ever again.”
* “It reminds me of how Steve Jobs used to wear the same clothes every day because he has a million decisions to make and he didn’t want to be bothered to make trivial ones like picking out clothes. I think Prettier is like that.”
Helping Newcomers
------------------
Prettier is usually introduced by people with experience in the current codebase and JavaScript but the people that disproportionally benefit from it are newcomers to the codebase. One may think that it’s only useful for people with very limited programming experience, but we've seen it quicken the ramp up time from experienced engineers joining the company, as they likely used a different coding style before, and developers coming from a different programming language.
* “My motivations for using Prettier are: appearing that I know how to write JavaScript well.”
* “I always put spaces in the wrong place, now I don’t have to worry about it anymore.”
* “When you're a beginner you're making a lot of mistakes caused by the syntax. Thanks to Prettier, you can reduce these mistakes and save a lot of time to focus on what really matters.”
* “As a teacher, I will also tell to my students to install Prettier to help them to learn the JS syntax and have readable files.”
Writing code
-------------
What usually happens once people are using Prettier is that they realize that they actually spend a lot of time and mental energy formatting their code. With Prettier editor integration, you can just press that magic key binding and poof, the code is formatted. This is an eye opening experience if anything else.
* “I want to write code. Not spend cycles on formatting.”
* “It removed 5% that sucks in our daily life - aka formatting”
* “We're in 2017 and it’s still painful to break a call into multiple lines when you happen to add an argument that makes it go over the 80 columns limit :(“
Easy to adopt
--------------
We've worked very hard to use the least controversial coding styles, went through many rounds of fixing all the edge cases and polished the getting started experience. When you're ready to push Prettier into your codebase, not only should it be painless for you to do it technically but the newly formatted codebase should not generate major controversy and be accepted painlessly by your co-workers.
* “It’s low overhead. We were able to throw Prettier at very different kinds of repos without much work.”
* “It’s been mostly bug free. Had there been major styling issues during the course of implementation we would have been wary about throwing this at our JS codebase. I’m happy to say that’s not the case.”
* “Everyone runs it as part of their pre commit scripts, a couple of us use the editor on save extensions as well.”
* “It’s fast, against one of our larger JS codebases we were able to run Prettier in under 13 seconds.”
* “The biggest benefit for Prettier for us was being able to format the entire code base at once.”
Clean up an existing codebase
------------------------------
Since coming up with a coding style and enforcing it is a big undertaking, it often slips through the cracks and you are left working on inconsistent codebases. Running Prettier in this case is a quick win, the codebase is now uniform and easier to read without spending hardly any time.
* “Take a look at the code :) I just need to restore sanity.”
* “We inherited a ~2000 module ES6 code base, developed by 20 different developers over 18 months, in a global team. Felt like such a win without much research.”
Ride the hype train
--------------------
Purely technical aspects of the projects aren’t the only thing people look into when choosing to adopt Prettier. Who built and uses it and how quickly it spreads through the community has a non-trivial impact.
* “The amazing thing, for me, is: 1) Announced 2 months ago. 2) Already adopted by, it seems, every major JS project. 3) 7000 stars, 100,000 npm downloads/mo”
* “Was built by the same people as React & React Native.”
* “I like to be part of the hot new things.”
* “Because soon enough people are gonna ask for it.”
| programming_docs |
prettier Vim Setup Vim Setup
=========
Vim users can install either [vim-prettier](https://github.com/prettier/vim-prettier), which is Prettier specific, or [Neoformat](https://github.com/sbdchd/neoformat) or [ALE](https://github.com/dense-analysis/ale) which are generalized lint/format engines with support for Prettier.
[vim-prettier](https://github.com/prettier/vim-prettier)
---------------------------------------------------------
See the [vim-prettier](https://github.com/prettier/vim-prettier) readme for installation and usage instructions.
[Neoformat](https://github.com/sbdchd/neoformat)
-------------------------------------------------
The best way to install Neoformat is with your favorite plugin manager for Vim, such as [vim-plug](https://github.com/junegunn/vim-plug):
```
Plug 'sbdchd/neoformat'
```
In order for Neoformat to use a project-local version of Prettier (i.e. to use `node_modules/.bin/prettier` instead of looking for `prettier` on `$PATH`), you must set the `neoformat_try_node_exe` option:
```
let g:neoformat\_try\_node\_exe = 1
```
Run `:Neoformat` or `:Neoformat prettier` in a supported file to run Prettier.
To have Neoformat run Prettier on save:
```
autocmd BufWritePre *.js Neoformat
```
You can also make Vim format your code more frequently, by setting an `autocmd` for other events. Here are a couple of useful ones:
* `TextChanged`: after a change was made to the text in Normal mode
* `InsertLeave`: when leaving Insert mode
For example, you can format on both of the above events together with `BufWritePre` like this:
```
autocmd BufWritePre,TextChanged,InsertLeave *.js Neoformat
```
See `:help autocmd-events` in Vim for details.
It’s recommended to use a [config file](configuration), but you can also add options in your `.vimrc`:
```
autocmd FileType javascript setlocal formatprg=prettier\ --single-quote\ --trailing-comma\ es5
" Use formatprg when available
let g:neoformat\_try\_formatprg = 1
```
Each space in Prettier options should be escaped with `\`.
[ALE](https://github.com/dense-analysis/ale)
---------------------------------------------
ALE requires either Vim 8 or Neovim as ALE makes use of the asynchronous abilities that both Vim 8 and Neovim provide.
The best way to install ALE is with your favorite plugin manager for Vim, such as [vim-plug](https://github.com/junegunn/vim-plug):
```
Plug 'dense-analysis/ale'
```
You can find further instructions on the [ALE repository](https://github.com/dense-analysis/ale#3-installation).
ALE will try to use Prettier installed locally before looking for a global installation.
Enable the Prettier fixer for the languages you use:
```
let g:ale\_fixers = {
\ 'javascript': ['prettier'],
\ 'css': ['prettier'],
\}
```
ALE supports both *linters* and *fixers*. If you don’t specify which *linters* to run, **all available tools for all supported languages will be run,** and you might get a correctly formatted file with a bunch of lint errors. To disable this behavior you can tell ALE to run only linters you've explicitly configured (more info in the [FAQ](https://github.com/dense-analysis/ale/blob/ed8104b6ab10f63c78e49b60d2468ae2656250e9/README.md#faq-disable-linters)):
```
let g:ale\_linters\_explicit = 1
```
You can then run `:ALEFix` in a JavaScript or CSS file to run Prettier.
To have ALE run Prettier on save:
```
let g:ale\_fix\_on\_save = 1
```
It’s recommended to use a [config file](configuration), but you can also add options in your `.vimrc`:
```
let g:ale\_javascript\_prettier\_options = '--single-quote --trailing-comma all'
```
[coc-prettier](https://github.com/neoclide/coc-prettier)
---------------------------------------------------------
Prettier extension for [coc.nvim](https://github.com/neoclide/coc.nvim) which requires neovim or vim8.1. Install coc.nvim with your favorite plugin manager, such as [vim-plug](https://github.com/junegunn/vim-plug):
```
Plug 'neoclide/coc.nvim', {'branch': 'release'}
```
And install coc-prettier by command:
```
CocInstall coc-prettier
```
Setup `Prettier` command in your `init.vim` or `.vimrc`
```
command! -nargs=0 Prettier :call CocAction('runCommand', 'prettier.formatFile')
```
Update your `coc-settings.json` for languages that you want format on save.
```
{
"coc.preferences.formatOnSaveFiletypes": ["css", "markdown"]
}
```
[coc-prettier](https://github.com/neoclide/coc-prettier) have same configurations of [prettier-vscode](https://github.com/prettier/prettier-vscode), open `coc-settings.json` by `:CocConfig` to get autocompletion support.
Running manually
-----------------
If you want something really bare-bones, you can create a custom key binding. In this example, `gp` (mnemonic: "get pretty") is used to run prettier (with options) in the currently active buffer:
```
nnoremap gp :silent %!prettier --stdin-filepath %<CR>
```
Note that if there’s a syntax error in your code, the whole buffer will be replaced with an error message. You’ll need to press `u` to get your code back.
Another disadvantage of this approach is that the cursor position won’t be preserved.
prettier Rationale Rationale
=========
Prettier is an opinionated code formatter. This document explains some of its choices.
What Prettier is concerned about
---------------------------------
###
Correctness
The first requirement of Prettier is to output valid code that has the exact same behavior as before formatting. Please report any code where Prettier fails to follow these correctness rules — that’s a bug which needs to be fixed!
###
Strings
Double or single quotes? Prettier chooses the one which results in the fewest number of escapes. `"It's gettin' better!"`, not `'It\'s gettin\' better!'`. In case of a tie or the string not containing any quotes, Prettier defaults to double quotes (but that can be changed via the [singleQuote](options#quotes) option).
JSX has its own option for quotes: [jsxSingleQuote](options#jsx-quotes). JSX takes its roots from HTML, where the dominant use of quotes for attributes is double quotes. Browser developer tools also follow this convention by always displaying HTML with double quotes, even if the source code uses single quotes. A separate option allows using single quotes for JS and double quotes for "HTML" (JSX).
Prettier maintains the way your string is escaped. For example, `"🙂"` won’t be formatted into `"\uD83D\uDE42"` and vice versa.
###
Empty lines
It turns out that empty lines are very hard to automatically generate. The approach that Prettier takes is to preserve empty lines the way they were in the original source code. There are two additional rules:
* Prettier collapses multiple blank lines into a single blank line.
* Empty lines at the start and end of blocks (and whole files) are removed. (Files always end with a single newline, though.)
###
Multi-line objects
By default, Prettier’s printing algorithm prints expressions on a single line if they fit. Objects are used for a lot of different things in JavaScript, though, and sometimes it really helps readability if they stay multiline. See [object lists](https://github.com/prettier/prettier/issues/74#issue-199965534), [nested configs](https://github.com/prettier/prettier/issues/88#issuecomment-275448346), [stylesheets](https://github.com/prettier/prettier/issues/74#issuecomment-275262094) and [keyed methods](https://github.com/prettier/prettier/pull/495#issuecomment-275745434), for example. We haven’t been able to find a good rule for all those cases, so Prettier instead keeps objects multiline if there’s a newline between the `{` and the first key in the original source code. A consequence of this is that long singleline objects are automatically expanded, but short multiline objects are never collapsed.
**Tip:** If you have a multiline object that you’d like to join up into a single line:
```
const user = {
name: "John Doe",
age: 30,
};
```
…all you need to do is remove the newline after `{`:
```
const user = { name: "John Doe",
age: 30
};
```
…and then run Prettier:
```
const user = { name: "John Doe", age: 30 };
```
And if you’d like to go multiline again, add in a newline after `{`:
```
const user = {
name: "John Doe", age: 30 };
```
…and run Prettier:
```
const user = {
name: "John Doe",
age: 30,
};
```
> ####
> ♻️ A note on formatting reversibility
>
> The semi-manual formatting for object literals is in fact a workaround, not a feature. It was implemented only because at the time a good heuristic wasn’t found and an urgent fix was needed. However, as a general strategy, Prettier avoids *non-reversible* formatting like that, so the team is still looking for heuristics that would allow either to remove this behavior completely or at least to reduce the number of situations where it’s applied.
>
> What does **reversible** mean? Once an object literal becomes multiline, Prettier won’t collapse it back. If in Prettier-formatted code, we add a property to an object literal, run Prettier, then change our mind, remove the added property, and then run Prettier again, we might end up with a formatting not identical to the initial one. This useless change might even get included in a commit, which is exactly the kind of situation Prettier was created to prevent.
>
>
###
Decorators
Just like with objects, decorators are used for a lot of different things. Sometimes it makes sense to write decorators *above* the line they're decorating, sometimes it’s nicer if they're on the *same* line. We haven’t been able to find a good rule for this, so Prettier keeps your decorator positioned like you wrote them (if they fit on the line). This isn’t ideal, but a pragmatic solution to a difficult problem.
```
@Component({
selector: "hero-button",
template: `<button>{{ label }}</button>`,
})
class HeroButtonComponent {
// These decorators were written inline and fit on the line so they stay
// inline.
@Output() change = new EventEmitter();
@Input() label: string;
// These were written multiline, so they stay multiline.
@readonly
@nonenumerable
NODE\_TYPE: 2;
}
```
There’s one exception: classes. We don’t think it ever makes sense to inline the decorators for them, so they are always moved to their own line.
```
// Before running Prettier:
@observer class OrderLine {
@observable price: number = 0;
}
```
```
// After running Prettier:
@observer
class OrderLine {
@observable price: number = 0;
}
```
Note: Prettier 1.14.x and older tried to automatically move your decorators, so if you've run an older Prettier version on your code you might need to manually join up some decorators here and there to avoid inconsistencies:
```
@observer
class OrderLine {
@observable price: number = 0;
@observable
amount: number = 0;
}
```
One final thing: TC39 has [not yet decided if decorators come before or after `export`](https://github.com/tc39/proposal-decorators/issues/69). In the meantime, Prettier supports both:
```
@decorator export class Foo {}
export @decorator class Foo {}
```
###
Semicolons
This is about using the [noSemi](options#semicolons) option.
Consider this piece of code:
```
if (shouldAddLines) {
[-1, 1].forEach(delta => addLine(delta \* 20))
}
```
While the above code works just fine without semicolons, Prettier actually turns it into:
```
if (shouldAddLines) {
;[-1, 1].forEach(delta => addLine(delta \* 20))
}
```
This is to help you avoid mistakes. Imagine Prettier *not* inserting that semicolon and adding this line:
```
if (shouldAddLines) {
+ console.log('Do we even get here??')
[-1, 1].forEach(delta => addLine(delta * 20))
}
```
Oops! The above actually means:
```
if (shouldAddLines) {
console.log('Do we even get here??')[-1, 1].forEach(delta => addLine(delta \* 20))
}
```
With a semicolon in front of that `[` such issues never happen. It makes the line independent of other lines so you can move and add lines without having to think about ASI rules.
This practice is also common in [standard](https://standardjs.com/rules.html#semicolons) which uses a semicolon-free style.
###
Print width
The [printWidth](options#print-width) option is more of a guideline to Prettier than a hard rule. It is not the upper allowed line length limit. It is a way to say to Prettier roughly how long you’d like lines to be. Prettier will make both shorter and longer lines, but generally strive to meet the specified print width.
There are some edge cases, such as really long string literals, regexps, comments and variable names, which cannot be broken across lines (without using code transforms which [Prettier doesn’t do](#what-prettier-is-_not_-concerned-about)). Or if you nest your code 50 levels deep your lines are of course going to be mostly indentation :)
Apart from that, there are a few cases where Prettier intentionally exceeds the print width.
####
Imports
Prettier can break long `import` statements across several lines:
```
import {
CollectionDashboard,
DashboardPlaceholder,
} from "../components/collections/collection-dashboard/main";
```
The following example doesn’t fit within the print width, but Prettier prints it in a single line anyway:
```
import { CollectionDashboard } from "../components/collections/collection-dashboard/main";
```
This might be unexpected by some, but we do it this way since it was a common request to keep `import`s with single elements in a single line. The same applies for `require` calls.
####
Testing functions
Another common request was to keep lengthy test descriptions in one line, even if it gets too long. In such cases, wrapping the arguments to new lines doesn’t help much.
```
describe("NodeRegistry", () => {
it("makes no request if there are no nodes to prefetch, even if the cache is stale", async () => {
// The above line exceeds the print width but stayed on one line anyway.
});
});
```
Prettier has special cases for common testing framework functions such as `describe`, `it` and `test`.
###
JSX
Prettier prints things a little differently compared to other JS when JSX is involved:
```
function greet(user) {
return user
? `Welcome back, ${user.name}!`
: "Greetings, traveler! Sign up today!";
}
function Greet({ user }) {
return (
<div>{user ? (
<p>Welcome back, {user.name}!</p>
) : (
<p>Greetings, traveler! Sign up today!</p>
)}</div>
);
}
```
There are two reasons.
First off, lots of people already wrapped their JSX in parentheses, especially in `return` statements. Prettier follows this common style.
Secondly, [the alternate formatting makes it easier to edit the JSX](https://github.com/prettier/prettier/issues/2208). It is easy to leave a semicolon behind. As opposed to normal JS, a leftover semicolon in JSX can end up as plain text showing on your page.
```
<div><p>Greetings, traveler! Sign up today!</p>; {/\* <-- Oops! \*/}</div>
```
###
Comments
When it comes to the *content* of comments, Prettier can’t do much really. Comments can contain everything from prose to commented out code and ASCII diagrams. Since they can contain anything, Prettier can’t know how to format or wrap them. So they are left as-is. The only exception to this are JSDoc-style comments (block comments where every line starts with a `*`), which Prettier can fix the indentation of.
Then there’s the question of *where* to put the comments. Turns out this is a really difficult problem. Prettier tries its best to keep your comments roughly where they were, but it’s no easy task because comments can be placed almost anywhere.
Generally, you get the best results when placing comments **on their own lines,** instead of at the end of lines. Prefer `// eslint-disable-next-line` over `// eslint-disable-line`.
Note that “magic comments” such as `eslint-disable-next-line` and `$FlowFixMe` might sometimes need to be manually moved due to Prettier breaking an expression into multiple lines.
Imagine this piece of code:
```
// eslint-disable-next-line no-eval
const result = safeToEval ? eval(input) : fallback(input);
```
Then you need to add another condition:
```
// eslint-disable-next-line no-eval
const result = safeToEval && settings.allowNativeEval ? eval(input) : fallback(input);
```
Prettier will turn the above into:
```
// eslint-disable-next-line no-eval
const result =
safeToEval && settings.allowNativeEval ? eval(input) : fallback(input);
```
Which means that the `eslint-disable-next-line` comment is no longer effective. In this case you need to move the comment:
```
const result =
// eslint-disable-next-line no-eval
safeToEval && settings.allowNativeEval ? eval(input) : fallback(input);
```
If possible, prefer comments that operate on line ranges (e.g. `eslint-disable` and `eslint-enable`) or on the statement level (e.g. `/* istanbul ignore next */`), they are even safer. It’s possible to disallow using `eslint-disable-line` and `eslint-disable-next-line` comments using [`eslint-plugin-eslint-comments`](https://github.com/mysticatea/eslint-plugin-eslint-comments).
Disclaimer about non-standard syntax
-------------------------------------
Prettier is often able to recognize and format non-standard syntax such as ECMAScript early-stage proposals and Markdown syntax extensions not defined by any specification. The support for such syntax is considered best-effort and experimental. Incompatibilities may be introduced in any release and should not be viewed as breaking changes.
What Prettier is *not* concerned about
---------------------------------------
Prettier only *prints* code. It does not transform it. This is to limit the scope of Prettier. Let’s focus on the printing and do it really well!
Here are a few examples of things that are out of scope for Prettier:
* Turning single- or double-quoted strings into template literals or vice versa.
* Using `+` to break long string literals into parts that fit the print width.
* Adding/removing `{}` and `return` where they are optional.
* Turning `?:` into `if`-`else` statements.
* Sorting/moving imports, object keys, class members, JSX keys, CSS properties or anything else. Apart from being a *transform* rather than just printing (as mentioned above), sorting is potentially unsafe because of side effects (for imports, as an example) and makes it difficult to verify the most important [correctness](#correctness) goal.
cakephp Class PluginUnloadCommand Class PluginUnloadCommand
==========================
Command for unloading plugins.
**Namespace:** [Cake\Command](namespace-cake.command)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [buildOptionParser()](#buildOptionParser()) public
Get the option parser.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) public
Execute the command
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [modifyApplication()](#modifyApplication()) protected
Modify the application class.
* ##### [run()](#run()) public
Run the command.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor
By default CakePHP will construct command objects when building the CommandCollection for your application.
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### buildOptionParser() public
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Get the option parser.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser to update
#### Returns
`Cake\Console\ConsoleOptionParser`
### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int|null
```
Execute the command
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### modifyApplication() protected
```
modifyApplication(string $app, string $plugin): bool
```
Modify the application class.
#### Parameters
`string` $app Path to the application to update.
`string` $plugin Name of plugin.
#### Returns
`bool`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
Property Detail
---------------
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name protected
The name of this command.
#### Type
`string`
| programming_docs |
cakephp Class NullEngine Class NullEngine
=================
Null cache engine, all operations appear to work, but do nothing.
This is used internally for when Cache::disable() has been called.
**Namespace:** [Cake\Cache\Engine](namespace-cake.cache.engine)
Constants
---------
* `string` **CHECK\_KEY**
```
'key'
```
* `string` **CHECK\_VALUE**
```
'value'
```
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` The default cache configuration is overridden in most cache adapters. These are the keys that are common to all adapters. If overridden, this property is not used.
* [$\_groupPrefix](#%24_groupPrefix) protected `string` Contains the compiled string with all group prefixes to be prepended to every key in this cache engine
Method Summary
--------------
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_key()](#_key()) protected
Generates a key for cache backend usage.
* ##### [add()](#add()) public
Add a key to the cache if it does not already exist.
* ##### [clear()](#clear()) public
Delete all keys from the cache
* ##### [clearGroup()](#clearGroup()) public
Clears all values belonging to a group. Is up to the implementing engine to decide whether actually delete the keys or just simulate it to achieve the same result.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [decrement()](#decrement()) public
Decrement a number under the key and return decremented value
* ##### [delete()](#delete()) public
Delete a key from the cache
* ##### [deleteMultiple()](#deleteMultiple()) public
Deletes multiple cache items as a list
* ##### [duration()](#duration()) protected
Convert the various expressions of a TTL value into duration in seconds
* ##### [ensureValidKey()](#ensureValidKey()) protected
Ensure the validity of the given cache key.
* ##### [ensureValidType()](#ensureValidType()) protected
Ensure the validity of the argument type and cache keys.
* ##### [get()](#get()) public
Fetches the value for a given key from the cache.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getMultiple()](#getMultiple()) public
Obtains multiple cache items by their unique keys.
* ##### [groups()](#groups()) public
Does whatever initialization for each group is required and returns the `group value` for each of them, this is the token representing each group in the cache key
* ##### [has()](#has()) public
Determines whether an item is present in the cache.
* ##### [increment()](#increment()) public
Increment a number under the key and return incremented value
* ##### [init()](#init()) public
Initialize the cache engine
* ##### [set()](#set()) public
Persists data in the cache, uniquely referenced by the given key with an optional expiration TTL time.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setMultiple()](#setMultiple()) public
Persists a set of key => value pairs in the cache, with an optional TTL.
* ##### [warning()](#warning()) protected
Cache Engines may trigger warnings if they encounter failures during operation, if option warnOnWriteFailures is set to true.
Method Detail
-------------
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_key() protected
```
_key(string $key): string
```
Generates a key for cache backend usage.
If the requested key is valid, the group prefix value and engine prefix are applied. Whitespace in keys will be replaced.
#### Parameters
`string` $key the key passed over
#### Returns
`string`
#### Throws
`Cake\Cache\InvalidArgumentException`
If key's value is invalid. ### add() public
```
add(string $key, mixed $value): bool
```
Add a key to the cache if it does not already exist.
Defaults to a non-atomic implementation. Subclasses should prefer atomic implementations.
#### Parameters
`string` $key Identifier for the data.
`mixed` $value Data to be cached.
#### Returns
`bool`
### clear() public
```
clear(): bool
```
Delete all keys from the cache
#### Returns
`bool`
### clearGroup() public
```
clearGroup(string $group): bool
```
Clears all values belonging to a group. Is up to the implementing engine to decide whether actually delete the keys or just simulate it to achieve the same result.
Each implementation needs to decide whether actually delete the keys or just augment a group generation value to achieve the same result.
#### Parameters
`string` $group #### Returns
`bool`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
```
$this->configShallow('key', $value);
```
Setting a nested value:
```
$this->configShallow('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->configShallow(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### decrement() public
```
decrement(string $key, int $offset = 1): int|false
```
Decrement a number under the key and return decremented value
#### Parameters
`string` $key `int` $offset optional #### Returns
`int|false`
### delete() public
```
delete(string $key): bool
```
Delete a key from the cache
#### Parameters
`string` $key #### Returns
`bool`
### deleteMultiple() public
```
deleteMultiple(iterable $keys): bool
```
Deletes multiple cache items as a list
This is a best effort attempt. If deleting an item would create an error it will be ignored, and all items will be attempted.
#### Parameters
`iterable` $keys #### Returns
`bool`
### duration() protected
```
duration(DateInterval|int|null $ttl): int
```
Convert the various expressions of a TTL value into duration in seconds
#### Parameters
`DateInterval|int|null` $ttl The TTL value of this item. If null is sent, the driver's default duration will be used.
#### Returns
`int`
### ensureValidKey() protected
```
ensureValidKey(string $key): void
```
Ensure the validity of the given cache key.
#### Parameters
`string` $key Key to check.
#### Returns
`void`
#### Throws
`Cake\Cache\InvalidArgumentException`
When the key is not valid. ### ensureValidType() protected
```
ensureValidType(iterable $iterable, string $check = self::CHECK_VALUE): void
```
Ensure the validity of the argument type and cache keys.
#### Parameters
`iterable` $iterable The iterable to check.
`string` $check optional Whether to check keys or values.
#### Returns
`void`
#### Throws
`Cake\Cache\InvalidArgumentException`
### get() public
```
get(string $key, mixed $default = null): mixed
```
Fetches the value for a given key from the cache.
#### Parameters
`string` $key `mixed` $default optional #### Returns
`mixed`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### Usage
Reading the whole config:
```
$this->getConfig();
```
Reading a specific value:
```
$this->getConfig('key');
```
Reading a nested value:
```
$this->getConfig('some.nested.key');
```
Reading with default value:
```
$this->getConfig('some-key', 'default-value');
```
#### Parameters
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getMultiple() public
```
getMultiple(iterable $keys, mixed $default = null): iterable
```
Obtains multiple cache items by their unique keys.
#### Parameters
`iterable` $keys `mixed` $default optional #### Returns
`iterable`
### groups() public
```
groups(): array<string>
```
Does whatever initialization for each group is required and returns the `group value` for each of them, this is the token representing each group in the cache key
#### Returns
`array<string>`
### has() public
```
has(string $key): bool
```
Determines whether an item is present in the cache.
NOTE: It is recommended that has() is only to be used for cache warming type purposes and not to be used within your live applications operations for get/set, as this method is subject to a race condition where your has() will return true and immediately after, another script can remove it making the state of your app out of date.
#### Parameters
`string` $key The cache item key.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If the $key string is not a legal value. ### increment() public
```
increment(string $key, int $offset = 1): int|false
```
Increment a number under the key and return incremented value
#### Parameters
`string` $key `int` $offset optional #### Returns
`int|false`
### init() public
```
init(array<string, mixed> $config = []): bool
```
Initialize the cache engine
Called automatically by the cache frontend. Merge the runtime config with the defaults before use.
#### Parameters
`array<string, mixed>` $config optional #### Returns
`bool`
### set() public
```
set(string $key, mixed $value, null|intDateInterval $ttl = null): bool
```
Persists data in the cache, uniquely referenced by the given key with an optional expiration TTL time.
#### Parameters
`string` $key `mixed` $value `null|intDateInterval` $ttl optional #### Returns
`bool`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### Usage
Setting a specific value:
```
$this->setConfig('key', $value);
```
Setting a nested value:
```
$this->setConfig('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->setConfig(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setMultiple() public
```
setMultiple(iterable $values, null|intDateInterval $ttl = null): bool
```
Persists a set of key => value pairs in the cache, with an optional TTL.
#### Parameters
`iterable` $values `null|intDateInterval` $ttl optional #### Returns
`bool`
### warning() protected
```
warning(string $message): void
```
Cache Engines may trigger warnings if they encounter failures during operation, if option warnOnWriteFailures is set to true.
#### Parameters
`string` $message The warning message.
#### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
The default cache configuration is overridden in most cache adapters. These are the keys that are common to all adapters. If overridden, this property is not used.
* `duration` Specify how long items in this cache configuration last.
* `groups` List of groups or 'tags' associated to every key stored in this config. handy for deleting a complete group from cache.
* `prefix` Prefix appended to all entries. Good for when you need to share a keyspace with either another cache config or another application.
* `warnOnWriteFailures` Some engines, such as ApcuEngine, may raise warnings on write failures.
#### Type
`array<string, mixed>`
### $\_groupPrefix protected
Contains the compiled string with all group prefixes to be prepended to every key in this cache engine
#### Type
`string`
cakephp Class UrlHelper Class UrlHelper
================
UrlHelper class for generating URLs.
**Namespace:** [Cake\View\Helper](namespace-cake.view.helper)
Property Summary
----------------
* [$\_View](#%24_View) protected `Cake\View\View` The View instance this helper is attached to
* [$\_assetUrlClassName](#%24_assetUrlClassName) protected `string` Asset URL engine class name
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
* [$\_helperMap](#%24_helperMap) protected `array<string, array>` A helper lookup table used to lazy load helper objects.
* [$helpers](#%24helpers) protected `array` List of helpers used by this helper
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Provide non fatal errors on missing method calls.
* ##### [\_\_construct()](#__construct()) public
Default Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Lazy loads helpers.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_confirm()](#_confirm()) protected
Returns a string to be used as onclick handler for confirm dialogs.
* ##### [addClass()](#addClass()) public
Adds the given class to the element options
* ##### [assetTimestamp()](#assetTimestamp()) public
Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in Configure. If Asset.timestamp is true and debug is true, or Asset.timestamp === 'force' a timestamp will be added.
* ##### [assetUrl()](#assetUrl()) public
Generates URL for given asset file.
* ##### [build()](#build()) public
Returns a URL based on provided parameters.
* ##### [buildFromPath()](#buildFromPath()) public
Returns a URL from a route path string.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [css()](#css()) public
Generates URL for given CSS file.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getView()](#getView()) public
Get the view instance this helper is bound to.
* ##### [image()](#image()) public
Generates URL for given image file.
* ##### [implementedEvents()](#implementedEvents()) public
Event listeners.
* ##### [initialize()](#initialize()) public
Check proper configuration
* ##### [script()](#script()) public
Generates URL for given javascript file.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [webroot()](#webroot()) public
Checks if a file exists when theme is used, if no file is found default location is returned
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $params): mixed|void
```
Provide non fatal errors on missing method calls.
#### Parameters
`string` $method Method to invoke
`array` $params Array of params for the method.
#### Returns
`mixed|void`
### \_\_construct() public
```
__construct(Cake\View\View $view, array<string, mixed> $config = [])
```
Default Constructor
#### Parameters
`Cake\View\View` $view The View this helper is being attached to.
`array<string, mixed>` $config optional Configuration settings for the helper.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\View\Helper|null|void
```
Lazy loads helpers.
#### Parameters
`string` $name Name of the property being accessed.
#### Returns
`Cake\View\Helper|null|void`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_confirm() protected
```
_confirm(string $okCode, string $cancelCode): string
```
Returns a string to be used as onclick handler for confirm dialogs.
#### Parameters
`string` $okCode Code to be executed after user chose 'OK'
`string` $cancelCode Code to be executed after user chose 'Cancel'
#### Returns
`string`
### addClass() public
```
addClass(array<string, mixed> $options, string $class, string $key = 'class'): array<string, mixed>
```
Adds the given class to the element options
#### Parameters
`array<string, mixed>` $options Array options/attributes to add a class to
`string` $class The class name being added.
`string` $key optional the key to use for class. Defaults to `'class'`.
#### Returns
`array<string, mixed>`
### assetTimestamp() public
```
assetTimestamp(string $path, string|bool $timestamp = null): string
```
Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in Configure. If Asset.timestamp is true and debug is true, or Asset.timestamp === 'force' a timestamp will be added.
#### Parameters
`string` $path The file path to timestamp, the path must be inside `App.wwwRoot` in Configure.
`string|bool` $timestamp optional If set will overrule the value of `Asset.timestamp` in Configure.
#### Returns
`string`
### assetUrl() public
```
assetUrl(string $path, array<string, mixed> $options = []): string
```
Generates URL for given asset file.
Depending on options passed provides full URL with domain name. Also calls `Helper::assetTimestamp()` to add timestamp to local files.
### Options:
* `fullBase` Boolean true or a string (e.g. <https://example>) to return full URL with protocol and domain name.
* `pathPrefix` Path prefix for relative URLs
* `ext` Asset extension to append
* `plugin` False value will prevent parsing path as a plugin
* `timestamp` Overrides the value of `Asset.timestamp` in Configure. Set to false to skip timestamp generation. Set to true to apply timestamps when debug is true. Set to 'force' to always enable timestamping regardless of debug value.
#### Parameters
`string` $path Path string or URL array
`array<string, mixed>` $options optional Options array.
#### Returns
`string`
### build() public
```
build(array|string|null $url = null, array<string, mixed> $options = []): string
```
Returns a URL based on provided parameters.
### Options:
* `escape`: If false, the URL will be returned unescaped, do only use if it is manually escaped afterwards before being displayed.
* `fullBase`: If true, the full base URL will be prepended to the result
#### Parameters
`array|string|null` $url optional Either a relative string URL like `/products/view/23` or an array of URL parameters. Using an array for URLs will allow you to leverage the reverse routing features of CakePHP.
`array<string, mixed>` $options optional Array of options.
#### Returns
`string`
### buildFromPath() public
```
buildFromPath(string $path, array $params = [], array<string, mixed> $options = []): string
```
Returns a URL from a route path string.
### Options:
* `escape`: If false, the URL will be returned unescaped, do only use if it is manually escaped afterwards before being displayed.
* `fullBase`: If true, the full base URL will be prepended to the result
#### Parameters
`string` $path Cake-relative route path.
`array` $params optional An array specifying any additional parameters. Can be also any special parameters supported by `Router::url()`.
`array<string, mixed>` $options optional Array of options.
#### Returns
`string`
#### See Also
\Cake\Routing\Router::pathUrl() ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
```
$this->configShallow('key', $value);
```
Setting a nested value:
```
$this->configShallow('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->configShallow(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### css() public
```
css(string $path, array<string, mixed> $options = []): string
```
Generates URL for given CSS file.
Depending on options passed provides full URL with domain name. Also calls `Helper::assetTimestamp()` to add timestamp to local files.
#### Parameters
`string` $path Path string.
`array<string, mixed>` $options optional Options array. Possible keys: `fullBase` Return full URL with domain name `pathPrefix` Path prefix for relative URLs `ext` Asset extension to append `plugin` False value will prevent parsing path as a plugin `timestamp` Overrides the value of `Asset.timestamp` in Configure. Set to false to skip timestamp generation. Set to true to apply timestamps when debug is true. Set to 'force' to always enable timestamping regardless of debug value.
#### Returns
`string`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### Usage
Reading the whole config:
```
$this->getConfig();
```
Reading a specific value:
```
$this->getConfig('key');
```
Reading a nested value:
```
$this->getConfig('some.nested.key');
```
Reading with default value:
```
$this->getConfig('some-key', 'default-value');
```
#### Parameters
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getView() public
```
getView(): Cake\View\View
```
Get the view instance this helper is bound to.
#### Returns
`Cake\View\View`
### image() public
```
image(string $path, array<string, mixed> $options = []): string
```
Generates URL for given image file.
Depending on options passed provides full URL with domain name. Also calls `Helper::assetTimestamp()` to add timestamp to local files.
#### Parameters
`string` $path Path string.
`array<string, mixed>` $options optional Options array. Possible keys: `fullBase` Return full URL with domain name `pathPrefix` Path prefix for relative URLs `plugin` False value will prevent parsing path as a plugin `timestamp` Overrides the value of `Asset.timestamp` in Configure. Set to false to skip timestamp generation. Set to true to apply timestamps when debug is true. Set to 'force' to always enable timestamping regardless of debug value.
#### Returns
`string`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Event listeners.
By defining one of the callback methods a helper is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want helpers to listen to non-standard events.
#### Returns
`array<string, mixed>`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Check proper configuration
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The configuration settings provided to this helper.
#### Returns
`void`
### script() public
```
script(string $path, array<string, mixed> $options = []): string
```
Generates URL for given javascript file.
Depending on options passed provides full URL with domain name. Also calls `Helper::assetTimestamp()` to add timestamp to local files.
#### Parameters
`string` $path Path string.
`array<string, mixed>` $options optional Options array. Possible keys: `fullBase` Return full URL with domain name `pathPrefix` Path prefix for relative URLs `ext` Asset extension to append `plugin` False value will prevent parsing path as a plugin `timestamp` Overrides the value of `Asset.timestamp` in Configure. Set to false to skip timestamp generation. Set to true to apply timestamps when debug is true. Set to 'force' to always enable timestamping regardless of debug value.
#### Returns
`string`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### Usage
Setting a specific value:
```
$this->setConfig('key', $value);
```
Setting a nested value:
```
$this->setConfig('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->setConfig(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### webroot() public
```
webroot(string $file): string
```
Checks if a file exists when theme is used, if no file is found default location is returned
#### Parameters
`string` $file The file to create a webroot path to.
#### Returns
`string`
Property Detail
---------------
### $\_View protected
The View instance this helper is attached to
#### Type
`Cake\View\View`
### $\_assetUrlClassName protected
Asset URL engine class name
#### Type
`string`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
### $\_helperMap protected
A helper lookup table used to lazy load helper objects.
#### Type
`array<string, array>`
### $helpers protected
List of helpers used by this helper
#### Type
`array`
| programming_docs |
cakephp Class TypeMap Class TypeMap
==============
Implements default and single-use mappings for columns to their associated types
**Namespace:** [Cake\Database](namespace-cake.database)
Property Summary
----------------
* [$\_defaults](#%24_defaults) protected `array<int|string, string>` Array with the default fields and the related types this query might contain.
* [$\_types](#%24_types) protected `array<int|string, string>` Array with the fields and the related types that override defaults this query might contain
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Creates an instance with the given defaults
* ##### [addDefaults()](#addDefaults()) public
Add additional default types into the type map.
* ##### [getDefaults()](#getDefaults()) public
Returns the currently configured types.
* ##### [getTypes()](#getTypes()) public
Gets a map of fields and their associated types for single-use.
* ##### [setDefaults()](#setDefaults()) public
Configures a map of fields and associated type.
* ##### [setTypes()](#setTypes()) public
Sets a map of fields and their associated types for single-use.
* ##### [toArray()](#toArray()) public
Returns an array of all types mapped types
* ##### [type()](#type()) public
Returns the type of the given column. If there is no single use type is configured, the column type will be looked for inside the default mapping. If neither exist, null will be returned.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<int|string, string> $defaults = [])
```
Creates an instance with the given defaults
#### Parameters
`array<int|string, string>` $defaults optional The defaults to use.
### addDefaults() public
```
addDefaults(array<int|string, string> $types): void
```
Add additional default types into the type map.
If a key already exists it will not be overwritten.
#### Parameters
`array<int|string, string>` $types The additional types to add.
#### Returns
`void`
### getDefaults() public
```
getDefaults(): array<int|string, string>
```
Returns the currently configured types.
#### Returns
`array<int|string, string>`
### getTypes() public
```
getTypes(): array<int|string, string>
```
Gets a map of fields and their associated types for single-use.
#### Returns
`array<int|string, string>`
### setDefaults() public
```
setDefaults(array<int|string, string> $defaults): $this
```
Configures a map of fields and associated type.
These values will be used as the default mapping of types for every function in this instance that supports a `$types` param.
This method is useful when you want to avoid repeating type definitions as setting types overwrites the last set of types.
### Example
```
$query->setDefaults(['created' => 'datetime', 'is_visible' => 'boolean']);
```
This method will replace all the existing default mappings with the ones provided. To add into the mappings use `addDefaults()`.
#### Parameters
`array<int|string, string>` $defaults Array where keys are field names / positions and values are the correspondent type.
#### Returns
`$this`
### setTypes() public
```
setTypes(array<int|string, string> $types): $this
```
Sets a map of fields and their associated types for single-use.
### Example
```
$query->setTypes(['created' => 'time']);
```
This method will replace all the existing type maps with the ones provided.
#### Parameters
`array<int|string, string>` $types Array where keys are field names / positions and values are the correspondent type.
#### Returns
`$this`
### toArray() public
```
toArray(): array<int|string, string>
```
Returns an array of all types mapped types
#### Returns
`array<int|string, string>`
### type() public
```
type(string|int $column): string|null
```
Returns the type of the given column. If there is no single use type is configured, the column type will be looked for inside the default mapping. If neither exist, null will be returned.
#### Parameters
`string|int` $column The type for a given column
#### Returns
`string|null`
Property Detail
---------------
### $\_defaults protected
Array with the default fields and the related types this query might contain.
Used to avoid repetition when calling multiple functions inside this class that may require a custom type for a specific field.
#### Type
`array<int|string, string>`
### $\_types protected
Array with the fields and the related types that override defaults this query might contain
Used to avoid repetition when calling multiple functions inside this class that may require a custom type for a specific field.
#### Type
`array<int|string, string>`
cakephp Class BodyNotContains Class BodyNotContains
======================
BodyContains
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$ignoreCase](#%24ignoreCase) protected `bool`
* [$response](#%24response) protected `Psr\Http\Message\ResponseInterface`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface $response, bool $ignoreCase = false)
```
Constructor.
#### Parameters
`Psr\Http\Message\ResponseInterface` $response A response instance.
`bool` $ignoreCase optional Ignore case
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected type
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $ignoreCase protected
#### Type
`bool`
### $response protected
#### Type
`Psr\Http\Message\ResponseInterface`
cakephp Class MissingModelException Class MissingModelException
============================
Used when a model cannot be found.
**Namespace:** [Cake\Datasource\Exception](namespace-cake.datasource.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional Either the string of the error message, or an array of attributes that are made available in the view, and sprintf()'d into Exception::$\_messageTemplate
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class MissingViewException Class MissingViewException
===========================
Used when a view class file cannot be found.
**Namespace:** [Cake\View\Exception](namespace-cake.view.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional Either the string of the error message, or an array of attributes that are made available in the view, and sprintf()'d into Exception::$\_messageTemplate
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class PersistenceFailedException Class PersistenceFailedException
=================================
Used when a strict save or delete fails
**Namespace:** [Cake\ORM\Exception](namespace-cake.orm.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_entity](#%24_entity) protected `Cake\Datasource\EntityInterface` The entity on which the persistence operation failed
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getEntity()](#getEntity()) public
Get the passed in entity
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Datasource\EntityInterface $entity, array<string>|string $message, int|null $code = null, Throwable|null $previous = null)
```
Constructor.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity on which the persistence operation failed
`array<string>|string` $message Either the string of the error message, or an array of attributes that are made available in the view, and sprintf()'d into Exception::$\_messageTemplate
`int|null` $code optional The code of the error, is also the HTTP status code for the error.
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getEntity() public
```
getEntity(): Cake\Datasource\EntityInterface
```
Get the passed in entity
#### Returns
`Cake\Datasource\EntityInterface`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_entity protected
The entity on which the persistence operation failed
#### Type
`Cake\Datasource\EntityInterface`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
| programming_docs |
cakephp Class DatabaseSession Class DatabaseSession
======================
DatabaseSession provides methods to be used with Session.
**Namespace:** [Cake\Http\Session](namespace-cake.http.session)
Property Summary
----------------
* [$\_table](#%24_table) protected `Cake\ORM\Table` Reference to the table handling the session data
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$\_timeout](#%24_timeout) protected `int` Number of seconds to mark the session as expired
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor. Looks at Session configuration information and sets up the session model.
* ##### [close()](#close()) public
Method called on close of a database session.
* ##### [destroy()](#destroy()) public
Method called on the destruction of a database session.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [gc()](#gc()) public
Helper function called on gc for database sessions.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [open()](#open()) public
Method called on open of a database session.
* ##### [read()](#read()) public
Method used to read from a database session.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [setTimeout()](#setTimeout()) public
Set the timeout value for sessions.
* ##### [write()](#write()) public
Helper function called on write for database sessions.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor. Looks at Session configuration information and sets up the session model.
#### Parameters
`array<string, mixed>` $config optional The configuration for this engine. It requires the 'model' key to be present corresponding to the Table to use for managing the sessions.
### close() public
```
close(): bool
```
Method called on close of a database session.
#### Returns
`bool`
### destroy() public
```
destroy(string $id): bool
```
Method called on the destruction of a database session.
#### Parameters
`string` $id ID that uniquely identifies session in database.
#### Returns
`bool`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### gc() public
```
gc(int $maxlifetime): int|false
```
Helper function called on gc for database sessions.
#### Parameters
`int` $maxlifetime Sessions that have not updated for the last maxlifetime seconds will be removed.
#### Returns
`int|false`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### open() public
```
open(string $path, string $name): bool
```
Method called on open of a database session.
#### Parameters
`string` $path The path where to store/retrieve the session.
`string` $name The session name.
#### Returns
`bool`
### read() public
```
read(string $id): string|false
```
Method used to read from a database session.
#### Parameters
`string` $id ID that uniquely identifies session in database.
#### Returns
`string|false`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### setTimeout() public
```
setTimeout(int $timeout): $this
```
Set the timeout value for sessions.
Primarily used in testing.
#### Parameters
`int` $timeout The timeout duration.
#### Returns
`$this`
### write() public
```
write(string $id, string $data): bool
```
Helper function called on write for database sessions.
#### Parameters
`string` $id ID that uniquely identifies session in database.
`string` $data The data to be saved.
#### Returns
`bool`
Property Detail
---------------
### $\_table protected
Reference to the table handling the session data
#### Type
`Cake\ORM\Table`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $\_timeout protected
Number of seconds to mark the session as expired
#### Type
`int`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
cakephp Interface ControllerFactoryInterface Interface ControllerFactoryInterface
=====================================
Factory method for building controllers from request/response pairs.
**Namespace:** [Cake\Http](namespace-cake.http)
Method Summary
--------------
* ##### [create()](#create()) public
Create a controller for a given request
* ##### [invoke()](#invoke()) public
Invoke a controller's action and wrapping methods.
Method Detail
-------------
### create() public
```
create(Psr\Http\Message\ServerRequestInterface $request): mixed
```
Create a controller for a given request
#### Parameters
`Psr\Http\Message\ServerRequestInterface` $request The request to build a controller for.
#### Returns
`mixed`
#### Throws
`Cake\Http\Exception\MissingControllerException`
### invoke() public
```
invoke(mixed $controller): Psr\Http\Message\ResponseInterface
```
Invoke a controller's action and wrapping methods.
#### Parameters
`mixed` $controller The controller to invoke.
#### Returns
`Psr\Http\Message\ResponseInterface`
cakephp Class MapReduce Class MapReduce
================
Implements a simplistic version of the popular Map-Reduce algorithm. Acts like an iterator for the original passed data after each result has been processed, thus offering a transparent wrapper for results coming from any source.
**Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator)
Property Summary
----------------
* [$\_counter](#%24_counter) protected `int` Count of elements emitted during the Reduce phase
* [$\_data](#%24_data) protected `Traversable` Holds the original data that needs to be processed
* [$\_executed](#%24_executed) protected `bool` Whether the Map-Reduce routine has been executed already on the data
* [$\_intermediate](#%24_intermediate) protected `array` Holds the shuffled results that were emitted from the map phase
* [$\_mapper](#%24_mapper) protected `callable` A callable that will be executed for each record in the original data
* [$\_reducer](#%24_reducer) protected `callable|null` A callable that will be executed for each intermediate record emitted during the Map phase
* [$\_result](#%24_result) protected `array` Holds the results as emitted during the reduce phase
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_execute()](#_execute()) protected
Runs the actual Map-Reduce algorithm. This is iterate the original data and call the mapper function for each , then for each intermediate bucket created during the Map phase call the reduce function.
* ##### [emit()](#emit()) public
Appends a new record to the final list of results and optionally assign a key for this record.
* ##### [emitIntermediate()](#emitIntermediate()) public
Appends a new record to the bucket labelled with $key, usually as a result of mapping a single record from the original data.
* ##### [getIterator()](#getIterator()) public
Returns an iterator with the end result of running the Map and Reduce phases on the original data
Method Detail
-------------
### \_\_construct() public
```
__construct(Traversable $data, callable $mapper, callable|null $reducer = null)
```
Constructor
### Example:
Separate all unique odd and even numbers in an array
```
$data = new \ArrayObject([1, 2, 3, 4, 5, 3]);
$mapper = function ($value, $key, $mr) {
$type = ($value % 2 === 0) ? 'even' : 'odd';
$mr->emitIntermediate($value, $type);
};
$reducer = function ($numbers, $type, $mr) {
$mr->emit(array_unique($numbers), $type);
};
$results = new MapReduce($data, $mapper, $reducer);
```
Previous example will generate the following result:
```
['odd' => [1, 3, 5], 'even' => [2, 4]]
```
#### Parameters
`Traversable` $data the original data to be processed
`callable` $mapper the mapper callback. This function will receive 3 arguments. The first one is the current value, second the current results key and third is this class instance so you can call the result emitters.
`callable|null` $reducer optional the reducer callback. This function will receive 3 arguments. The first one is the list of values inside a bucket, second one is the name of the bucket that was created during the mapping phase and third one is an instance of this class.
### \_execute() protected
```
_execute(): void
```
Runs the actual Map-Reduce algorithm. This is iterate the original data and call the mapper function for each , then for each intermediate bucket created during the Map phase call the reduce function.
#### Returns
`void`
#### Throws
`LogicException`
if emitIntermediate was called but no reducer function was provided ### emit() public
```
emit(mixed $val, mixed $key = null): void
```
Appends a new record to the final list of results and optionally assign a key for this record.
#### Parameters
`mixed` $val The value to be appended to the final list of results
`mixed` $key optional and optional key to assign to the value
#### Returns
`void`
### emitIntermediate() public
```
emitIntermediate(mixed $val, mixed $bucket): void
```
Appends a new record to the bucket labelled with $key, usually as a result of mapping a single record from the original data.
#### Parameters
`mixed` $val The record itself to store in the bucket
`mixed` $bucket the name of the bucket where to put the record
#### Returns
`void`
### getIterator() public
```
getIterator(): Traversable
```
Returns an iterator with the end result of running the Map and Reduce phases on the original data
#### Returns
`Traversable`
Property Detail
---------------
### $\_counter protected
Count of elements emitted during the Reduce phase
#### Type
`int`
### $\_data protected
Holds the original data that needs to be processed
#### Type
`Traversable`
### $\_executed protected
Whether the Map-Reduce routine has been executed already on the data
#### Type
`bool`
### $\_intermediate protected
Holds the shuffled results that were emitted from the map phase
#### Type
`array`
### $\_mapper protected
A callable that will be executed for each record in the original data
#### Type
`callable`
### $\_reducer protected
A callable that will be executed for each intermediate record emitted during the Map phase
#### Type
`callable|null`
### $\_result protected
Holds the results as emitted during the reduce phase
#### Type
`array`
cakephp Class Digest Class Digest
=============
Digest authentication adapter for Cake\Http\Client
Generally not directly constructed, but instead used by {@link \Cake\Http\Client} when $options['auth']['type'] is 'digest'
**Namespace:** [Cake\Http\Client\Auth](namespace-cake.http.client.auth)
Property Summary
----------------
* [$\_client](#%24_client) protected `Cake\Http\Client` Instance of Cake\Http\Client
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_generateHeader()](#_generateHeader()) protected
Generate the header Authorization
* ##### [\_getServerInfo()](#_getServerInfo()) protected
Retrieve information about the authentication
* ##### [authentication()](#authentication()) public
Add Authorization header to the request.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Http\Client $client, array|null $options = null)
```
Constructor
#### Parameters
`Cake\Http\Client` $client Http client object.
`array|null` $options optional Options list.
### \_generateHeader() protected
```
_generateHeader(Cake\Http\Client\Request $request, array<string, mixed> $credentials): string
```
Generate the header Authorization
#### Parameters
`Cake\Http\Client\Request` $request The request object.
`array<string, mixed>` $credentials Authentication credentials.
#### Returns
`string`
### \_getServerInfo() protected
```
_getServerInfo(Cake\Http\Client\Request $request, array $credentials): array
```
Retrieve information about the authentication
Will get the realm and other tokens by performing another request without authentication to get authentication challenge.
#### Parameters
`Cake\Http\Client\Request` $request The request object.
`array` $credentials Authentication credentials.
#### Returns
`array`
### authentication() public
```
authentication(Cake\Http\Client\Request $request, array<string, mixed> $credentials): Cake\Http\Client\Request
```
Add Authorization header to the request.
#### Parameters
`Cake\Http\Client\Request` $request The request object.
`array<string, mixed>` $credentials Authentication credentials.
#### Returns
`Cake\Http\Client\Request`
#### See Also
https://www.ietf.org/rfc/rfc2617.txt Property Detail
---------------
### $\_client protected
Instance of Cake\Http\Client
#### Type
`Cake\Http\Client`
cakephp Class I18nException Class I18nException
====================
I18n exception.
**Namespace:** [Cake\I18n\Exception](namespace-cake.i18n.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional Either the string of the error message, or an array of attributes that are made available in the view, and sprintf()'d into Exception::$\_messageTemplate
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class BasicWidget Class BasicWidget
==================
Basic input class.
This input class can be used to render basic simple input elements like hidden, text, email, tel and other types.
**Namespace:** [Cake\View\Widget](namespace-cake.view.widget)
Property Summary
----------------
* [$\_templates](#%24_templates) protected `Cake\View\StringTemplate` StringTemplate instance.
* [$defaults](#%24defaults) protected `array<string, mixed>` Data defaults.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [mergeDefaults()](#mergeDefaults()) protected
Merge default values with supplied data.
* ##### [render()](#render()) public
Render a text widget or other simple widget like email/tel/number.
* ##### [secureFields()](#secureFields()) public
Returns a list of fields that need to be secured for this widget.
* ##### [setMaxLength()](#setMaxLength()) protected
Set value for "maxlength" attribute if applicable.
* ##### [setRequired()](#setRequired()) protected
Set value for "required" attribute if applicable.
* ##### [setStep()](#setStep()) protected
Set value for "step" attribute if applicable.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\View\StringTemplate $templates)
```
Constructor.
#### Parameters
`Cake\View\StringTemplate` $templates Templates list.
### mergeDefaults() protected
```
mergeDefaults(array<string, mixed> $data, Cake\View\Form\ContextInterface $context): array<string, mixed>
```
Merge default values with supplied data.
#### Parameters
`array<string, mixed>` $data Data array
`Cake\View\Form\ContextInterface` $context Context instance.
#### Returns
`array<string, mixed>`
### render() public
```
render(array<string, mixed> $data, Cake\View\Form\ContextInterface $context): string
```
Render a text widget or other simple widget like email/tel/number.
This method accepts a number of keys:
* `name` The name attribute.
* `val` The value attribute.
* `escape` Set to false to disable escaping on all attributes.
Any other keys provided in $data will be converted into HTML attributes.
#### Parameters
`array<string, mixed>` $data The data to build an input with.
`Cake\View\Form\ContextInterface` $context The current form context.
#### Returns
`string`
### secureFields() public
```
secureFields(array<string, mixed> $data): array<string>
```
Returns a list of fields that need to be secured for this widget.
#### Parameters
`array<string, mixed>` $data #### Returns
`array<string>`
### setMaxLength() protected
```
setMaxLength(array<string, mixed> $data, Cake\View\Form\ContextInterface $context, string $fieldName): array<string, mixed>
```
Set value for "maxlength" attribute if applicable.
#### Parameters
`array<string, mixed>` $data Data array
`Cake\View\Form\ContextInterface` $context Context instance.
`string` $fieldName Field name.
#### Returns
`array<string, mixed>`
### setRequired() protected
```
setRequired(array<string, mixed> $data, Cake\View\Form\ContextInterface $context, string $fieldName): array<string, mixed>
```
Set value for "required" attribute if applicable.
#### Parameters
`array<string, mixed>` $data Data array
`Cake\View\Form\ContextInterface` $context Context instance.
`string` $fieldName Field name.
#### Returns
`array<string, mixed>`
### setStep() protected
```
setStep(array<string, mixed> $data, Cake\View\Form\ContextInterface $context, string $fieldName): array<string, mixed>
```
Set value for "step" attribute if applicable.
#### Parameters
`array<string, mixed>` $data Data array
`Cake\View\Form\ContextInterface` $context Context instance.
`string` $fieldName Field name.
#### Returns
`array<string, mixed>`
Property Detail
---------------
### $\_templates protected
StringTemplate instance.
#### Type
`Cake\View\StringTemplate`
### $defaults protected
Data defaults.
#### Type
`array<string, mixed>`
| programming_docs |
cakephp Class EagerLoadable Class EagerLoadable
====================
Represents a single level in the associations tree to be eagerly loaded for a specific query. This contains all the information required to fetch the results from the database from an associations and all its children levels.
**Namespace:** [Cake\ORM](namespace-cake.orm)
Property Summary
----------------
* [$\_aliasPath](#%24_aliasPath) protected `string` A dotted separated string representing the path of associations that should be followed to fetch this level.
* [$\_associations](#%24_associations) protected `arrayCake\ORM\EagerLoadable>` A list of other associations to load from this level.
* [$\_canBeJoined](#%24_canBeJoined) protected `bool` Whether this level can be fetched using a join.
* [$\_config](#%24_config) protected `array<string, mixed>` A list of options to pass to the association object for loading the records.
* [$\_forMatching](#%24_forMatching) protected `bool|null` Whether this level was meant for a "matching" fetch operation
* [$\_instance](#%24_instance) protected `Cake\ORM\Association|null` The Association class instance to use for loading the records.
* [$\_name](#%24_name) protected `string` The name of the association to load.
* [$\_propertyPath](#%24_propertyPath) protected `string|null` A dotted separated string representing the path of entity properties in which results for this level should be placed.
* [$\_targetProperty](#%24_targetProperty) protected `string|null` The property name where the association result should be nested in the result.
Method Summary
--------------
* ##### [\_\_clone()](#__clone()) public
Handles cloning eager loadables.
* ##### [\_\_construct()](#__construct()) public
Constructor. The $config parameter accepts the following array keys:
* ##### [addAssociation()](#addAssociation()) public
Adds a new association to be loaded from this level.
* ##### [aliasPath()](#aliasPath()) public
Gets a dot separated string representing the path of associations that should be followed to fetch this level.
* ##### [asContainArray()](#asContainArray()) public
Returns a representation of this object that can be passed to Cake\ORM\EagerLoader::contain()
* ##### [associations()](#associations()) public
Returns the Association class instance to use for loading the records.
* ##### [canBeJoined()](#canBeJoined()) public
Gets whether this level can be fetched using a join.
* ##### [forMatching()](#forMatching()) public
Gets whether this level was meant for a "matching" fetch operation.
* ##### [getConfig()](#getConfig()) public
Gets the list of options to pass to the association object for loading the records.
* ##### [instance()](#instance()) public
Gets the Association class instance to use for loading the records.
* ##### [propertyPath()](#propertyPath()) public
Gets a dot separated string representing the path of entity properties in which results for this level should be placed.
* ##### [setCanBeJoined()](#setCanBeJoined()) public
Sets whether this level can be fetched using a join.
* ##### [setConfig()](#setConfig()) public
Sets the list of options to pass to the association object for loading the records.
* ##### [targetProperty()](#targetProperty()) public
The property name where the result of this association should be nested at the end.
Method Detail
-------------
### \_\_clone() public
```
__clone(): void
```
Handles cloning eager loadables.
#### Returns
`void`
### \_\_construct() public
```
__construct(string $name, array<string, mixed> $config = [])
```
Constructor. The $config parameter accepts the following array keys:
* associations
* instance
* config
* canBeJoined
* aliasPath
* propertyPath
* forMatching
* targetProperty
The keys maps to the settable properties in this class.
#### Parameters
`string` $name The Association name.
`array<string, mixed>` $config optional The list of properties to set.
### addAssociation() public
```
addAssociation(string $name, Cake\ORM\EagerLoadable $association): void
```
Adds a new association to be loaded from this level.
#### Parameters
`string` $name The association name.
`Cake\ORM\EagerLoadable` $association The association to load.
#### Returns
`void`
### aliasPath() public
```
aliasPath(): string
```
Gets a dot separated string representing the path of associations that should be followed to fetch this level.
#### Returns
`string`
### asContainArray() public
```
asContainArray(): array<string, array>
```
Returns a representation of this object that can be passed to Cake\ORM\EagerLoader::contain()
#### Returns
`array<string, array>`
### associations() public
```
associations(): arrayCake\ORM\EagerLoadable>
```
Returns the Association class instance to use for loading the records.
#### Returns
`arrayCake\ORM\EagerLoadable>`
### canBeJoined() public
```
canBeJoined(): bool
```
Gets whether this level can be fetched using a join.
#### Returns
`bool`
### forMatching() public
```
forMatching(): bool|null
```
Gets whether this level was meant for a "matching" fetch operation.
#### Returns
`bool|null`
### getConfig() public
```
getConfig(): array<string, mixed>
```
Gets the list of options to pass to the association object for loading the records.
#### Returns
`array<string, mixed>`
### instance() public
```
instance(): Cake\ORM\Association
```
Gets the Association class instance to use for loading the records.
#### Returns
`Cake\ORM\Association`
#### Throws
`RuntimeException`
### propertyPath() public
```
propertyPath(): string|null
```
Gets a dot separated string representing the path of entity properties in which results for this level should be placed.
For example, in the following nested property:
```
$article->author->company->country
```
The property path of `country` will be `author.company`
#### Returns
`string|null`
### setCanBeJoined() public
```
setCanBeJoined(bool $possible): $this
```
Sets whether this level can be fetched using a join.
#### Parameters
`bool` $possible The value to set.
#### Returns
`$this`
### setConfig() public
```
setConfig(array<string, mixed> $config): $this
```
Sets the list of options to pass to the association object for loading the records.
#### Parameters
`array<string, mixed>` $config The value to set.
#### Returns
`$this`
### targetProperty() public
```
targetProperty(): string|null
```
The property name where the result of this association should be nested at the end.
For example, in the following nested property:
```
$article->author->company->country
```
The target property of `country` will be just `country`
#### Returns
`string|null`
Property Detail
---------------
### $\_aliasPath protected
A dotted separated string representing the path of associations that should be followed to fetch this level.
#### Type
`string`
### $\_associations protected
A list of other associations to load from this level.
#### Type
`arrayCake\ORM\EagerLoadable>`
### $\_canBeJoined protected
Whether this level can be fetched using a join.
#### Type
`bool`
### $\_config protected
A list of options to pass to the association object for loading the records.
#### Type
`array<string, mixed>`
### $\_forMatching protected
Whether this level was meant for a "matching" fetch operation
#### Type
`bool|null`
### $\_instance protected
The Association class instance to use for loading the records.
#### Type
`Cake\ORM\Association|null`
### $\_name protected
The name of the association to load.
#### Type
`string`
### $\_propertyPath protected
A dotted separated string representing the path of entity properties in which results for this level should be placed.
For example, in the following nested property:
```
$article->author->company->country
```
The property path of `country` will be `author.company`
#### Type
`string|null`
### $\_targetProperty protected
The property name where the association result should be nested in the result.
For example, in the following nested property:
```
$article->author->company->country
```
The target property of `country` will be just `country`
#### Type
`string|null`
cakephp Namespace Stub Namespace Stub
==============
### Classes
* ##### [TestExceptionRenderer](class-cake.testsuite.stub.testexceptionrenderer)
Test Exception Renderer.
cakephp Class Date Class Date
===========
Extends the Date class provided by Chronos.
Adds handy methods and locale-aware formatting helpers
**Namespace:** [Cake\I18n](namespace-cake.i18n)
**Deprecated:** 4.3.0 Use the immutable alternative `FrozenDate` instead.
Constants
---------
* `int` **DAYS\_PER\_WEEK**
```
7
```
* `string` **DEFAULT\_TO\_STRING\_FORMAT**
```
'Y-m-d H:i:s'
```
Default format to use for \_\_toString method when type juggling occurs.
* `int` **FRIDAY**
```
5
```
* `int` **HOURS\_PER\_DAY**
```
24
```
* `int` **MINUTES\_PER\_HOUR**
```
60
```
* `int` **MONDAY**
```
1
```
* `int` **MONTHS\_PER\_QUARTER**
```
3
```
* `int` **MONTHS\_PER\_YEAR**
```
12
```
* `int` **SATURDAY**
```
6
```
* `int` **SECONDS\_PER\_MINUTE**
```
60
```
* `int` **SUNDAY**
```
7
```
* `int` **THURSDAY**
```
4
```
* `int` **TUESDAY**
```
2
```
* `int` **WEDNESDAY**
```
3
```
* `int` **WEEKS\_PER\_YEAR**
```
52
```
* `int` **YEARS\_PER\_CENTURY**
```
100
```
* `int` **YEARS\_PER\_DECADE**
```
10
```
Property Summary
----------------
* [$\_formatters](#%24_formatters) protected static `arrayIntlDateFormatter>` In-memory cache of date formatters
* [$\_jsonEncodeFormat](#%24_jsonEncodeFormat) protected static `Closure|array<int>|string|int` The format to use when converting this object to JSON.
* [$\_lastErrors](#%24_lastErrors) protected static `array` Holds the last error generated by createFromFormat
* [$\_toStringFormat](#%24_toStringFormat) protected static `array<int>|string|int` The format to use when formatting a time using `Cake\I18n\Date::i18nFormat()` and `__toString`. This format is also used by `parseDateTime()`.
* [$age](#%24age) public @property-read `int` does a diffInYears() with default parameters
* [$day](#%24day) public @property-read `int`
* [$dayOfWeek](#%24dayOfWeek) public @property-read `int` 1 (for Monday) through 7 (for Sunday)
* [$dayOfWeekName](#%24dayOfWeekName) public @property-read `string`
* [$dayOfYear](#%24dayOfYear) public @property-read `int` 0 through 365
* [$days](#%24days) protected static `array` Names of days of the week.
* [$daysInMonth](#%24daysInMonth) public @property-read `int` number of days in the given month
* [$defaultLocale](#%24defaultLocale) protected static `string|null` The default locale to be used for displaying formatted date strings.
* [$diffFormatter](#%24diffFormatter) protected static `Cake\Chronos\DifferenceFormatterInterface` Instance of the diff formatting object.
* [$dst](#%24dst) public @property-read `bool` daylight savings time indicator, true if DST, false otherwise
* [$hour](#%24hour) public @property-read `int`
* [$lenientParsing](#%24lenientParsing) protected static `bool` Whether lenient parsing is enabled for IntlDateFormatter.
* [$local](#%24local) public @property-read `bool` checks if the timezone is local, true if local, false otherwise
* [$micro](#%24micro) public @property-read `int`
* [$microsecond](#%24microsecond) public @property-read `int`
* [$minute](#%24minute) public @property-read `int`
* [$month](#%24month) public @property-read `int`
* [$niceFormat](#%24niceFormat) public static `array<int>|string|int` The format to use when formatting a time using `Cake\I18n\Date::nice()`
* [$offset](#%24offset) public @property-read `int` the timezone offset in seconds from UTC
* [$offsetHours](#%24offsetHours) public @property-read `int` the timezone offset in hours from UTC
* [$quarter](#%24quarter) public @property-read `int` the quarter of this instance, 1 - 4
* [$relativePattern](#%24relativePattern) protected static `string` Regex for relative period.
* [$second](#%24second) public @property-read `int`
* [$timestamp](#%24timestamp) public @property-read `int` seconds since the Unix Epoch
* [$timezone](#%24timezone) public @property-read `DateTimeZone` the current timezone
* [$timezoneName](#%24timezoneName) public @property-read `string`
* [$toStringFormat](#%24toStringFormat) protected static `string` Format to use for \_\_toString method when type juggling occurs.
* [$tz](#%24tz) public @property-read `DateTimeZone` alias of timezone
* [$tzName](#%24tzName) public @property-read `string`
* [$utc](#%24utc) public @property-read `bool` checks if the timezone is UTC, true if UTC, false otherwise
* [$weekEndsAt](#%24weekEndsAt) protected static `int` Last day of week
* [$weekOfMonth](#%24weekOfMonth) public @property-read `int` 1 through 5
* [$weekOfYear](#%24weekOfYear) public @property-read `int` ISO-8601 week number of year, weeks starting on Monday
* [$weekStartsAt](#%24weekStartsAt) protected static `int` First day of week
* [$weekendDays](#%24weekendDays) protected static `array` Days of weekend
* [$wordAccuracy](#%24wordAccuracy) public static `array<string>` The format to use when formatting a time using `Date::timeAgoInWords()` and the difference is less than `Date::$wordEnd`
* [$wordEnd](#%24wordEnd) public static `string` The end of relative time telling
* [$wordFormat](#%24wordFormat) public static `array<int>|string|int` The format to use when formatting a time using `Cake\I18n\Date::timeAgoInWords()` and the difference is more than `Cake\I18n\Date::$wordEnd`
* [$year](#%24year) public @property-read `int`
* [$yearIso](#%24yearIso) public @property-read `int`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Create a new FrozenDate instance.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns the data that should be displayed when debugging this object
* ##### [\_\_get()](#__get()) public
Get a part of the ChronosInterface object
* ##### [\_\_isset()](#__isset()) public
Check if an attribute exists on the object
* ##### [\_\_toString()](#__toString()) public
Format the instance as a string using the set format
* ##### [\_formatObject()](#_formatObject()) protected
Returns a translated and localized date string. Implements what IntlDateFormatter::formatObject() is in PHP 5.5+
* ##### [add()](#add()) public
Add an Interval to a Date
* ##### [addDay()](#addDay()) public
Add a day to the instance
* ##### [addDays()](#addDays()) public
Add days to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addHour()](#addHour()) public
Add an hour to the instance
* ##### [addHours()](#addHours()) public
Add hours to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addMinute()](#addMinute()) public
Add a minute to the instance
* ##### [addMinutes()](#addMinutes()) public
Add minutes to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addMonth()](#addMonth()) public
Add a month to the instance.
* ##### [addMonthWithOverflow()](#addMonthWithOverflow()) public
Add a month with overflow to the instance.
* ##### [addMonths()](#addMonths()) public
Add months to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addMonthsWithOverflow()](#addMonthsWithOverflow()) public
Add months with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addSecond()](#addSecond()) public
Add a second to the instance
* ##### [addSeconds()](#addSeconds()) public
Add seconds to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addWeek()](#addWeek()) public
Add a week to the instance
* ##### [addWeekday()](#addWeekday()) public
Add a weekday to the instance
* ##### [addWeekdays()](#addWeekdays()) public
Add weekdays to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addWeeks()](#addWeeks()) public
Add weeks to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addYear()](#addYear()) public
Add a year to the instance
* ##### [addYearWithOverflow()](#addYearWithOverflow()) public
Add a year with overflow to the instance
* ##### [addYears()](#addYears()) public
Add years to the instance. Positive $value travel forward while negative $value travel into the past.
* ##### [addYearsWithOverflow()](#addYearsWithOverflow()) public
Add years with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [average()](#average()) public
Modify the current instance to the average of a given instance (default now) and the current instance.
* ##### [between()](#between()) public
Determines if the instance is between two others
* ##### [closest()](#closest()) public
Get the closest date from the instance.
* ##### [copy()](#copy()) public
Get a copy of the instance
* ##### [create()](#create()) public static
Create a new ChronosInterface instance from a specific date and time.
* ##### [createFromArray()](#createFromArray()) public static
Creates a ChronosInterface instance from an array of date and time values.
* ##### [createFromDate()](#createFromDate()) public static
Create a ChronosInterface instance from just a date. The time portion is set to now.
* ##### [createFromFormat()](#createFromFormat()) public static
Create a ChronosInterface instance from a specific format
* ##### [createFromTime()](#createFromTime()) public static
Create a ChronosInterface instance from just a time. The date portion is set to today.
* ##### [createFromTimestamp()](#createFromTimestamp()) public static
Create a ChronosInterface instance from a timestamp
* ##### [createFromTimestampUTC()](#createFromTimestampUTC()) public static
Create a ChronosInterface instance from an UTC timestamp
* ##### [day()](#day()) public
Set the instance's day
* ##### [diffFiltered()](#diffFiltered()) public
Get the difference by the given interval using a filter callable
* ##### [diffForHumans()](#diffForHumans()) public
Get the difference in a human readable format.
* ##### [diffFormatter()](#diffFormatter()) public static
Get the difference formatter instance or overwrite the current one.
* ##### [diffInDays()](#diffInDays()) public
Get the difference in days
* ##### [diffInDaysFiltered()](#diffInDaysFiltered()) public
Get the difference in days using a filter callable
* ##### [diffInHours()](#diffInHours()) public
Get the difference in hours
* ##### [diffInHoursFiltered()](#diffInHoursFiltered()) public
Get the difference in hours using a filter callable
* ##### [diffInMinutes()](#diffInMinutes()) public
Get the difference in minutes
* ##### [diffInMonths()](#diffInMonths()) public
Get the difference in months
* ##### [diffInMonthsIgnoreTimezone()](#diffInMonthsIgnoreTimezone()) public
Get the difference in months ignoring the timezone. This means the months are calculated in the specified timezone without converting to UTC first. This prevents the day from changing which can change the month.
* ##### [diffInSeconds()](#diffInSeconds()) public
Get the difference in seconds
* ##### [diffInWeekdays()](#diffInWeekdays()) public
Get the difference in weekdays
* ##### [diffInWeekendDays()](#diffInWeekendDays()) public
Get the difference in weekend days using a filter
* ##### [diffInWeeks()](#diffInWeeks()) public
Get the difference in weeks
* ##### [diffInYears()](#diffInYears()) public
Get the difference in years
* ##### [disableLenientParsing()](#disableLenientParsing()) public static
Enables lenient parsing for locale formats.
* ##### [enableLenientParsing()](#enableLenientParsing()) public static
Enables lenient parsing for locale formats.
* ##### [endOfCentury()](#endOfCentury()) public
Resets the date to end of the century and time to 23:59:59
* ##### [endOfDay()](#endOfDay()) public
Resets the time to 23:59:59
* ##### [endOfDecade()](#endOfDecade()) public
Resets the date to end of the decade and time to 23:59:59
* ##### [endOfMonth()](#endOfMonth()) public
Resets the date to end of the month and time to 23:59:59
* ##### [endOfWeek()](#endOfWeek()) public
Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59
* ##### [endOfYear()](#endOfYear()) public
Resets the date to end of the year and time to 23:59:59
* ##### [eq()](#eq()) public
Determines if the instance is equal to another
* ##### [equals()](#equals()) public
Determines if the instance is equal to another
* ##### [farthest()](#farthest()) public
Get the farthest date from the instance.
* ##### [firstOfMonth()](#firstOfMonth()) public
Modify to the first occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the first day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [firstOfQuarter()](#firstOfQuarter()) public
Modify to the first occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the first day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [firstOfYear()](#firstOfYear()) public
Modify to the first occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the first day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [fromNow()](#fromNow()) public static
Convenience method for getting the remaining time from a given time.
* ##### [getDefaultLocale()](#getDefaultLocale()) public static
Gets the default locale.
* ##### [getDiffFormatter()](#getDiffFormatter()) public static
Get the difference formatter instance.
* ##### [getLastErrors()](#getLastErrors()) public static
Returns any errors or warnings that were found during the parsing of the last object created by this class.
* ##### [getTestNow()](#getTestNow()) public static
Get the test instance stored in Chronos
* ##### [getWeekEndsAt()](#getWeekEndsAt()) public static
Get the last day of week
* ##### [getWeekStartsAt()](#getWeekStartsAt()) public static
Get the first day of week
* ##### [getWeekendDays()](#getWeekendDays()) public static
Get weekend days
* ##### [greaterThan()](#greaterThan()) public
Determines if the instance is greater (after) than another
* ##### [greaterThanOrEquals()](#greaterThanOrEquals()) public
Determines if the instance is greater (after) than or equal to another
* ##### [gt()](#gt()) public
Determines if the instance is greater (after) than another
* ##### [gte()](#gte()) public
Determines if the instance is greater (after) than or equal to another
* ##### [hasRelativeKeywords()](#hasRelativeKeywords()) public static
Determine if there is a relative keyword in the time string, this is to create dates relative to now for test instances. e.g.: next tuesday
* ##### [hasTestNow()](#hasTestNow()) public static
Get whether or not Chronos has a test instance set.
* ##### [hour()](#hour()) public
Set the instance's hour
* ##### [i18nFormat()](#i18nFormat()) public
Returns a formatted string for this time object using the preferred format and language for the specified locale.
* ##### [instance()](#instance()) public static
Create a ChronosInterface instance from a DateTimeInterface one
* ##### [isBirthday()](#isBirthday()) public
Check if its the birthday. Compares the date/month values of the two dates.
* ##### [isFriday()](#isFriday()) public
Checks if this day is a Friday.
* ##### [isFuture()](#isFuture()) public
Determines if the instance is in the future, ie. greater (after) than now
* ##### [isLastMonth()](#isLastMonth()) public
Determines if the instance is within the last month
* ##### [isLastWeek()](#isLastWeek()) public
Determines if the instance is within the last week
* ##### [isLastYear()](#isLastYear()) public
Determines if the instance is within the last year
* ##### [isLeapYear()](#isLeapYear()) public
Determines if the instance is a leap year
* ##### [isMonday()](#isMonday()) public
Checks if this day is a Monday.
* ##### [isMutable()](#isMutable()) public
Check if instance of ChronosInterface is mutable.
* ##### [isNextMonth()](#isNextMonth()) public
Determines if the instance is within the next month
* ##### [isNextWeek()](#isNextWeek()) public
Determines if the instance is within the next week
* ##### [isNextYear()](#isNextYear()) public
Determines if the instance is within the next year
* ##### [isPast()](#isPast()) public
Determines if the instance is in the past, ie. less (before) than now
* ##### [isSameDay()](#isSameDay()) public
Checks if the passed in date is the same day as the instance current day.
* ##### [isSaturday()](#isSaturday()) public
Checks if this day is a Saturday.
* ##### [isSunday()](#isSunday()) public
Checks if this day is a Sunday.
* ##### [isThisMonth()](#isThisMonth()) public
Returns true if this object represents a date within the current month
* ##### [isThisWeek()](#isThisWeek()) public
Returns true if this object represents a date within the current week
* ##### [isThisYear()](#isThisYear()) public
Returns true if this object represents a date within the current year
* ##### [isThursday()](#isThursday()) public
Checks if this day is a Thursday.
* ##### [isToday()](#isToday()) public
Determines if the instance is today
* ##### [isTomorrow()](#isTomorrow()) public
Determines if the instance is tomorrow
* ##### [isTuesday()](#isTuesday()) public
Checks if this day is a Tuesday.
* ##### [isWednesday()](#isWednesday()) public
Checks if this day is a Wednesday.
* ##### [isWeekday()](#isWeekday()) public
Determines if the instance is a weekday
* ##### [isWeekend()](#isWeekend()) public
Determines if the instance is a weekend day
* ##### [isWithinNext()](#isWithinNext()) public
Returns true this instance will happen within the specified interval
* ##### [isYesterday()](#isYesterday()) public
Determines if the instance is yesterday
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns a string that should be serialized when converting this object to JSON
* ##### [lastOfMonth()](#lastOfMonth()) public
Modify to the last occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the last day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [lastOfQuarter()](#lastOfQuarter()) public
Modify to the last occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the last day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [lastOfYear()](#lastOfYear()) public
Modify to the last occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the last day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [lenientParsingEnabled()](#lenientParsingEnabled()) public static
Gets whether locale format parsing is set to lenient.
* ##### [lessThan()](#lessThan()) public
Determines if the instance is less (before) than another
* ##### [lessThanOrEquals()](#lessThanOrEquals()) public
Determines if the instance is less (before) or equal to another
* ##### [lt()](#lt()) public
Determines if the instance is less (before) than another
* ##### [lte()](#lte()) public
Determines if the instance is less (before) or equal to another
* ##### [max()](#max()) public
Get the maximum instance between a given instance (default now) and the current instance.
* ##### [maxValue()](#maxValue()) public static
Create a ChronosInterface instance for the greatest supported date.
* ##### [microsecond()](#microsecond()) public
Set the instance's microsecond
* ##### [min()](#min()) public
Get the minimum instance between a given instance (default now) and the current instance.
* ##### [minValue()](#minValue()) public static
Create a ChronosInterface instance for the lowest supported date.
* ##### [minute()](#minute()) public
Set the instance's minute
* ##### [modify()](#modify()) public @method
Overloaded to ignore time changes.
* ##### [month()](#month()) public
Set the instance's month
* ##### [ne()](#ne()) public
Determines if the instance is not equal to another
* ##### [next()](#next()) public
Modify to the next occurrence of a given day of the week. If no dayOfWeek is provided, modify to the next occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [nice()](#nice()) public
Returns a nicely formatted date string for this object.
* ##### [notEquals()](#notEquals()) public
Determines if the instance is not equal to another
* ##### [now()](#now()) public static
Get a ChronosInterface instance for the current date and time
* ##### [nthOfMonth()](#nthOfMonth()) public
Modify to the given occurrence of a given day of the week in the current month. If the calculated occurrence is outside the scope of the current month, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [nthOfQuarter()](#nthOfQuarter()) public
Modify to the given occurrence of a given day of the week in the current quarter. If the calculated occurrence is outside the scope of the current quarter, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [nthOfYear()](#nthOfYear()) public
Modify to the given occurrence of a given day of the week in the current year. If the calculated occurrence is outside the scope of the current year, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [parse()](#parse()) public static
Create a ChronosInterface instance from a string. This is an alias for the constructor that allows better fluent syntax as it allows you to do ChronosInterface::parse('Monday next week')->fn() rather than (new Chronos('Monday next week'))->fn()
* ##### [parseDate()](#parseDate()) public static
Returns a new Time object after parsing the provided $date string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
* ##### [parseDateTime()](#parseDateTime()) public static
Returns a new Time object after parsing the provided time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
* ##### [parseTime()](#parseTime()) public static
Returns a new Time object after parsing the provided $time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
* ##### [previous()](#previous()) public
Modify to the previous occurrence of a given day of the week. If no dayOfWeek is provided, modify to the previous occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [resetToStringFormat()](#resetToStringFormat()) public static
Resets the format used to the default when converting an instance of this type to a string
* ##### [safeCreateDateTimeZone()](#safeCreateDateTimeZone()) protected static
Creates a DateTimeZone from a string or a DateTimeZone
* ##### [second()](#second()) public
Set the instance's second
* ##### [secondsSinceMidnight()](#secondsSinceMidnight()) public
The number of seconds since midnight.
* ##### [secondsUntilEndOfDay()](#secondsUntilEndOfDay()) public
The number of seconds until 23:59:59.
* ##### [setDate()](#setDate()) public
Set the date to a different date.
* ##### [setDateTime()](#setDateTime()) public
Set the date and time all together
* ##### [setDefaultLocale()](#setDefaultLocale()) public static
Sets the default locale.
* ##### [setDiffFormatter()](#setDiffFormatter()) public static
Set the difference formatter instance.
* ##### [setJsonEncodeFormat()](#setJsonEncodeFormat()) public static
Sets the default format used when converting this object to JSON
* ##### [setTestNow()](#setTestNow()) public static
Set the test now used by Date and Time classes provided by Chronos
* ##### [setTime()](#setTime()) public
Modify the time on the Date.
* ##### [setTimeFromTimeString()](#setTimeFromTimeString()) public
Set the time by time string
* ##### [setTimestamp()](#setTimestamp()) public
Set the timestamp value and get a new object back.
* ##### [setTimezone()](#setTimezone()) public
Set the instance's timezone from a string or object
* ##### [setToStringFormat()](#setToStringFormat()) public static
Sets the default format used when type converting instances of this type to string
* ##### [setWeekEndsAt()](#setWeekEndsAt()) public static
Set the last day of week
* ##### [setWeekStartsAt()](#setWeekStartsAt()) public static
Set the first day of week
* ##### [setWeekendDays()](#setWeekendDays()) public static
Set weekend days
* ##### [startOfCentury()](#startOfCentury()) public
Resets the date to the first day of the century and the time to 00:00:00
* ##### [startOfDay()](#startOfDay()) public
Resets the time to 00:00:00
* ##### [startOfDecade()](#startOfDecade()) public
Resets the date to the first day of the decade and the time to 00:00:00
* ##### [startOfMonth()](#startOfMonth()) public
Resets the date to the first day of the month and the time to 00:00:00
* ##### [startOfWeek()](#startOfWeek()) public
Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00
* ##### [startOfYear()](#startOfYear()) public
Resets the date to the first day of the year and the time to 00:00:00
* ##### [stripRelativeTime()](#stripRelativeTime()) protected
Remove time components from strtotime relative strings.
* ##### [stripTime()](#stripTime()) protected
Removes the time components from an input string.
* ##### [sub()](#sub()) public
Subtract an Interval from a Date.
* ##### [subDay()](#subDay()) public
Remove a day from the instance
* ##### [subDays()](#subDays()) public
Remove days from the instance
* ##### [subHour()](#subHour()) public
Remove an hour from the instance
* ##### [subHours()](#subHours()) public
Remove hours from the instance
* ##### [subMinute()](#subMinute()) public
Remove a minute from the instance
* ##### [subMinutes()](#subMinutes()) public
Remove minutes from the instance
* ##### [subMonth()](#subMonth()) public
Remove a month from the instance
* ##### [subMonthWithOverflow()](#subMonthWithOverflow()) public
Remove a month with overflow from the instance.
* ##### [subMonths()](#subMonths()) public
Remove months from the instance.
* ##### [subMonthsWithOverflow()](#subMonthsWithOverflow()) public
Remove months with overflow from the instance.
* ##### [subSecond()](#subSecond()) public
Remove a second from the instance
* ##### [subSeconds()](#subSeconds()) public
Remove seconds from the instance
* ##### [subWeek()](#subWeek()) public
Remove a week from the instance
* ##### [subWeekday()](#subWeekday()) public
Remove a weekday from the instance
* ##### [subWeekdays()](#subWeekdays()) public
Remove weekdays from the instance
* ##### [subWeeks()](#subWeeks()) public
Remove weeks to the instance
* ##### [subYear()](#subYear()) public
Remove a year from the instance.
* ##### [subYearWithOverflow()](#subYearWithOverflow()) public
Remove a year with overflow from the instance
* ##### [subYears()](#subYears()) public
Remove years from the instance.
* ##### [subYearsWithOverflow()](#subYearsWithOverflow()) public
Remove years with overflow from the instance
* ##### [timeAgoInWords()](#timeAgoInWords()) public
Returns either a relative or a formatted absolute date depending on the difference between the current date and this object.
* ##### [timestamp()](#timestamp()) public
Set the instance's timestamp
* ##### [timezone()](#timezone()) public
Alias for setTimezone()
* ##### [toAtomString()](#toAtomString()) public
Format the instance as ATOM
* ##### [toCookieString()](#toCookieString()) public
Format the instance as COOKIE
* ##### [toDateString()](#toDateString()) public
Format the instance as date
* ##### [toDateTimeString()](#toDateTimeString()) public
Format the instance as date and time
* ##### [toDayDateTimeString()](#toDayDateTimeString()) public
Format the instance with day, date and time
* ##### [toFormattedDateString()](#toFormattedDateString()) public
Format the instance as a readable date
* ##### [toImmutable()](#toImmutable()) public
Create a new immutable instance from current mutable instance.
* ##### [toIso8601String()](#toIso8601String()) public
Format the instance as ISO8601
* ##### [toQuarter()](#toQuarter()) public
Returns the quarter
* ##### [toRfc1036String()](#toRfc1036String()) public
Format the instance as RFC1036
* ##### [toRfc1123String()](#toRfc1123String()) public
Format the instance as RFC1123
* ##### [toRfc2822String()](#toRfc2822String()) public
Format the instance as RFC2822
* ##### [toRfc3339String()](#toRfc3339String()) public
Format the instance as RFC3339
* ##### [toRfc822String()](#toRfc822String()) public
Format the instance as RFC822
* ##### [toRfc850String()](#toRfc850String()) public
Format the instance as RFC850
* ##### [toRssString()](#toRssString()) public
Format the instance as RSS
* ##### [toTimeString()](#toTimeString()) public
Format the instance as time
* ##### [toUnixString()](#toUnixString()) public
Returns a UNIX timestamp.
* ##### [toW3cString()](#toW3cString()) public
Format the instance as W3C
* ##### [toWeek()](#toWeek()) public
* ##### [today()](#today()) public static
Create a ChronosInterface instance for today
* ##### [tomorrow()](#tomorrow()) public static
Create a ChronosInterface instance for tomorrow
* ##### [tz()](#tz()) public
Alias for setTimezone()
* ##### [wasWithinLast()](#wasWithinLast()) public
Returns true this instance happened within the specified interval
* ##### [year()](#year()) public
Set the instance's year
* ##### [yesterday()](#yesterday()) public static
Create a ChronosInterface instance for yesterday
Method Detail
-------------
### \_\_construct() public
```
__construct(DateTimeInterface|string|int|null $time = 'now', DateTimeZone|string|null $tz = null)
```
Create a new FrozenDate instance.
You can specify the timezone for the $time parameter. This timezone will not be used in any future modifications to the Date instance.
The `$timezone` parameter is ignored if `$time` is a DateTimeInterface instance.
Date instances lack time components, however due to limitations in PHP's internal Datetime object the time will always be set to 00:00:00, and the timezone will always be the server local time. Normalizing the timezone allows for subtraction/addition to have deterministic results.
#### Parameters
`DateTimeInterface|string|int|null` $time optional Fixed or relative time
`DateTimeZone|string|null` $tz optional The timezone in which the date is taken. Ignored if `$time` is a DateTimeInterface instance.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns the data that should be displayed when debugging this object
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): string|int|boolDateTimeZone
```
Get a part of the ChronosInterface object
#### Parameters
`string` $name The property name to read.
#### Returns
`string|int|boolDateTimeZone`
#### Throws
`InvalidArgumentException`
### \_\_isset() public
```
__isset(string $name): bool
```
Check if an attribute exists on the object
#### Parameters
`string` $name The property name to check.
#### Returns
`bool`
### \_\_toString() public
```
__toString(): string
```
Format the instance as a string using the set format
#### Returns
`string`
### \_formatObject() protected
```
_formatObject(DateTimeDateTimeImmutable $date, array<int>|string|int $format, string|null $locale): string
```
Returns a translated and localized date string. Implements what IntlDateFormatter::formatObject() is in PHP 5.5+
#### Parameters
`DateTimeDateTimeImmutable` $date Date.
`array<int>|string|int` $format Format.
`string|null` $locale The locale name in which the date should be displayed.
#### Returns
`string`
### add() public
```
add(DateInterval $interval): static
```
Add an Interval to a Date
Any changes to the time will be ignored and reset to 00:00:00
#### Parameters
`DateInterval` $interval The interval to modify this date by.
#### Returns
`static`
### addDay() public
```
addDay(int $value = 1): static
```
Add a day to the instance
#### Parameters
`int` $value optional The number of days to add.
#### Returns
`static`
### addDays() public
```
addDays(int $value): static
```
Add days to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of days to add.
#### Returns
`static`
### addHour() public
```
addHour(int $value = 1): static
```
Add an hour to the instance
#### Parameters
`int` $value optional The number of hours to add.
#### Returns
`static`
### addHours() public
```
addHours(int $value): static
```
Add hours to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of hours to add.
#### Returns
`static`
### addMinute() public
```
addMinute(int $value = 1): static
```
Add a minute to the instance
#### Parameters
`int` $value optional The number of minutes to add.
#### Returns
`static`
### addMinutes() public
```
addMinutes(int $value): static
```
Add minutes to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of minutes to add.
#### Returns
`static`
### addMonth() public
```
addMonth(int $value = 1): static
```
Add a month to the instance.
Has the same behavior as `addMonths()`.
#### Parameters
`int` $value optional The number of months to add.
#### Returns
`static`
### addMonthWithOverflow() public
```
addMonthWithOverflow(int $value = 1): static
```
Add a month with overflow to the instance.
Has the same behavior as `addMonthsWithOverflow()`.
#### Parameters
`int` $value optional The number of months to add.
#### Returns
`static`
### addMonths() public
```
addMonths(int $value): static
```
Add months to the instance. Positive $value travels forward while negative $value travels into the past.
If the new date does not exist, the last day of the month is used instead instead of overflowing into the next month.
### Example:
```
(new Chronos('2015-01-03'))->addMonths(1); // Results in 2015-02-03
(new Chronos('2015-01-31'))->addMonths(1); // Results in 2015-02-28
```
#### Parameters
`int` $value The number of months to add.
#### Returns
`static`
### addMonthsWithOverflow() public
```
addMonthsWithOverflow(int $value): static
```
Add months with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
If the new date does not exist, the days overflow into the next month.
### Example:
```
(new Chronos('2012-01-30'))->addMonthsWithOverflow(1); // Results in 2013-03-01
```
#### Parameters
`int` $value The number of months to add.
#### Returns
`static`
### addSecond() public
```
addSecond(int $value = 1): static
```
Add a second to the instance
#### Parameters
`int` $value optional The number of seconds to add.
#### Returns
`static`
### addSeconds() public
```
addSeconds(int $value): static
```
Add seconds to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of seconds to add.
#### Returns
`static`
### addWeek() public
```
addWeek(int $value = 1): static
```
Add a week to the instance
#### Parameters
`int` $value optional The number of weeks to add.
#### Returns
`static`
### addWeekday() public
```
addWeekday(int $value = 1): static
```
Add a weekday to the instance
#### Parameters
`int` $value optional The number of weekdays to add.
#### Returns
`static`
### addWeekdays() public
```
addWeekdays(int $value): static
```
Add weekdays to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of weekdays to add.
#### Returns
`static`
### addWeeks() public
```
addWeeks(int $value): static
```
Add weeks to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of weeks to add.
#### Returns
`static`
### addYear() public
```
addYear(int $value = 1): static
```
Add a year to the instance
Has the same behavior as `addYears()`.
#### Parameters
`int` $value optional The number of years to add.
#### Returns
`static`
### addYearWithOverflow() public
```
addYearWithOverflow(int $value = 1): static
```
Add a year with overflow to the instance
Has the same behavior as `addYearsWithOverflow()`.
#### Parameters
`int` $value optional The number of years to add.
#### Returns
`static`
### addYears() public
```
addYears(int $value): static
```
Add years to the instance. Positive $value travel forward while negative $value travel into the past.
If the new date does not exist, the last day of the month is used instead instead of overflowing into the next month.
### Example:
```
(new Chronos('2015-01-03'))->addYears(1); // Results in 2016-01-03
(new Chronos('2012-02-29'))->addYears(1); // Results in 2013-02-28
```
#### Parameters
`int` $value The number of years to add.
#### Returns
`static`
### addYearsWithOverflow() public
```
addYearsWithOverflow(int $value): static
```
Add years with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
If the new date does not exist, the days overflow into the next month.
### Example:
```
(new Chronos('2012-02-29'))->addYearsWithOverflow(1); // Results in 2013-03-01
```
#### Parameters
`int` $value The number of years to add.
#### Returns
`static`
### average() public
```
average(Cake\Chronos\ChronosInterface $dt = null): static
```
Modify the current instance to the average of a given instance (default now) and the current instance.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt optional The instance to compare with.
#### Returns
`static`
### between() public
```
between(Cake\Chronos\ChronosInterface $dt1, Cake\Chronos\ChronosInterface $dt2, bool $equal = true): bool
```
Determines if the instance is between two others
#### Parameters
`Cake\Chronos\ChronosInterface` $dt1 The instance to compare with.
`Cake\Chronos\ChronosInterface` $dt2 The instance to compare with.
`bool` $equal optional Indicates if a > and < comparison should be used or <= or >=
#### Returns
`bool`
### closest() public
```
closest(Cake\Chronos\ChronosInterface $dt1, Cake\Chronos\ChronosInterface $dt2): static
```
Get the closest date from the instance.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt1 The instance to compare with.
`Cake\Chronos\ChronosInterface` $dt2 The instance to compare with.
#### Returns
`static`
### copy() public
```
copy(): static
```
Get a copy of the instance
#### Returns
`static`
### create() public static
```
create(int|null $year = null, int|null $month = null, int|null $day = null, int|null $hour = null, int|null $minute = null, int|null $second = null, int|null $microsecond = null, DateTimeZone|string|null $tz = null): static
```
Create a new ChronosInterface instance from a specific date and time.
If any of $year, $month or $day are set to null their now() values will be used.
If $hour is null it will be set to its now() value and the default values for $minute, $second and $microsecond will be their now() values. If $hour is not null then the default values for $minute, $second and $microsecond will be 0.
#### Parameters
`int|null` $year optional The year to create an instance with.
`int|null` $month optional The month to create an instance with.
`int|null` $day optional The day to create an instance with.
`int|null` $hour optional The hour to create an instance with.
`int|null` $minute optional The minute to create an instance with.
`int|null` $second optional The second to create an instance with.
`int|null` $microsecond optional The microsecond to create an instance with.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### createFromArray() public static
```
createFromArray((int|string)[] $values): static
```
Creates a ChronosInterface instance from an array of date and time values.
The 'year', 'month' and 'day' values must all be set for a date. The time values all default to 0.
The 'timezone' value can be any format supported by `\DateTimeZone`.
Allowed values:
* year
* month
* day
* hour
* minute
* second
* microsecond
* meridian ('am' or 'pm')
* timezone
#### Parameters
`(int|string)[]` $values Array of date and time values.
#### Returns
`static`
### createFromDate() public static
```
createFromDate(int|null $year = null, int|null $month = null, int|null $day = null, DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from just a date. The time portion is set to now.
#### Parameters
`int|null` $year optional The year to create an instance with.
`int|null` $month optional The month to create an instance with.
`int|null` $day optional The day to create an instance with.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### createFromFormat() public static
```
createFromFormat(string $format, string $time, DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from a specific format
#### Parameters
`string` $format The date() compatible format string.
`string` $time The formatted date string to interpret.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
#### Throws
`InvalidArgumentException`
### createFromTime() public static
```
createFromTime(int|null $hour = null, int|null $minute = null, int|null $second = null, int|null $microsecond = null, DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from just a time. The date portion is set to today.
#### Parameters
`int|null` $hour optional The hour to create an instance with.
`int|null` $minute optional The minute to create an instance with.
`int|null` $second optional The second to create an instance with.
`int|null` $microsecond optional The microsecond to create an instance with.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### createFromTimestamp() public static
```
createFromTimestamp(int $timestamp, DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from a timestamp
#### Parameters
`int` $timestamp The timestamp to create an instance from.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### createFromTimestampUTC() public static
```
createFromTimestampUTC(int $timestamp): static
```
Create a ChronosInterface instance from an UTC timestamp
#### Parameters
`int` $timestamp The UTC timestamp to create an instance from.
#### Returns
`static`
### day() public
```
day(int $value): static
```
Set the instance's day
#### Parameters
`int` $value The day value.
#### Returns
`static`
### diffFiltered() public
```
diffFiltered(Cake\Chronos\ChronosInterval $ci, callable $callback, Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference by the given interval using a filter callable
#### Parameters
`Cake\Chronos\ChronosInterval` $ci An interval to traverse by
`callable` $callback The callback to use for filtering.
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffForHumans() public
```
diffForHumans(Cake\Chronos\ChronosInterface|null $other = null, bool $absolute = false): string
```
Get the difference in a human readable format.
When comparing a value in the past to default now: 1 hour ago 5 months ago
When comparing a value in the future to default now: 1 hour from now 5 months from now
When comparing a value in the past to another value: 1 hour before 5 months before
When comparing a value in the future to another value: 1 hour after 5 months after
#### Parameters
`Cake\Chronos\ChronosInterface|null` $other optional The datetime to compare with.
`bool` $absolute optional removes time difference modifiers ago, after, etc
#### Returns
`string`
### diffFormatter() public static
```
diffFormatter(Cake\Chronos\DifferenceFormatterInterface|null $formatter = null): Cake\Chronos\DifferenceFormatterInterface
```
Get the difference formatter instance or overwrite the current one.
#### Parameters
`Cake\Chronos\DifferenceFormatterInterface|null` $formatter optional The formatter instance when setting.
#### Returns
`Cake\Chronos\DifferenceFormatterInterface`
### diffInDays() public
```
diffInDays(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in days
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInDaysFiltered() public
```
diffInDaysFiltered(callable $callback, Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in days using a filter callable
#### Parameters
`callable` $callback The callback to use for filtering.
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInHours() public
```
diffInHours(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in hours
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInHoursFiltered() public
```
diffInHoursFiltered(callable $callback, Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in hours using a filter callable
#### Parameters
`callable` $callback The callback to use for filtering.
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInMinutes() public
```
diffInMinutes(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in minutes
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInMonths() public
```
diffInMonths(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in months
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInMonthsIgnoreTimezone() public
```
diffInMonthsIgnoreTimezone(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in months ignoring the timezone. This means the months are calculated in the specified timezone without converting to UTC first. This prevents the day from changing which can change the month.
For example, if comparing `2019-06-01 Asia/Tokyo` and `2019-10-01 Asia/Tokyo`, the result would be 4 months instead of 3 when using normal `DateTime::diff()`.
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInSeconds() public
```
diffInSeconds(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in seconds
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInWeekdays() public
```
diffInWeekdays(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in weekdays
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInWeekendDays() public
```
diffInWeekendDays(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in weekend days using a filter
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInWeeks() public
```
diffInWeeks(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in weeks
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInYears() public
```
diffInYears(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in years
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### disableLenientParsing() public static
```
disableLenientParsing(): void
```
Enables lenient parsing for locale formats.
#### Returns
`void`
### enableLenientParsing() public static
```
enableLenientParsing(): void
```
Enables lenient parsing for locale formats.
#### Returns
`void`
### endOfCentury() public
```
endOfCentury(): static
```
Resets the date to end of the century and time to 23:59:59
#### Returns
`static`
### endOfDay() public
```
endOfDay(): static
```
Resets the time to 23:59:59
#### Returns
`static`
### endOfDecade() public
```
endOfDecade(): static
```
Resets the date to end of the decade and time to 23:59:59
#### Returns
`static`
### endOfMonth() public
```
endOfMonth(): static
```
Resets the date to end of the month and time to 23:59:59
#### Returns
`static`
### endOfWeek() public
```
endOfWeek(): static
```
Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59
#### Returns
`static`
### endOfYear() public
```
endOfYear(): static
```
Resets the date to end of the year and time to 23:59:59
#### Returns
`static`
### eq() public
```
eq(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
equals ### equals() public
```
equals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### farthest() public
```
farthest(Cake\Chronos\ChronosInterface $dt1, Cake\Chronos\ChronosInterface $dt2): static
```
Get the farthest date from the instance.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt1 The instance to compare with.
`Cake\Chronos\ChronosInterface` $dt2 The instance to compare with.
#### Returns
`static`
### firstOfMonth() public
```
firstOfMonth(int|null $dayOfWeek = null): mixed
```
Modify to the first occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the first day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### firstOfQuarter() public
```
firstOfQuarter(int|null $dayOfWeek = null): mixed
```
Modify to the first occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the first day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### firstOfYear() public
```
firstOfYear(int|null $dayOfWeek = null): mixed
```
Modify to the first occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the first day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### fromNow() public static
```
fromNow(DateTimeDateTimeImmutable $datetime): DateInterval|bool
```
Convenience method for getting the remaining time from a given time.
#### Parameters
`DateTimeDateTimeImmutable` $datetime The date to get the remaining time from.
#### Returns
`DateInterval|bool`
### getDefaultLocale() public static
```
getDefaultLocale(): string|null
```
Gets the default locale.
#### Returns
`string|null`
### getDiffFormatter() public static
```
getDiffFormatter(): Cake\Chronos\DifferenceFormatterInterface
```
Get the difference formatter instance.
#### Returns
`Cake\Chronos\DifferenceFormatterInterface`
### getLastErrors() public static
```
getLastErrors(): array
```
Returns any errors or warnings that were found during the parsing of the last object created by this class.
#### Returns
`array`
### getTestNow() public static
```
getTestNow(): Cake\Chronos\ChronosInterface|null
```
Get the test instance stored in Chronos
#### Returns
`Cake\Chronos\ChronosInterface|null`
#### See Also
\Cake\Chronos\Chronos::getTestNow() ### getWeekEndsAt() public static
```
getWeekEndsAt(): int
```
Get the last day of week
#### Returns
`int`
### getWeekStartsAt() public static
```
getWeekStartsAt(): int
```
Get the first day of week
#### Returns
`int`
### getWeekendDays() public static
```
getWeekendDays(): array
```
Get weekend days
#### Returns
`array`
### greaterThan() public
```
greaterThan(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### greaterThanOrEquals() public
```
greaterThanOrEquals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### gt() public
```
gt(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
greaterThan ### gte() public
```
gte(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
greaterThanOrEquals ### hasRelativeKeywords() public static
```
hasRelativeKeywords(string|null $time): bool
```
Determine if there is a relative keyword in the time string, this is to create dates relative to now for test instances. e.g.: next tuesday
#### Parameters
`string|null` $time The time string to check.
#### Returns
`bool`
### hasTestNow() public static
```
hasTestNow(): bool
```
Get whether or not Chronos has a test instance set.
#### Returns
`bool`
#### See Also
\Cake\Chronos\Chronos::hasTestNow() ### hour() public
```
hour(int $value): static
```
Set the instance's hour
#### Parameters
`int` $value The hour value.
#### Returns
`static`
### i18nFormat() public
```
i18nFormat(string|int|null $format = null, DateTimeZone|string|null $timezone = null, string|null $locale = null): string|int
```
Returns a formatted string for this time object using the preferred format and language for the specified locale.
It is possible to specify the desired format for the string to be displayed. You can either pass `IntlDateFormatter` constants as the first argument of this function, or pass a full ICU date formatting string as specified in the following resource: <https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax>.
Additional to `IntlDateFormatter` constants and date formatting string you can use Time::UNIX\_TIMESTAMP\_FORMAT to get a unix timestamp
### Examples
```
$time = new Time('2014-04-20 22:10');
$time->i18nFormat(); // outputs '4/20/14, 10:10 PM' for the en-US locale
$time->i18nFormat(\IntlDateFormatter::FULL); // Use the full date and time format
$time->i18nFormat([\IntlDateFormatter::FULL, \IntlDateFormatter::SHORT]); // Use full date but short time format
$time->i18nFormat('yyyy-MM-dd HH:mm:ss'); // outputs '2014-04-20 22:10'
$time->i18nFormat(Time::UNIX_TIMESTAMP_FORMAT); // outputs '1398031800'
```
You can control the default format used through `Time::setToStringFormat()`.
You can read about the available IntlDateFormatter constants at <https://secure.php.net/manual/en/class.intldateformatter.php>
If you need to display the date in a different timezone than the one being used for this Time object without altering its internal state, you can pass a timezone string or object as the second parameter.
Finally, should you need to use a different locale for displaying this time object, pass a locale string as the third parameter to this function.
### Examples
```
$time = new Time('2014-04-20 22:10');
$time->i18nFormat(null, null, 'de-DE');
$time->i18nFormat(\IntlDateFormatter::FULL, 'Europe/Berlin', 'de-DE');
```
You can control the default locale used through `Time::setDefaultLocale()`. If empty, the default will be taken from the `intl.default_locale` ini config.
#### Parameters
`string|int|null` $format optional Format string.
`DateTimeZone|string|null` $timezone optional Timezone string or DateTimeZone object in which the date will be displayed. The timezone stored for this object will not be changed.
`string|null` $locale optional The locale name in which the date should be displayed (e.g. pt-BR)
#### Returns
`string|int`
### instance() public static
```
instance(DateTimeInterface $dt): static
```
Create a ChronosInterface instance from a DateTimeInterface one
#### Parameters
`DateTimeInterface` $dt The datetime instance to convert.
#### Returns
`static`
### isBirthday() public
```
isBirthday(Cake\Chronos\ChronosInterface $dt): bool
```
Check if its the birthday. Compares the date/month values of the two dates.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### isFriday() public
```
isFriday(): bool
```
Checks if this day is a Friday.
#### Returns
`bool`
### isFuture() public
```
isFuture(): bool
```
Determines if the instance is in the future, ie. greater (after) than now
#### Returns
`bool`
### isLastMonth() public
```
isLastMonth(): bool
```
Determines if the instance is within the last month
#### Returns
`bool`
### isLastWeek() public
```
isLastWeek(): bool
```
Determines if the instance is within the last week
#### Returns
`bool`
### isLastYear() public
```
isLastYear(): bool
```
Determines if the instance is within the last year
#### Returns
`bool`
### isLeapYear() public
```
isLeapYear(): bool
```
Determines if the instance is a leap year
#### Returns
`bool`
### isMonday() public
```
isMonday(): bool
```
Checks if this day is a Monday.
#### Returns
`bool`
### isMutable() public
```
isMutable(): bool
```
Check if instance of ChronosInterface is mutable.
#### Returns
`bool`
### isNextMonth() public
```
isNextMonth(): bool
```
Determines if the instance is within the next month
#### Returns
`bool`
### isNextWeek() public
```
isNextWeek(): bool
```
Determines if the instance is within the next week
#### Returns
`bool`
### isNextYear() public
```
isNextYear(): bool
```
Determines if the instance is within the next year
#### Returns
`bool`
### isPast() public
```
isPast(): bool
```
Determines if the instance is in the past, ie. less (before) than now
#### Returns
`bool`
### isSameDay() public
```
isSameDay(Cake\Chronos\ChronosInterface $dt): bool
```
Checks if the passed in date is the same day as the instance current day.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to check against.
#### Returns
`bool`
### isSaturday() public
```
isSaturday(): bool
```
Checks if this day is a Saturday.
#### Returns
`bool`
### isSunday() public
```
isSunday(): bool
```
Checks if this day is a Sunday.
#### Returns
`bool`
### isThisMonth() public
```
isThisMonth(): bool
```
Returns true if this object represents a date within the current month
#### Returns
`bool`
### isThisWeek() public
```
isThisWeek(): bool
```
Returns true if this object represents a date within the current week
#### Returns
`bool`
### isThisYear() public
```
isThisYear(): bool
```
Returns true if this object represents a date within the current year
#### Returns
`bool`
### isThursday() public
```
isThursday(): bool
```
Checks if this day is a Thursday.
#### Returns
`bool`
### isToday() public
```
isToday(): bool
```
Determines if the instance is today
#### Returns
`bool`
### isTomorrow() public
```
isTomorrow(): bool
```
Determines if the instance is tomorrow
#### Returns
`bool`
### isTuesday() public
```
isTuesday(): bool
```
Checks if this day is a Tuesday.
#### Returns
`bool`
### isWednesday() public
```
isWednesday(): bool
```
Checks if this day is a Wednesday.
#### Returns
`bool`
### isWeekday() public
```
isWeekday(): bool
```
Determines if the instance is a weekday
#### Returns
`bool`
### isWeekend() public
```
isWeekend(): bool
```
Determines if the instance is a weekend day
#### Returns
`bool`
### isWithinNext() public
```
isWithinNext(string|int $timeInterval): bool
```
Returns true this instance will happen within the specified interval
#### Parameters
`string|int` $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
#### Returns
`bool`
### isYesterday() public
```
isYesterday(): bool
```
Determines if the instance is yesterday
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): string|int
```
Returns a string that should be serialized when converting this object to JSON
#### Returns
`string|int`
### lastOfMonth() public
```
lastOfMonth(int|null $dayOfWeek = null): mixed
```
Modify to the last occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the last day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### lastOfQuarter() public
```
lastOfQuarter(int|null $dayOfWeek = null): mixed
```
Modify to the last occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the last day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### lastOfYear() public
```
lastOfYear(int|null $dayOfWeek = null): mixed
```
Modify to the last occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the last day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### lenientParsingEnabled() public static
```
lenientParsingEnabled(): bool
```
Gets whether locale format parsing is set to lenient.
#### Returns
`bool`
### lessThan() public
```
lessThan(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### lessThanOrEquals() public
```
lessThanOrEquals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### lt() public
```
lt(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
lessThan ### lte() public
```
lte(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
lessThanOrEquals ### max() public
```
max(Cake\Chronos\ChronosInterface|null $dt = null): static
```
Get the maximum instance between a given instance (default now) and the current instance.
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to compare with.
#### Returns
`static`
### maxValue() public static
```
maxValue(): Cake\Chronos\ChronosInterface
```
Create a ChronosInterface instance for the greatest supported date.
#### Returns
`Cake\Chronos\ChronosInterface`
### microsecond() public
```
microsecond(int $value): static
```
Set the instance's microsecond
#### Parameters
`int` $value The microsecond value.
#### Returns
`static`
### min() public
```
min(Cake\Chronos\ChronosInterface|null $dt = null): static
```
Get the minimum instance between a given instance (default now) and the current instance.
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to compare with.
#### Returns
`static`
### minValue() public static
```
minValue(): Cake\Chronos\ChronosInterface
```
Create a ChronosInterface instance for the lowest supported date.
#### Returns
`Cake\Chronos\ChronosInterface`
### minute() public
```
minute(int $value): static
```
Set the instance's minute
#### Parameters
`int` $value The minute value.
#### Returns
`static`
### modify() public @method
```
modify(string $relative): Cake\Chronos\ChronosInterface
```
Overloaded to ignore time changes.
Changing any aspect of the time will be ignored, and the resulting object will have its time frozen to 00:00:00.
#### Parameters
`string` $relative #### Returns
`Cake\Chronos\ChronosInterface`
### month() public
```
month(int $value): static
```
Set the instance's month
#### Parameters
`int` $value The month value.
#### Returns
`static`
### ne() public
```
ne(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is not equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
notEquals ### next() public
```
next(int|null $dayOfWeek = null): mixed
```
Modify to the next occurrence of a given day of the week. If no dayOfWeek is provided, modify to the next occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### nice() public
```
nice(DateTimeZone|string|null $timezone = null, string|null $locale = null): string
```
Returns a nicely formatted date string for this object.
The format to be used is stored in the static property `Time::niceFormat`.
#### Parameters
`DateTimeZone|string|null` $timezone optional Timezone string or DateTimeZone object in which the date will be displayed. The timezone stored for this object will not be changed.
`string|null` $locale optional The locale name in which the date should be displayed (e.g. pt-BR)
#### Returns
`string`
### notEquals() public
```
notEquals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is not equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### now() public static
```
now(DateTimeZone|string|null $tz): static
```
Get a ChronosInterface instance for the current date and time
#### Parameters
`DateTimeZone|string|null` $tz The DateTimeZone object or timezone name.
#### Returns
`static`
### nthOfMonth() public
```
nthOfMonth(int $nth, int $dayOfWeek): mixed
```
Modify to the given occurrence of a given day of the week in the current month. If the calculated occurrence is outside the scope of the current month, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int` $nth The offset to use.
`int` $dayOfWeek The day of the week to move to.
#### Returns
`mixed`
### nthOfQuarter() public
```
nthOfQuarter(int $nth, int $dayOfWeek): mixed
```
Modify to the given occurrence of a given day of the week in the current quarter. If the calculated occurrence is outside the scope of the current quarter, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int` $nth The offset to use.
`int` $dayOfWeek The day of the week to move to.
#### Returns
`mixed`
### nthOfYear() public
```
nthOfYear(int $nth, int $dayOfWeek): mixed
```
Modify to the given occurrence of a given day of the week in the current year. If the calculated occurrence is outside the scope of the current year, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int` $nth The offset to use.
`int` $dayOfWeek The day of the week to move to.
#### Returns
`mixed`
### parse() public static
```
parse(DateTimeInterface|string|int $time = 'now', DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from a string. This is an alias for the constructor that allows better fluent syntax as it allows you to do ChronosInterface::parse('Monday next week')->fn() rather than (new Chronos('Monday next week'))->fn()
#### Parameters
`DateTimeInterface|string|int` $time optional The strtotime compatible string to parse
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name.
#### Returns
`static`
### parseDate() public static
```
parseDate(string $date, array|string|int|null $format = null): static|null
```
Returns a new Time object after parsing the provided $date string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
When no $format is provided, the `wordFormat` format will be used.
If it was impossible to parse the provided time, null will be returned.
Example:
```
$time = Time::parseDate('10/13/2013');
$time = Time::parseDate('13 Oct, 2013', 'dd MMM, y');
$time = Time::parseDate('13 Oct, 2013', IntlDateFormatter::SHORT);
```
#### Parameters
`string` $date The date string to parse.
`array|string|int|null` $format optional Any format accepted by IntlDateFormatter.
#### Returns
`static|null`
### parseDateTime() public static
```
parseDateTime(string $time, array<int>|string|null $format = null, DateTimeZone|string|null $tz = null): static|null
```
Returns a new Time object after parsing the provided time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
When no $format is provided, the `toString` format will be used.
Unlike DateTime, the time zone of the returned instance is always converted to `$tz` (default time zone if null) even if the `$time` string specified a time zone. This is a limitation of IntlDateFormatter.
If it was impossible to parse the provided time, null will be returned.
Example:
```
$time = Time::parseDateTime('10/13/2013 12:54am');
$time = Time::parseDateTime('13 Oct, 2013 13:54', 'dd MMM, y H:mm');
$time = Time::parseDateTime('10/10/2015', [IntlDateFormatter::SHORT, IntlDateFormatter::NONE]);
```
#### Parameters
`string` $time The time string to parse.
`array<int>|string|null` $format optional Any format accepted by IntlDateFormatter.
`DateTimeZone|string|null` $tz optional The timezone for the instance
#### Returns
`static|null`
### parseTime() public static
```
parseTime(string $time, string|int|null $format = null): static|null
```
Returns a new Time object after parsing the provided $time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
When no $format is provided, the IntlDateFormatter::SHORT format will be used.
If it was impossible to parse the provided time, null will be returned.
Example:
```
$time = Time::parseTime('11:23pm');
```
#### Parameters
`string` $time The time string to parse.
`string|int|null` $format optional Any format accepted by IntlDateFormatter.
#### Returns
`static|null`
### previous() public
```
previous(int|null $dayOfWeek = null): mixed
```
Modify to the previous occurrence of a given day of the week. If no dayOfWeek is provided, modify to the previous occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### resetToStringFormat() public static
```
resetToStringFormat(): void
```
Resets the format used to the default when converting an instance of this type to a string
#### Returns
`void`
### safeCreateDateTimeZone() protected static
```
safeCreateDateTimeZone(DateTimeZone|string|null $object): DateTimeZone
```
Creates a DateTimeZone from a string or a DateTimeZone
#### Parameters
`DateTimeZone|string|null` $object The value to convert.
#### Returns
`DateTimeZone`
#### Throws
`InvalidArgumentException`
### second() public
```
second(int $value): static
```
Set the instance's second
#### Parameters
`int` $value The seconds value.
#### Returns
`static`
### secondsSinceMidnight() public
```
secondsSinceMidnight(): int
```
The number of seconds since midnight.
#### Returns
`int`
### secondsUntilEndOfDay() public
```
secondsUntilEndOfDay(): int
```
The number of seconds until 23:59:59.
#### Returns
`int`
### setDate() public
```
setDate(int $year, int $month, int $day): static
```
Set the date to a different date.
Workaround for a PHP bug related to the first day of a month
#### Parameters
`int` $year The year to set.
`int` $month The month to set.
`int` $day The day to set.
#### Returns
`static`
### setDateTime() public
```
setDateTime(int $year, int $month, int $day, int $hour, int $minute, int $second = 0): static
```
Set the date and time all together
#### Parameters
`int` $year The year to set.
`int` $month The month to set.
`int` $day The day to set.
`int` $hour The hour to set.
`int` $minute The minute to set.
`int` $second optional The second to set.
#### Returns
`static`
### setDefaultLocale() public static
```
setDefaultLocale(string|null $locale = null): void
```
Sets the default locale.
Set to null to use IntlDateFormatter default.
#### Parameters
`string|null` $locale optional The default locale string to be used.
#### Returns
`void`
### setDiffFormatter() public static
```
setDiffFormatter(Cake\Chronos\DifferenceFormatterInterface $formatter): void
```
Set the difference formatter instance.
#### Parameters
`Cake\Chronos\DifferenceFormatterInterface` $formatter The formatter instance when setting.
#### Returns
`void`
### setJsonEncodeFormat() public static
```
setJsonEncodeFormat(Closure|array|string|int $format): void
```
Sets the default format used when converting this object to JSON
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
Alternatively, the format can provide a callback. In this case, the callback can receive this datetime object and return a formatted string.
#### Parameters
`Closure|array|string|int` $format #### Returns
`void`
### setTestNow() public static
```
setTestNow(Cake\Chronos\ChronosInterface|string|null $testNow = null): void
```
Set the test now used by Date and Time classes provided by Chronos
#### Parameters
`Cake\Chronos\ChronosInterface|string|null` $testNow optional The instance to use for all future instances.
#### Returns
`void`
#### See Also
\Cake\Chronos\Chronos::setTestNow() ### setTime() public
```
setTime(int $hours, int $minutes, int $seconds = null, int $microseconds = null): static
```
Modify the time on the Date.
This method ignores all inputs and forces all inputs to 0.
#### Parameters
`int` $hours The hours to set (ignored)
`int` $minutes The minutes to set (ignored)
`int` $seconds optional The seconds to set (ignored)
`int` $microseconds optional The microseconds to set (ignored)
#### Returns
`static`
### setTimeFromTimeString() public
```
setTimeFromTimeString(string $time): static
```
Set the time by time string
#### Parameters
`string` $time Time as string.
#### Returns
`static`
### setTimestamp() public
```
setTimestamp(int $value): static
```
Set the timestamp value and get a new object back.
This method will discard the time aspects of the timestamp and only apply the date portions
#### Parameters
`int` $value The timestamp value to set.
#### Returns
`static`
### setTimezone() public
```
setTimezone(DateTimeZone|string $value): static
```
Set the instance's timezone from a string or object
Timezones have no effect on calendar dates.
#### Parameters
`DateTimeZone|string` $value The DateTimeZone object or timezone name to use.
#### Returns
`static`
### setToStringFormat() public static
```
setToStringFormat(string $format): void
```
Sets the default format used when type converting instances of this type to string
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
#### Parameters
`string` $format Format.
#### Returns
`void`
### setWeekEndsAt() public static
```
setWeekEndsAt(int $day): void
```
Set the last day of week
#### Parameters
`int` $day The day the week ends with.
#### Returns
`void`
### setWeekStartsAt() public static
```
setWeekStartsAt(int $day): void
```
Set the first day of week
#### Parameters
`int` $day The day the week starts with.
#### Returns
`void`
### setWeekendDays() public static
```
setWeekendDays(array $days): void
```
Set weekend days
#### Parameters
`array` $days Which days are 'weekends'.
#### Returns
`void`
### startOfCentury() public
```
startOfCentury(): static
```
Resets the date to the first day of the century and the time to 00:00:00
#### Returns
`static`
### startOfDay() public
```
startOfDay(): static
```
Resets the time to 00:00:00
#### Returns
`static`
### startOfDecade() public
```
startOfDecade(): static
```
Resets the date to the first day of the decade and the time to 00:00:00
#### Returns
`static`
### startOfMonth() public
```
startOfMonth(): static
```
Resets the date to the first day of the month and the time to 00:00:00
#### Returns
`static`
### startOfWeek() public
```
startOfWeek(): static
```
Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00
#### Returns
`static`
### startOfYear() public
```
startOfYear(): static
```
Resets the date to the first day of the year and the time to 00:00:00
#### Returns
`static`
### stripRelativeTime() protected
```
stripRelativeTime(string $time): string
```
Remove time components from strtotime relative strings.
#### Parameters
`string` $time The input expression
#### Returns
`string`
### stripTime() protected
```
stripTime(DateTimeDateTimeImmutable|string|int|null $time, DateTimeZone|null $tz): string
```
Removes the time components from an input string.
Used to ensure constructed objects always lack time.
#### Parameters
`DateTimeDateTimeImmutable|string|int|null` $time The input time. Integer values will be assumed to be in UTC. The 'now' and '' values will use the current local time.
`DateTimeZone|null` $tz The timezone in which the date is taken
#### Returns
`string`
### sub() public
```
sub(DateInterval $interval): static
```
Subtract an Interval from a Date.
Any changes to the time will be ignored and reset to 00:00:00
#### Parameters
`DateInterval` $interval The interval to modify this date by.
#### Returns
`static`
### subDay() public
```
subDay(int $value = 1): static
```
Remove a day from the instance
#### Parameters
`int` $value optional The number of days to remove.
#### Returns
`static`
### subDays() public
```
subDays(int $value): static
```
Remove days from the instance
#### Parameters
`int` $value The number of days to remove.
#### Returns
`static`
### subHour() public
```
subHour(int $value = 1): static
```
Remove an hour from the instance
#### Parameters
`int` $value optional The number of hours to remove.
#### Returns
`static`
### subHours() public
```
subHours(int $value): static
```
Remove hours from the instance
#### Parameters
`int` $value The number of hours to remove.
#### Returns
`static`
### subMinute() public
```
subMinute(int $value = 1): static
```
Remove a minute from the instance
#### Parameters
`int` $value optional The number of minutes to remove.
#### Returns
`static`
### subMinutes() public
```
subMinutes(int $value): static
```
Remove minutes from the instance
#### Parameters
`int` $value The number of minutes to remove.
#### Returns
`static`
### subMonth() public
```
subMonth(int $value = 1): static
```
Remove a month from the instance
Has the same behavior as `addMonths()`.
#### Parameters
`int` $value optional The number of months to remove.
#### Returns
`static`
### subMonthWithOverflow() public
```
subMonthWithOverflow(int $value = 1): static
```
Remove a month with overflow from the instance.
Has the same behavior as `addMonthsWithOverflow()`.
#### Parameters
`int` $value optional The number of months to remove.
#### Returns
`static`
### subMonths() public
```
subMonths(int $value): static
```
Remove months from the instance.
Has the same behavior as `addMonths()`.
#### Parameters
`int` $value The number of months to remove.
#### Returns
`static`
### subMonthsWithOverflow() public
```
subMonthsWithOverflow(int $value): static
```
Remove months with overflow from the instance.
Has the same behavior as `addMonthsWithOverflow()`.
#### Parameters
`int` $value The number of months to remove.
#### Returns
`static`
### subSecond() public
```
subSecond(int $value = 1): static
```
Remove a second from the instance
#### Parameters
`int` $value optional The number of seconds to remove.
#### Returns
`static`
### subSeconds() public
```
subSeconds(int $value): static
```
Remove seconds from the instance
#### Parameters
`int` $value The number of seconds to remove.
#### Returns
`static`
### subWeek() public
```
subWeek(int $value = 1): static
```
Remove a week from the instance
#### Parameters
`int` $value optional The number of weeks to remove.
#### Returns
`static`
### subWeekday() public
```
subWeekday(int $value = 1): static
```
Remove a weekday from the instance
#### Parameters
`int` $value optional The number of weekdays to remove.
#### Returns
`static`
### subWeekdays() public
```
subWeekdays(int $value): static
```
Remove weekdays from the instance
#### Parameters
`int` $value The number of weekdays to remove.
#### Returns
`static`
### subWeeks() public
```
subWeeks(int $value): static
```
Remove weeks to the instance
#### Parameters
`int` $value The number of weeks to remove.
#### Returns
`static`
### subYear() public
```
subYear(int $value = 1): static
```
Remove a year from the instance.
Has the same behavior as `addYears()`.
#### Parameters
`int` $value optional The number of years to remove.
#### Returns
`static`
### subYearWithOverflow() public
```
subYearWithOverflow(int $value = 1): static
```
Remove a year with overflow from the instance
Has the same behavior as `addYearsWithOverflow()`.
#### Parameters
`int` $value optional The number of years to remove.
#### Returns
`static`
### subYears() public
```
subYears(int $value): static
```
Remove years from the instance.
Has the same behavior as `addYears()`.
#### Parameters
`int` $value The number of years to remove.
#### Returns
`static`
### subYearsWithOverflow() public
```
subYearsWithOverflow(int $value): static
```
Remove years with overflow from the instance
Has the same behavior as `addYearsWithOverflow()`.
#### Parameters
`int` $value The number of years to remove.
#### Returns
`static`
### timeAgoInWords() public
```
timeAgoInWords(array<string, mixed> $options = []): string
```
Returns either a relative or a formatted absolute date depending on the difference between the current date and this object.
### Options:
* `from` => another Date object representing the "now" date
* `format` => a fall back format if the relative time is longer than the duration specified by end
* `accuracy` => Specifies how accurate the date should be described (array)
+ year => The format if years > 0 (default "day")
+ month => The format if months > 0 (default "day")
+ week => The format if weeks > 0 (default "day")
+ day => The format if weeks > 0 (default "day")
* `end` => The end of relative date telling
* `relativeString` => The printf compatible string when outputting relative date
* `absoluteString` => The printf compatible string when outputting absolute date
* `timezone` => The user timezone the timestamp should be formatted in.
Relative dates look something like this:
* 3 weeks, 4 days ago
* 1 day ago
Default date formatting is d/M/YY e.g: on 18/2/09. Formatting is done internally using `i18nFormat`, see the method for the valid formatting strings.
The returned string includes 'ago' or 'on' and assumes you'll properly add a word like 'Posted ' before the function output.
NOTE: If the difference is one week or more, the lowest level of accuracy is day.
#### Parameters
`array<string, mixed>` $options optional Array of options.
#### Returns
`string`
### timestamp() public
```
timestamp(int $value): static
```
Set the instance's timestamp
#### Parameters
`int` $value The timestamp value to set.
#### Returns
`static`
### timezone() public
```
timezone(DateTimeZone|string $value): static
```
Alias for setTimezone()
Timezones have no effect on calendar dates.
#### Parameters
`DateTimeZone|string` $value The DateTimeZone object or timezone name to use.
#### Returns
`static`
### toAtomString() public
```
toAtomString(): string
```
Format the instance as ATOM
#### Returns
`string`
### toCookieString() public
```
toCookieString(): string
```
Format the instance as COOKIE
#### Returns
`string`
### toDateString() public
```
toDateString(): string
```
Format the instance as date
#### Returns
`string`
### toDateTimeString() public
```
toDateTimeString(): string
```
Format the instance as date and time
#### Returns
`string`
### toDayDateTimeString() public
```
toDayDateTimeString(): string
```
Format the instance with day, date and time
#### Returns
`string`
### toFormattedDateString() public
```
toFormattedDateString(): string
```
Format the instance as a readable date
#### Returns
`string`
### toImmutable() public
```
toImmutable(): Cake\Chronos\Date
```
Create a new immutable instance from current mutable instance.
#### Returns
`Cake\Chronos\Date`
### toIso8601String() public
```
toIso8601String(): string
```
Format the instance as ISO8601
#### Returns
`string`
### toQuarter() public
```
toQuarter(bool $range = false): int|array
```
Returns the quarter
#### Parameters
`bool` $range optional Range.
#### Returns
`int|array`
### toRfc1036String() public
```
toRfc1036String(): string
```
Format the instance as RFC1036
#### Returns
`string`
### toRfc1123String() public
```
toRfc1123String(): string
```
Format the instance as RFC1123
#### Returns
`string`
### toRfc2822String() public
```
toRfc2822String(): string
```
Format the instance as RFC2822
#### Returns
`string`
### toRfc3339String() public
```
toRfc3339String(): string
```
Format the instance as RFC3339
#### Returns
`string`
### toRfc822String() public
```
toRfc822String(): string
```
Format the instance as RFC822
#### Returns
`string`
### toRfc850String() public
```
toRfc850String(): string
```
Format the instance as RFC850
#### Returns
`string`
### toRssString() public
```
toRssString(): string
```
Format the instance as RSS
#### Returns
`string`
### toTimeString() public
```
toTimeString(): string
```
Format the instance as time
#### Returns
`string`
### toUnixString() public
```
toUnixString(): string
```
Returns a UNIX timestamp.
#### Returns
`string`
### toW3cString() public
```
toW3cString(): string
```
Format the instance as W3C
#### Returns
`string`
### toWeek() public
```
toWeek(): int
```
#### Returns
`int`
### today() public static
```
today(DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance for today
#### Parameters
`DateTimeZone|string|null` $tz optional The timezone to use.
#### Returns
`static`
### tomorrow() public static
```
tomorrow(DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance for tomorrow
#### Parameters
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### tz() public
```
tz(DateTimeZone|string $value): static
```
Alias for setTimezone()
Timezones have no effect on calendar dates.
#### Parameters
`DateTimeZone|string` $value The DateTimeZone object or timezone name to use.
#### Returns
`static`
### wasWithinLast() public
```
wasWithinLast(string|int $timeInterval): bool
```
Returns true this instance happened within the specified interval
#### Parameters
`string|int` $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
#### Returns
`bool`
### year() public
```
year(int $value): static
```
Set the instance's year
#### Parameters
`int` $value The year value.
#### Returns
`static`
### yesterday() public static
```
yesterday(DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance for yesterday
#### Parameters
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
Property Detail
---------------
### $\_formatters protected static
In-memory cache of date formatters
#### Type
`arrayIntlDateFormatter>`
### $\_jsonEncodeFormat protected static
The format to use when converting this object to JSON.
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
#### Type
`Closure|array<int>|string|int`
### $\_lastErrors protected static
Holds the last error generated by createFromFormat
#### Type
`array`
### $\_toStringFormat protected static
The format to use when formatting a time using `Cake\I18n\Date::i18nFormat()` and `__toString`. This format is also used by `parseDateTime()`.
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
#### Type
`array<int>|string|int`
### $age public @property-read
does a diffInYears() with default parameters
#### Type
`int`
### $day public @property-read
#### Type
`int`
### $dayOfWeek public @property-read
1 (for Monday) through 7 (for Sunday)
#### Type
`int`
### $dayOfWeekName public @property-read
#### Type
`string`
### $dayOfYear public @property-read
0 through 365
#### Type
`int`
### $days protected static
Names of days of the week.
#### Type
`array`
### $daysInMonth public @property-read
number of days in the given month
#### Type
`int`
### $defaultLocale protected static
The default locale to be used for displaying formatted date strings.
Use static::setDefaultLocale() and static::getDefaultLocale() instead.
#### Type
`string|null`
### $diffFormatter protected static
Instance of the diff formatting object.
#### Type
`Cake\Chronos\DifferenceFormatterInterface`
### $dst public @property-read
daylight savings time indicator, true if DST, false otherwise
#### Type
`bool`
### $hour public @property-read
#### Type
`int`
### $lenientParsing protected static
Whether lenient parsing is enabled for IntlDateFormatter.
Defaults to true which is the default for IntlDateFormatter.
#### Type
`bool`
### $local public @property-read
checks if the timezone is local, true if local, false otherwise
#### Type
`bool`
### $micro public @property-read
#### Type
`int`
### $microsecond public @property-read
#### Type
`int`
### $minute public @property-read
#### Type
`int`
### $month public @property-read
#### Type
`int`
### $niceFormat public static
The format to use when formatting a time using `Cake\I18n\Date::nice()`
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
#### Type
`array<int>|string|int`
### $offset public @property-read
the timezone offset in seconds from UTC
#### Type
`int`
### $offsetHours public @property-read
the timezone offset in hours from UTC
#### Type
`int`
### $quarter public @property-read
the quarter of this instance, 1 - 4
#### Type
`int`
### $relativePattern protected static
Regex for relative period.
#### Type
`string`
### $second public @property-read
#### Type
`int`
### $timestamp public @property-read
seconds since the Unix Epoch
#### Type
`int`
### $timezone public @property-read
the current timezone
#### Type
`DateTimeZone`
### $timezoneName public @property-read
#### Type
`string`
### $toStringFormat protected static
Format to use for \_\_toString method when type juggling occurs.
#### Type
`string`
### $tz public @property-read
alias of timezone
#### Type
`DateTimeZone`
### $tzName public @property-read
#### Type
`string`
### $utc public @property-read
checks if the timezone is UTC, true if UTC, false otherwise
#### Type
`bool`
### $weekEndsAt protected static
Last day of week
#### Type
`int`
### $weekOfMonth public @property-read
1 through 5
#### Type
`int`
### $weekOfYear public @property-read
ISO-8601 week number of year, weeks starting on Monday
#### Type
`int`
### $weekStartsAt protected static
First day of week
#### Type
`int`
### $weekendDays protected static
Days of weekend
#### Type
`array`
### $wordAccuracy public static
The format to use when formatting a time using `Date::timeAgoInWords()` and the difference is less than `Date::$wordEnd`
#### Type
`array<string>`
### $wordEnd public static
The end of relative time telling
#### Type
`string`
### $wordFormat public static
The format to use when formatting a time using `Cake\I18n\Date::timeAgoInWords()` and the difference is more than `Cake\I18n\Date::$wordEnd`
#### Type
`array<int>|string|int`
### $year public @property-read
#### Type
`int`
### $yearIso public @property-read
#### Type
`int`
| programming_docs |
cakephp Class ControllerAuthorize Class ControllerAuthorize
==========================
An authorization adapter for AuthComponent. Provides the ability to authorize using a controller callback. Your controller's isAuthorized() method should return a boolean to indicate whether the user is authorized.
```
public function isAuthorized($user)
{
if ($this->request->getParam('admin')) {
return $user['role'] === 'admin';
}
return !empty($user);
}
```
The above is simple implementation that would only authorize users of the 'admin' role to access admin routing.
**Namespace:** [Cake\Auth](namespace-cake.auth)
**See:** \Cake\Controller\Component\AuthComponent::$authenticate
Property Summary
----------------
* [$\_Controller](#%24_Controller) protected `Cake\Controller\Controller` Controller for the request.
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for authorize objects.
* [$\_registry](#%24_registry) protected `Cake\Controller\ComponentRegistry` ComponentRegistry instance for getting more components.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [authorize()](#authorize()) public
Checks user authorization using a controller callback.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [controller()](#controller()) public
Get/set the controller this authorize object will be working with. Also checks that isAuthorized is implemented.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Controller\ComponentRegistry $registry, array<string, mixed> $config = [])
```
Constructor
#### Parameters
`Cake\Controller\ComponentRegistry` $registry `array<string, mixed>` $config optional ### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### authorize() public
```
authorize(ArrayAccess|array $user, Cake\Http\ServerRequest $request): bool
```
Checks user authorization using a controller callback.
#### Parameters
`ArrayAccess|array` $user Active user data
`Cake\Http\ServerRequest` $request Request instance.
#### Returns
`bool`
#### Throws
`Cake\Core\Exception\CakeException`
If controller does not have method `isAuthorized()`. ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
```
$this->configShallow('key', $value);
```
Setting a nested value:
```
$this->configShallow('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->configShallow(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### controller() public
```
controller(Cake\Controller\Controller|null $controller = null): Cake\Controller\Controller
```
Get/set the controller this authorize object will be working with. Also checks that isAuthorized is implemented.
#### Parameters
`Cake\Controller\Controller|null` $controller optional null to get, a controller to set.
#### Returns
`Cake\Controller\Controller`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### Usage
Reading the whole config:
```
$this->getConfig();
```
Reading a specific value:
```
$this->getConfig('key');
```
Reading a nested value:
```
$this->getConfig('some.nested.key');
```
Reading with default value:
```
$this->getConfig('some-key', 'default-value');
```
#### Parameters
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### Usage
Setting a specific value:
```
$this->setConfig('key', $value);
```
Setting a nested value:
```
$this->setConfig('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->setConfig(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_Controller protected
Controller for the request.
#### Type
`Cake\Controller\Controller`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for authorize objects.
#### Type
`array<string, mixed>`
### $\_registry protected
ComponentRegistry instance for getting more components.
#### Type
`Cake\Controller\ComponentRegistry`
cakephp Class ContentsBase Class ContentsBase
===================
Base constraint for content constraints
**Abstract**
**Namespace:** [Cake\Console\TestSuite\Constraint](namespace-cake.console.testsuite.constraint)
Property Summary
----------------
* [$contents](#%24contents) protected `string`
* [$output](#%24output) protected `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) protected
Evaluates the constraint for parameter $other. Returns true if the constraint is met, false otherwise.
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Returns a string representation of the object.
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string> $contents, string $output)
```
Constructor
#### Parameters
`array<string>` $contents Contents
`string` $output Output type
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() protected
```
matches(mixed $other): bool
```
Evaluates the constraint for parameter $other. Returns true if the constraint is met, false otherwise.
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other value or object to evaluate
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Returns a string representation of the object.
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $contents protected
#### Type
`string`
### $output protected
#### Type
`string`
cakephp Class ExitCode Class ExitCode
===============
ExitCode constraint
**Namespace:** [Cake\Console\TestSuite\Constraint](namespace-cake.console.testsuite.constraint)
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks if event is in fired array
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message string
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(int|null $exitCode)
```
Constructor
#### Parameters
`int|null` $exitCode Exit code
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks if event is in fired array
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Constraint check
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message string
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
| programming_docs |
cakephp Class MultiCheckboxWidget Class MultiCheckboxWidget
==========================
Input widget class for generating multiple checkboxes.
This class is usually used internally by `Cake\View\Helper\FormHelper`, it but can be used to generate standalone multiple checkboxes.
**Namespace:** [Cake\View\Widget](namespace-cake.view.widget)
Property Summary
----------------
* [$\_idPrefix](#%24_idPrefix) protected `string|null` Prefix for id attribute.
* [$\_idSuffixes](#%24_idSuffixes) protected `array<string>` A list of id suffixes used in the current rendering.
* [$\_label](#%24_label) protected `Cake\View\Widget\LabelWidget` Label widget instance.
* [$\_templates](#%24_templates) protected `Cake\View\StringTemplate` StringTemplate instance.
* [$defaults](#%24defaults) protected `array<string, mixed>` Data defaults.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Render multi-checkbox widget.
* ##### [\_clearIds()](#_clearIds()) protected
Clear the stored ID suffixes.
* ##### [\_domId()](#_domId()) protected
Generate an ID suitable for use in an ID attribute.
* ##### [\_id()](#_id()) protected
Generate an ID attribute for an element.
* ##### [\_idSuffix()](#_idSuffix()) protected
Generate an ID suffix.
* ##### [\_isDisabled()](#_isDisabled()) protected
Helper method for deciding what options are disabled.
* ##### [\_isSelected()](#_isSelected()) protected
Helper method for deciding what options are selected.
* ##### [\_renderInput()](#_renderInput()) protected
Render a single checkbox & wrapper.
* ##### [\_renderInputs()](#_renderInputs()) protected
Render the checkbox inputs.
* ##### [mergeDefaults()](#mergeDefaults()) protected
Merge default values with supplied data.
* ##### [render()](#render()) public
Render multi-checkbox widget.
* ##### [secureFields()](#secureFields()) public
Returns a list of fields that need to be secured for this widget.
* ##### [setMaxLength()](#setMaxLength()) protected
Set value for "maxlength" attribute if applicable.
* ##### [setRequired()](#setRequired()) protected
Set value for "required" attribute if applicable.
* ##### [setStep()](#setStep()) protected
Set value for "step" attribute if applicable.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\View\StringTemplate $templates, Cake\View\Widget\LabelWidget $label)
```
Render multi-checkbox widget.
This class uses the following templates:
* `checkbox` Renders checkbox input controls. Accepts the `name`, `value` and `attrs` variables.
* `checkboxWrapper` Renders the containing div/element for a checkbox and its label. Accepts the `input`, and `label` variables.
* `multicheckboxWrapper` Renders a wrapper around grouped inputs.
* `multicheckboxTitle` Renders the title element for grouped inputs.
#### Parameters
`Cake\View\StringTemplate` $templates Templates list.
`Cake\View\Widget\LabelWidget` $label Label widget instance.
### \_clearIds() protected
```
_clearIds(): void
```
Clear the stored ID suffixes.
#### Returns
`void`
### \_domId() protected
```
_domId(string $value): string
```
Generate an ID suitable for use in an ID attribute.
#### Parameters
`string` $value The value to convert into an ID.
#### Returns
`string`
### \_id() protected
```
_id(string $name, string $val): string
```
Generate an ID attribute for an element.
Ensures that id's for a given set of fields are unique.
#### Parameters
`string` $name The ID attribute name.
`string` $val The ID attribute value.
#### Returns
`string`
### \_idSuffix() protected
```
_idSuffix(string $val): string
```
Generate an ID suffix.
Ensures that id's for a given set of fields are unique.
#### Parameters
`string` $val The ID attribute value.
#### Returns
`string`
### \_isDisabled() protected
```
_isDisabled(string $key, mixed $disabled): bool
```
Helper method for deciding what options are disabled.
#### Parameters
`string` $key The key to test.
`mixed` $disabled The disabled values.
#### Returns
`bool`
### \_isSelected() protected
```
_isSelected(string $key, array<string>|string|int|false|null $selected): bool
```
Helper method for deciding what options are selected.
#### Parameters
`string` $key The key to test.
`array<string>|string|int|false|null` $selected The selected values.
#### Returns
`bool`
### \_renderInput() protected
```
_renderInput(array<string, mixed> $checkbox, Cake\View\Form\ContextInterface $context): string
```
Render a single checkbox & wrapper.
#### Parameters
`array<string, mixed>` $checkbox An array containing checkbox key/value option pairs
`Cake\View\Form\ContextInterface` $context Context object.
#### Returns
`string`
### \_renderInputs() protected
```
_renderInputs(array<string, mixed> $data, Cake\View\Form\ContextInterface $context): array<string>
```
Render the checkbox inputs.
#### Parameters
`array<string, mixed>` $data The data array defining the checkboxes.
`Cake\View\Form\ContextInterface` $context The current form context.
#### Returns
`array<string>`
### mergeDefaults() protected
```
mergeDefaults(array<string, mixed> $data, Cake\View\Form\ContextInterface $context): array<string, mixed>
```
Merge default values with supplied data.
#### Parameters
`array<string, mixed>` $data Data array
`Cake\View\Form\ContextInterface` $context Context instance.
#### Returns
`array<string, mixed>`
### render() public
```
render(array<string, mixed> $data, Cake\View\Form\ContextInterface $context): string
```
Render multi-checkbox widget.
Data supports the following options.
* `name` The name attribute of the inputs to create. `[]` will be appended to the name.
* `options` An array of options to create checkboxes out of.
* `val` Either a string/integer or array of values that should be checked. Can also be a complex options set.
* `disabled` Either a boolean or an array of checkboxes to disable.
* `escape` Set to false to disable HTML escaping.
* `options` An associative array of value=>labels to generate options for.
* `idPrefix` Prefix for generated ID attributes.
### Options format
The options option can take a variety of data format depending on the complexity of HTML you want generated.
You can generate simple options using a basic associative array:
```
'options' => ['elk' => 'Elk', 'beaver' => 'Beaver']
```
If you need to define additional attributes on your option elements you can use the complex form for options:
```
'options' => [
['value' => 'elk', 'text' => 'Elk', 'data-foo' => 'bar'],
]
```
This form **requires** that both the `value` and `text` keys be defined. If either is not set options will not be generated correctly.
#### Parameters
`array<string, mixed>` $data The data to generate a checkbox set with.
`Cake\View\Form\ContextInterface` $context The current form context.
#### Returns
`string`
### secureFields() public
```
secureFields(array<string, mixed> $data): array<string>
```
Returns a list of fields that need to be secured for this widget.
#### Parameters
`array<string, mixed>` $data #### Returns
`array<string>`
### setMaxLength() protected
```
setMaxLength(array<string, mixed> $data, Cake\View\Form\ContextInterface $context, string $fieldName): array<string, mixed>
```
Set value for "maxlength" attribute if applicable.
#### Parameters
`array<string, mixed>` $data Data array
`Cake\View\Form\ContextInterface` $context Context instance.
`string` $fieldName Field name.
#### Returns
`array<string, mixed>`
### setRequired() protected
```
setRequired(array<string, mixed> $data, Cake\View\Form\ContextInterface $context, string $fieldName): array<string, mixed>
```
Set value for "required" attribute if applicable.
#### Parameters
`array<string, mixed>` $data Data array
`Cake\View\Form\ContextInterface` $context Context instance.
`string` $fieldName Field name.
#### Returns
`array<string, mixed>`
### setStep() protected
```
setStep(array<string, mixed> $data, Cake\View\Form\ContextInterface $context, string $fieldName): array<string, mixed>
```
Set value for "step" attribute if applicable.
#### Parameters
`array<string, mixed>` $data Data array
`Cake\View\Form\ContextInterface` $context Context instance.
`string` $fieldName Field name.
#### Returns
`array<string, mixed>`
Property Detail
---------------
### $\_idPrefix protected
Prefix for id attribute.
#### Type
`string|null`
### $\_idSuffixes protected
A list of id suffixes used in the current rendering.
#### Type
`array<string>`
### $\_label protected
Label widget instance.
#### Type
`Cake\View\Widget\LabelWidget`
### $\_templates protected
StringTemplate instance.
#### Type
`Cake\View\StringTemplate`
### $defaults protected
Data defaults.
#### Type
`array<string, mixed>`
cakephp Class Sqlserver Class Sqlserver
================
SQLServer driver.
**Namespace:** [Cake\Database\Driver](namespace-cake.database.driver)
Constants
---------
* `string` **FEATURE\_CTE**
```
'cte'
```
Common Table Expressions (with clause) support.
* `string` **FEATURE\_DISABLE\_CONSTRAINT\_WITHOUT\_TRANSACTION**
```
'disable-constraint-without-transaction'
```
Disabling constraints without being in transaction support.
* `string` **FEATURE\_JSON**
```
'json'
```
Native JSON data type support.
* `string` **FEATURE\_QUOTE**
```
'quote'
```
PDO::quote() support.
* `string` **FEATURE\_SAVEPOINT**
```
'savepoint'
```
Transaction savepoint support.
* `string` **FEATURE\_TRUNCATE\_WITH\_CONSTRAINTS**
```
'truncate-with-constraints'
```
Truncate with foreign keys attached support.
* `string` **FEATURE\_WINDOW**
```
'window'
```
Window function support (all or partial clauses).
* `int|null` **MAX\_ALIAS\_LENGTH**
```
128
```
* `array<int>` **RETRY\_ERROR\_CODES**
```
[40613]
```
Property Summary
----------------
* [$\_autoQuoting](#%24_autoQuoting) protected `bool` Indicates whether the driver is doing automatic identifier quoting for all queries
* [$\_baseConfig](#%24_baseConfig) protected `array<string, mixed>` Base configuration settings for Sqlserver driver
* [$\_config](#%24_config) protected `array<string, mixed>` Configuration data.
* [$\_connection](#%24_connection) protected `PDO` Instance of PDO.
* [$\_endQuote](#%24_endQuote) protected `string` String used to end a database identifier quoting to make it safe
* [$\_schemaDialect](#%24_schemaDialect) protected `Cake\Database\Schema\SqlserverSchemaDialect|null` The schema dialect class for this driver
* [$\_startQuote](#%24_startQuote) protected `string` String used to start a database identifier quoting to make it safe
* [$\_version](#%24_version) protected `string|null` The server version
* [$connectRetries](#%24connectRetries) protected `int` The last number of connection retry attempts.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_destruct()](#__destruct()) public
Destructor
* ##### [\_connect()](#_connect()) protected
Establishes a connection to the database server
* ##### [\_deleteQueryTranslator()](#_deleteQueryTranslator()) protected
Apply translation steps to delete queries.
* ##### [\_expressionTranslators()](#_expressionTranslators()) protected
Returns an associative array of methods that will transform Expression objects to conform with the specific SQL dialect. Keys are class names and values a method in this class.
* ##### [\_insertQueryTranslator()](#_insertQueryTranslator()) protected
Apply translation steps to insert queries.
* ##### [\_pagingSubquery()](#_pagingSubquery()) protected
Generate a paging subquery for older versions of SQLserver.
* ##### [\_removeAliasesFromConditions()](#_removeAliasesFromConditions()) protected
Removes aliases from the `WHERE` clause of a query.
* ##### [\_selectQueryTranslator()](#_selectQueryTranslator()) protected
Apply translation steps to select queries.
* ##### [\_transformDistinct()](#_transformDistinct()) protected
Returns the passed query after rewriting the DISTINCT clause, so that drivers that do not support the "ON" part can provide the actual way it should be done
* ##### [\_transformFunctionExpression()](#_transformFunctionExpression()) protected
Receives a FunctionExpression and changes it so that it conforms to this SQL dialect.
* ##### [\_transformTupleComparison()](#_transformTupleComparison()) protected
Receives a TupleExpression and changes it so that it conforms to this SQL dialect.
* ##### [\_updateQueryTranslator()](#_updateQueryTranslator()) protected
Apply translation steps to update queries.
* ##### [beginTransaction()](#beginTransaction()) public
Starts a transaction.
* ##### [commitTransaction()](#commitTransaction()) public
Commits a transaction.
* ##### [compileQuery()](#compileQuery()) public
Transforms the passed query to this Driver's dialect and returns an instance of the transformed query and the full compiled SQL string.
* ##### [connect()](#connect()) public
Establishes a connection to the database server.
* ##### [disableAutoQuoting()](#disableAutoQuoting()) public
Disable auto quoting of identifiers in queries.
* ##### [disableForeignKeySQL()](#disableForeignKeySQL()) public
Get the SQL for disabling foreign keys.
* ##### [disconnect()](#disconnect()) public
Disconnects from database server.
* ##### [enableAutoQuoting()](#enableAutoQuoting()) public
Sets whether this driver should automatically quote identifiers in queries.
* ##### [enableForeignKeySQL()](#enableForeignKeySQL()) public
Get the SQL for enabling foreign keys.
* ##### [enabled()](#enabled()) public
Returns whether PHP is able to use this driver for connecting to database
* ##### [getConnectRetries()](#getConnectRetries()) public
Returns the number of connection retry attempts made.
* ##### [getConnection()](#getConnection()) public
Get the internal PDO connection instance.
* ##### [getMaxAliasLength()](#getMaxAliasLength()) public
Returns the maximum alias length allowed. This can be different from the maximum identifier length for columns.
* ##### [inTransaction()](#inTransaction()) public
Returns whether a transaction is active for connection.
* ##### [isAutoQuotingEnabled()](#isAutoQuotingEnabled()) public
Returns whether this driver should automatically quote identifiers in queries.
* ##### [isConnected()](#isConnected()) public
Checks whether the driver is connected.
* ##### [lastInsertId()](#lastInsertId()) public
Returns last id generated for a table or sequence in database.
* ##### [newCompiler()](#newCompiler()) public
Returns an instance of a QueryCompiler.
* ##### [newTableSchema()](#newTableSchema()) public
Constructs new TableSchema.
* ##### [prepare()](#prepare()) public
Prepares a sql statement to be executed
* ##### [queryTranslator()](#queryTranslator()) public
Returns a callable function that will be used to transform a passed Query object. This function, in turn, will return an instance of a Query object that has been transformed to accommodate any specificities of the SQL dialect in use.
* ##### [quote()](#quote()) public
Returns a value in a safe representation to be used in a query string
* ##### [quoteIdentifier()](#quoteIdentifier()) public
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words
* ##### [releaseSavePointSQL()](#releaseSavePointSQL()) public
Returns a SQL snippet for releasing a previously created save point
* ##### [rollbackSavePointSQL()](#rollbackSavePointSQL()) public
Returns a SQL snippet for rollbacking a previously created save point
* ##### [rollbackTransaction()](#rollbackTransaction()) public
Rollbacks a transaction.
* ##### [savePointSQL()](#savePointSQL()) public
Returns a SQL snippet for creating a new transaction savepoint
* ##### [schema()](#schema()) public
Returns the schema name that's being used.
* ##### [schemaDialect()](#schemaDialect()) public
Get the schema dialect.
* ##### [schemaValue()](#schemaValue()) public
Escapes values for use in schema definitions.
* ##### [setConnection()](#setConnection()) public
Set the internal PDO connection instance.
* ##### [supports()](#supports()) public
Returns whether the driver supports the feature.
* ##### [supportsCTEs()](#supportsCTEs()) public deprecated
Returns true if the server supports common table expressions.
* ##### [supportsDynamicConstraints()](#supportsDynamicConstraints()) public
Returns whether the driver supports adding or dropping constraints to already created tables.
* ##### [supportsQuoting()](#supportsQuoting()) public deprecated
Checks if the driver supports quoting, as PDO\_ODBC does not support it.
* ##### [supportsSavePoints()](#supportsSavePoints()) public
Returns whether this driver supports save points for nested transactions.
* ##### [version()](#version()) public
Returns connected server version.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional The configuration for the driver.
#### Throws
`InvalidArgumentException`
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_destruct() public
```
__destruct()
```
Destructor
### \_connect() protected
```
_connect(string $dsn, array<string, mixed> $config): bool
```
Establishes a connection to the database server
#### Parameters
`string` $dsn A Driver-specific PDO-DSN
`array<string, mixed>` $config configuration to be used for creating connection
#### Returns
`bool`
### \_deleteQueryTranslator() protected
```
_deleteQueryTranslator(Cake\Database\Query $query): Cake\Database\Query
```
Apply translation steps to delete queries.
Chops out aliases on delete query conditions as most database dialects do not support aliases in delete queries. This also removes aliases in table names as they frequently don't work either.
We are intentionally not supporting deletes with joins as they have even poorer support.
#### Parameters
`Cake\Database\Query` $query The query to translate
#### Returns
`Cake\Database\Query`
### \_expressionTranslators() protected
```
_expressionTranslators(): array<string>
```
Returns an associative array of methods that will transform Expression objects to conform with the specific SQL dialect. Keys are class names and values a method in this class.
#### Returns
`array<string>`
### \_insertQueryTranslator() protected
```
_insertQueryTranslator(Cake\Database\Query $query): Cake\Database\Query
```
Apply translation steps to insert queries.
#### Parameters
`Cake\Database\Query` $query The query to translate
#### Returns
`Cake\Database\Query`
### \_pagingSubquery() protected
```
_pagingSubquery(Cake\Database\Query $original, int|null $limit, int|null $offset): Cake\Database\Query
```
Generate a paging subquery for older versions of SQLserver.
Prior to SQLServer 2012 there was no equivalent to LIMIT OFFSET, so a subquery must be used.
#### Parameters
`Cake\Database\Query` $original The query to wrap in a subquery.
`int|null` $limit The number of rows to fetch.
`int|null` $offset The number of rows to offset.
#### Returns
`Cake\Database\Query`
### \_removeAliasesFromConditions() protected
```
_removeAliasesFromConditions(Cake\Database\Query $query): Cake\Database\Query
```
Removes aliases from the `WHERE` clause of a query.
#### Parameters
`Cake\Database\Query` $query The query to process.
#### Returns
`Cake\Database\Query`
#### Throws
`RuntimeException`
In case the processed query contains any joins, as removing aliases from the conditions can break references to the joined tables. ### \_selectQueryTranslator() protected
```
_selectQueryTranslator(Cake\Database\Query $query): Cake\Database\Query
```
Apply translation steps to select queries.
#### Parameters
`Cake\Database\Query` $query #### Returns
`Cake\Database\Query`
### \_transformDistinct() protected
```
_transformDistinct(Cake\Database\Query $query): Cake\Database\Query
```
Returns the passed query after rewriting the DISTINCT clause, so that drivers that do not support the "ON" part can provide the actual way it should be done
#### Parameters
`Cake\Database\Query` $query #### Returns
`Cake\Database\Query`
### \_transformFunctionExpression() protected
```
_transformFunctionExpression(Cake\Database\Expression\FunctionExpression $expression): void
```
Receives a FunctionExpression and changes it so that it conforms to this SQL dialect.
#### Parameters
`Cake\Database\Expression\FunctionExpression` $expression The function expression to convert to TSQL.
#### Returns
`void`
### \_transformTupleComparison() protected
```
_transformTupleComparison(Cake\Database\Expression\TupleComparison $expression, Cake\Database\Query $query): void
```
Receives a TupleExpression and changes it so that it conforms to this SQL dialect.
It transforms expressions looking like '(a, b) IN ((c, d), (e, f))' into an equivalent expression of the form '((a = c) AND (b = d)) OR ((a = e) AND (b = f))'.
It can also transform transform expressions where the right hand side is a query selecting the same amount of columns as the elements in the left hand side of the expression:
(a, b) IN (SELECT c, d FROM a\_table) is transformed into
1 = (SELECT 1 FROM a\_table WHERE (a = c) AND (b = d))
#### Parameters
`Cake\Database\Expression\TupleComparison` $expression The expression to transform
`Cake\Database\Query` $query The query to update.
#### Returns
`void`
### \_updateQueryTranslator() protected
```
_updateQueryTranslator(Cake\Database\Query $query): Cake\Database\Query
```
Apply translation steps to update queries.
Chops out aliases on update query conditions as not all database dialects do support aliases in update queries.
Just like for delete queries, joins are currently not supported for update queries.
#### Parameters
`Cake\Database\Query` $query The query to translate
#### Returns
`Cake\Database\Query`
### beginTransaction() public
```
beginTransaction(): bool
```
Starts a transaction.
#### Returns
`bool`
### commitTransaction() public
```
commitTransaction(): bool
```
Commits a transaction.
#### Returns
`bool`
### compileQuery() public
```
compileQuery(Cake\Database\Query $query, Cake\Database\ValueBinder $binder): array
```
Transforms the passed query to this Driver's dialect and returns an instance of the transformed query and the full compiled SQL string.
#### Parameters
`Cake\Database\Query` $query `Cake\Database\ValueBinder` $binder #### Returns
`array`
### connect() public
```
connect(): bool
```
Establishes a connection to the database server.
Please note that the PDO::ATTR\_PERSISTENT attribute is not supported by the SQL Server PHP PDO drivers. As a result you cannot use the persistent config option when connecting to a SQL Server (for more information see: <https://github.com/Microsoft/msphpsql/issues/65>).
#### Returns
`bool`
#### Throws
`InvalidArgumentException`
if an unsupported setting is in the driver config ### disableAutoQuoting() public
```
disableAutoQuoting(): $this
```
Disable auto quoting of identifiers in queries.
#### Returns
`$this`
### disableForeignKeySQL() public
```
disableForeignKeySQL(): string
```
Get the SQL for disabling foreign keys.
#### Returns
`string`
### disconnect() public
```
disconnect(): void
```
Disconnects from database server.
#### Returns
`void`
### enableAutoQuoting() public
```
enableAutoQuoting(bool $enable = true): $this
```
Sets whether this driver should automatically quote identifiers in queries.
#### Parameters
`bool` $enable optional #### Returns
`$this`
### enableForeignKeySQL() public
```
enableForeignKeySQL(): string
```
Get the SQL for enabling foreign keys.
#### Returns
`string`
### enabled() public
```
enabled(): bool
```
Returns whether PHP is able to use this driver for connecting to database
#### Returns
`bool`
### getConnectRetries() public
```
getConnectRetries(): int
```
Returns the number of connection retry attempts made.
#### Returns
`int`
### getConnection() public
```
getConnection(): PDO
```
Get the internal PDO connection instance.
#### Returns
`PDO`
### getMaxAliasLength() public
```
getMaxAliasLength(): int|null
```
Returns the maximum alias length allowed. This can be different from the maximum identifier length for columns.
#### Returns
`int|null`
### inTransaction() public
```
inTransaction(): bool
```
Returns whether a transaction is active for connection.
#### Returns
`bool`
### isAutoQuotingEnabled() public
```
isAutoQuotingEnabled(): bool
```
Returns whether this driver should automatically quote identifiers in queries.
#### Returns
`bool`
### isConnected() public
```
isConnected(): bool
```
Checks whether the driver is connected.
#### Returns
`bool`
### lastInsertId() public
```
lastInsertId(string|null $table = null, string|null $column = null): string|int
```
Returns last id generated for a table or sequence in database.
#### Parameters
`string|null` $table optional `string|null` $column optional #### Returns
`string|int`
### newCompiler() public
```
newCompiler(): Cake\Database\SqlserverCompiler
```
Returns an instance of a QueryCompiler.
#### Returns
`Cake\Database\SqlserverCompiler`
### newTableSchema() public
```
newTableSchema(string $table, array $columns = []): Cake\Database\Schema\TableSchema
```
Constructs new TableSchema.
#### Parameters
`string` $table `array` $columns optional #### Returns
`Cake\Database\Schema\TableSchema`
### prepare() public
```
prepare(Cake\Database\Query|string $query): Cake\Database\StatementInterface
```
Prepares a sql statement to be executed
#### Parameters
`Cake\Database\Query|string` $query The query to prepare.
#### Returns
`Cake\Database\StatementInterface`
### queryTranslator() public
```
queryTranslator(string $type): Closure
```
Returns a callable function that will be used to transform a passed Query object. This function, in turn, will return an instance of a Query object that has been transformed to accommodate any specificities of the SQL dialect in use.
#### Parameters
`string` $type the type of query to be transformed (select, insert, update, delete)
#### Returns
`Closure`
### quote() public
```
quote(mixed $value, int $type = PDO::PARAM_STR): string
```
Returns a value in a safe representation to be used in a query string
#### Parameters
`mixed` $value `int` $type optional #### Returns
`string`
### quoteIdentifier() public
```
quoteIdentifier(string $identifier): string
```
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words
#### Parameters
`string` $identifier The identifier to quote.
#### Returns
`string`
### releaseSavePointSQL() public
```
releaseSavePointSQL(string|int $name): string
```
Returns a SQL snippet for releasing a previously created save point
#### Parameters
`string|int` $name #### Returns
`string`
### rollbackSavePointSQL() public
```
rollbackSavePointSQL(string|int $name): string
```
Returns a SQL snippet for rollbacking a previously created save point
#### Parameters
`string|int` $name #### Returns
`string`
### rollbackTransaction() public
```
rollbackTransaction(): bool
```
Rollbacks a transaction.
#### Returns
`bool`
### savePointSQL() public
```
savePointSQL(string|int $name): string
```
Returns a SQL snippet for creating a new transaction savepoint
#### Parameters
`string|int` $name #### Returns
`string`
### schema() public
```
schema(): string
```
Returns the schema name that's being used.
#### Returns
`string`
### schemaDialect() public
```
schemaDialect(): Cake\Database\Schema\SchemaDialect
```
Get the schema dialect.
Used by {@link \Cake\Database\Schema} package to reflect schema and generate schema.
If all the tables that use this Driver specify their own schemas, then this may return null.
#### Returns
`Cake\Database\Schema\SchemaDialect`
### schemaValue() public
```
schemaValue(mixed $value): string
```
Escapes values for use in schema definitions.
#### Parameters
`mixed` $value #### Returns
`string`
### setConnection() public
```
setConnection(object $connection): $this
```
Set the internal PDO connection instance.
#### Parameters
`object` $connection PDO instance.
#### Returns
`$this`
### supports() public
```
supports(string $feature): bool
```
Returns whether the driver supports the feature.
Defaults to true for FEATURE\_QUOTE and FEATURE\_SAVEPOINT.
#### Parameters
`string` $feature #### Returns
`bool`
### supportsCTEs() public
```
supportsCTEs(): bool
```
Returns true if the server supports common table expressions.
#### Returns
`bool`
### supportsDynamicConstraints() public
```
supportsDynamicConstraints(): bool
```
Returns whether the driver supports adding or dropping constraints to already created tables.
#### Returns
`bool`
### supportsQuoting() public
```
supportsQuoting(): bool
```
Checks if the driver supports quoting, as PDO\_ODBC does not support it.
#### Returns
`bool`
### supportsSavePoints() public
```
supportsSavePoints(): bool
```
Returns whether this driver supports save points for nested transactions.
#### Returns
`bool`
### version() public
```
version(): string
```
Returns connected server version.
#### Returns
`string`
Property Detail
---------------
### $\_autoQuoting protected
Indicates whether the driver is doing automatic identifier quoting for all queries
#### Type
`bool`
### $\_baseConfig protected
Base configuration settings for Sqlserver driver
#### Type
`array<string, mixed>`
### $\_config protected
Configuration data.
#### Type
`array<string, mixed>`
### $\_connection protected
Instance of PDO.
#### Type
`PDO`
### $\_endQuote protected
String used to end a database identifier quoting to make it safe
#### Type
`string`
### $\_schemaDialect protected
The schema dialect class for this driver
#### Type
`Cake\Database\Schema\SqlserverSchemaDialect|null`
### $\_startQuote protected
String used to start a database identifier quoting to make it safe
#### Type
`string`
### $\_version protected
The server version
#### Type
`string|null`
### $connectRetries protected
The last number of connection retry attempts.
#### Type
`int`
| programming_docs |
cakephp Class Debugger Class Debugger
===============
Provide custom logging and error handling.
Debugger extends PHP's default error handling and gives simpler to use more powerful interfaces.
**Namespace:** [Cake\Error](namespace-cake.error)
**Link:** https://book.cakephp.org/4/en/development/debugging.html#namespace-Cake\Error
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_data](#%24_data) protected `array` Holds current output data when outputFormat is false.
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default configuration
* [$\_outputFormat](#%24_outputFormat) protected `string` The current output format.
* [$\_templates](#%24_templates) protected `array<string, array<string, mixed>>` Templates used when generating trace or error strings. Can be global or indexed by the format value used in $\_outputFormat.
* [$editors](#%24editors) protected `array<string, string|callable>` A map of editors to their link templates.
* [$renderers](#%24renderers) protected `array<string, class-string>` Mapping for error renderers.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_highlight()](#_highlight()) protected static
Wraps the highlight\_string function in case the server API does not implement the function as it is the case of the HipHop interpreter
* ##### [addEditor()](#addEditor()) public static
Add an editor link format
* ##### [addFormat()](#addFormat()) public static deprecated
Add an output format or update a format in Debugger.
* ##### [addRenderer()](#addRenderer()) public static deprecated
Add a renderer to the current instance.
* ##### [checkSecurityKeys()](#checkSecurityKeys()) public static
Verifies that the application's salt and cipher seed value has been changed from the default value.
* ##### [configInstance()](#configInstance()) public static
Read or write configuration options for the Debugger instance.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [dump()](#dump()) public static
Recursively formats and outputs the contents of the supplied variable.
* ##### [editorUrl()](#editorUrl()) public static
Get a formatted URL for the active editor.
* ##### [excerpt()](#excerpt()) public static
Grabs an excerpt from a file and highlights a given line of code.
* ##### [export()](#export()) protected static
Protected export function used to keep track of indentation and recursion.
* ##### [exportArray()](#exportArray()) protected static
Export an array type object. Filters out keys used in datasource configuration.
* ##### [exportObject()](#exportObject()) protected static
Handles object to node conversion.
* ##### [exportVar()](#exportVar()) public static
Converts a variable to a string for debug output.
* ##### [exportVarAsNodes()](#exportVarAsNodes()) public static
Convert the variable to the internal node tree.
* ##### [exportVarAsPlainText()](#exportVarAsPlainText()) public static
Converts a variable to a plain text string.
* ##### [formatHtmlMessage()](#formatHtmlMessage()) public static
Format an exception message to be HTML formatted.
* ##### [formatTrace()](#formatTrace()) public static
Formats a stack trace based on the supplied options.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getExportFormatter()](#getExportFormatter()) public
Get the configured export formatter or infer one based on the environment.
* ##### [getInstance()](#getInstance()) public static
Returns a reference to the Debugger singleton object instance.
* ##### [getOutputFormat()](#getOutputFormat()) public static deprecated
Get the output format for Debugger error rendering.
* ##### [getType()](#getType()) public static
Get the type of the given variable. Will return the class name for objects.
* ##### [log()](#log()) public static
Creates an entry in the log file. The log entry will contain a stack trace from where it was called. as well as export the variable using exportVar. By default, the log is written to the debug log.
* ##### [outputError()](#outputError()) public deprecated
Takes a processed array of data from an error and displays it in the chosen format.
* ##### [outputMask()](#outputMask()) public static
Reads the current output masking.
* ##### [printVar()](#printVar()) public static
Prints out debug information about given variable.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setEditor()](#setEditor()) public static
Choose the editor link style you want to use.
* ##### [setOutputFormat()](#setOutputFormat()) public static deprecated
Set the output format for Debugger error rendering.
* ##### [setOutputMask()](#setOutputMask()) public static
Sets configurable masking of debugger output by property name and array key names.
* ##### [trace()](#trace()) public static
Outputs a stack trace based on the supplied options.
* ##### [trimPath()](#trimPath()) public static
Shortens file paths by replacing the application base path with 'APP', and the CakePHP core path with 'CORE'.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_highlight() protected static
```
_highlight(string $str): string
```
Wraps the highlight\_string function in case the server API does not implement the function as it is the case of the HipHop interpreter
#### Parameters
`string` $str The string to convert.
#### Returns
`string`
### addEditor() public static
```
addEditor(string $name, Closure|string $template): void
```
Add an editor link format
Template strings can use the `{file}` and `{line}` placeholders. Closures templates must return a string, and accept two parameters: The file and line.
#### Parameters
`string` $name The name of the editor.
`Closure|string` $template The string template or closure
#### Returns
`void`
### addFormat() public static
```
addFormat(string $format, array $strings): array
```
Add an output format or update a format in Debugger.
```
Debugger::addFormat('custom', $data);
```
Where $data is an array of strings that use Text::insert() variable replacement. The template vars should be in a `{:id}` style. An error formatter can have the following keys:
* 'error' - Used for the container for the error message. Gets the following template variables: `id`, `error`, `code`, `description`, `path`, `line`, `links`, `info`
* 'info' - A combination of `code`, `context` and `trace`. Will be set with the contents of the other template keys.
* 'trace' - The container for a stack trace. Gets the following template variables: `trace`
* 'context' - The container element for the context variables. Gets the following templates: `id`, `context`
* 'links' - An array of HTML links that are used for creating links to other resources. Typically this is used to create javascript links to open other sections. Link keys, are: `code`, `context`, `help`. See the JS output format for an example.
* 'traceLine' - Used for creating lines in the stacktrace. Gets the following template variables: `reference`, `path`, `line`
Alternatively if you want to use a custom callback to do all the formatting, you can use the callback key, and provide a callable:
```
Debugger::addFormat('custom', ['callback' => [$foo, 'outputError']];
```
The callback can expect two parameters. The first is an array of all the error data. The second contains the formatted strings generated using the other template strings. Keys like `info`, `links`, `code`, `context` and `trace` will be present depending on the other templates in the format type.
#### Parameters
`string` $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for straight HTML output, or 'txt' for unformatted text.
`array` $strings Template strings, or a callback to be used for the output format.
#### Returns
`array`
### addRenderer() public static
```
addRenderer(string $name, class-stringCake\Error\ErrorRendererInterface> $class): void
```
Add a renderer to the current instance.
#### Parameters
`string` $name The alias for the the renderer.
`class-stringCake\Error\ErrorRendererInterface>` $class The classname of the renderer to use.
#### Returns
`void`
### checkSecurityKeys() public static
```
checkSecurityKeys(): void
```
Verifies that the application's salt and cipher seed value has been changed from the default value.
#### Returns
`void`
### configInstance() public static
```
configInstance(array<string, mixed>|string|null $key = null, mixed|null $value = null, bool $merge = true): mixed
```
Read or write configuration options for the Debugger instance.
#### Parameters
`array<string, mixed>|string|null` $key optional The key to get/set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`mixed`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
```
$this->configShallow('key', $value);
```
Setting a nested value:
```
$this->configShallow('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->configShallow(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### dump() public static
```
dump(mixed $var, int $maxDepth = 3): void
```
Recursively formats and outputs the contents of the supplied variable.
#### Parameters
`mixed` $var The variable to dump.
`int` $maxDepth optional The depth to output to. Defaults to 3.
#### Returns
`void`
#### See Also
\Cake\Error\Debugger::exportVar() #### Links
https://book.cakephp.org/4/en/development/debugging.html#outputting-values
### editorUrl() public static
```
editorUrl(string $file, int $line): string
```
Get a formatted URL for the active editor.
#### Parameters
`string` $file The file to create a link for.
`int` $line The line number to create a link for.
#### Returns
`string`
### excerpt() public static
```
excerpt(string $file, int $line, int $context = 2): array<string>
```
Grabs an excerpt from a file and highlights a given line of code.
Usage:
```
Debugger::excerpt('/path/to/file', 100, 4);
```
The above would return an array of 8 items. The 4th item would be the provided line, and would be wrapped in `<span class="code-highlight"></span>`. All the lines are processed with highlight\_string() as well, so they have basic PHP syntax highlighting applied.
#### Parameters
`string` $file Absolute path to a PHP file.
`int` $line Line number to highlight.
`int` $context optional Number of lines of context to extract above and below $line.
#### Returns
`array<string>`
#### See Also
https://secure.php.net/highlight\_string #### Links
https://book.cakephp.org/4/en/development/debugging.html#getting-an-excerpt-from-a-file
### export() protected static
```
export(mixed $var, Cake\Error\Debug\DebugContext $context): Cake\Error\Debug\NodeInterface
```
Protected export function used to keep track of indentation and recursion.
#### Parameters
`mixed` $var The variable to dump.
`Cake\Error\Debug\DebugContext` $context Dump context
#### Returns
`Cake\Error\Debug\NodeInterface`
### exportArray() protected static
```
exportArray(array $var, Cake\Error\Debug\DebugContext $context): Cake\Error\Debug\ArrayNode
```
Export an array type object. Filters out keys used in datasource configuration.
The following keys are replaced with \*\*\*'s
* password
* login
* host
* database
* port
* prefix
* schema
#### Parameters
`array` $var The array to export.
`Cake\Error\Debug\DebugContext` $context The current dump context.
#### Returns
`Cake\Error\Debug\ArrayNode`
### exportObject() protected static
```
exportObject(object $var, Cake\Error\Debug\DebugContext $context): Cake\Error\Debug\NodeInterface
```
Handles object to node conversion.
#### Parameters
`object` $var Object to convert.
`Cake\Error\Debug\DebugContext` $context The dump context.
#### Returns
`Cake\Error\Debug\NodeInterface`
#### See Also
\Cake\Error\Debugger::exportVar() ### exportVar() public static
```
exportVar(mixed $var, int $maxDepth = 3): string
```
Converts a variable to a string for debug output.
*Note:* The following keys will have their contents replaced with `*****`:
* password
+ login
+ host
+ database
+ port
+ prefix
+ schema
This is done to protect database credentials, which could be accidentally shown in an error message if CakePHP is deployed in development mode.
#### Parameters
`mixed` $var Variable to convert.
`int` $maxDepth optional The depth to output to. Defaults to 3.
#### Returns
`string`
### exportVarAsNodes() public static
```
exportVarAsNodes(mixed $var, int $maxDepth = 3): Cake\Error\Debug\NodeInterface
```
Convert the variable to the internal node tree.
The node tree can be manipulated and serialized more easily than many object graphs can.
#### Parameters
`mixed` $var Variable to convert.
`int` $maxDepth optional The depth to generate nodes to. Defaults to 3.
#### Returns
`Cake\Error\Debug\NodeInterface`
### exportVarAsPlainText() public static
```
exportVarAsPlainText(mixed $var, int $maxDepth = 3): string
```
Converts a variable to a plain text string.
#### Parameters
`mixed` $var Variable to convert.
`int` $maxDepth optional The depth to output to. Defaults to 3.
#### Returns
`string`
### formatHtmlMessage() public static
```
formatHtmlMessage(string $message): string
```
Format an exception message to be HTML formatted.
Does the following formatting operations:
* HTML escape the message.
* Convert `bool` into `<code>bool</code>`
* Convert newlines into `<br />`
#### Parameters
`string` $message The string message to format.
#### Returns
`string`
### formatTrace() public static
```
formatTrace(Throwable|array $backtrace, array<string, mixed> $options = []): array|string
```
Formats a stack trace based on the supplied options.
### Options
* `depth` - The number of stack frames to return. Defaults to 999
* `format` - The format you want the return. Defaults to the currently selected format. If format is 'array' or 'points' the return will be an array.
* `args` - Should arguments for functions be shown? If true, the arguments for each method call will be displayed.
* `start` - The stack frame to start generating a trace from. Defaults to 0
#### Parameters
`Throwable|array` $backtrace Trace as array or an exception object.
`array<string, mixed>` $options optional Format for outputting stack trace.
#### Returns
`array|string`
#### Links
https://book.cakephp.org/4/en/development/debugging.html#generating-stack-traces
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### Usage
Reading the whole config:
```
$this->getConfig();
```
Reading a specific value:
```
$this->getConfig('key');
```
Reading a nested value:
```
$this->getConfig('some.nested.key');
```
Reading with default value:
```
$this->getConfig('some-key', 'default-value');
```
#### Parameters
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getExportFormatter() public
```
getExportFormatter(): Cake\Error\Debug\FormatterInterface
```
Get the configured export formatter or infer one based on the environment.
#### Returns
`Cake\Error\Debug\FormatterInterface`
### getInstance() public static
```
getInstance(string|null $class = null): static
```
Returns a reference to the Debugger singleton object instance.
#### Parameters
`string|null` $class optional Class name.
#### Returns
`static`
### getOutputFormat() public static
```
getOutputFormat(): string
```
Get the output format for Debugger error rendering.
#### Returns
`string`
### getType() public static
```
getType(mixed $var): string
```
Get the type of the given variable. Will return the class name for objects.
#### Parameters
`mixed` $var The variable to get the type of.
#### Returns
`string`
### log() public static
```
log(mixed $var, string|int $level = 'debug', int $maxDepth = 3): void
```
Creates an entry in the log file. The log entry will contain a stack trace from where it was called. as well as export the variable using exportVar. By default, the log is written to the debug log.
#### Parameters
`mixed` $var Variable or content to log.
`string|int` $level optional Type of log to use. Defaults to 'debug'.
`int` $maxDepth optional The depth to output to. Defaults to 3.
#### Returns
`void`
### outputError() public
```
outputError(array $data): void
```
Takes a processed array of data from an error and displays it in the chosen format.
#### Parameters
`array` $data Data to output.
#### Returns
`void`
### outputMask() public static
```
outputMask(): array<string, string>
```
Reads the current output masking.
#### Returns
`array<string, string>`
### printVar() public static
```
printVar(mixed $var, array $location = [], bool|null $showHtml = null): void
```
Prints out debug information about given variable.
#### Parameters
`mixed` $var Variable to show debug information for.
`array` $location optional If contains keys "file" and "line" their values will be used to show location info.
`bool|null` $showHtml optional If set to true, the method prints the debug data encoded as HTML. If false, plain text formatting will be used. If null, the format will be chosen based on the configured exportFormatter, or environment conditions.
#### Returns
`void`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### Usage
Setting a specific value:
```
$this->setConfig('key', $value);
```
Setting a nested value:
```
$this->setConfig('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->setConfig(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setEditor() public static
```
setEditor(string $name): void
```
Choose the editor link style you want to use.
#### Parameters
`string` $name The editor name.
#### Returns
`void`
### setOutputFormat() public static
```
setOutputFormat(string $format): void
```
Set the output format for Debugger error rendering.
#### Parameters
`string` $format The format you want errors to be output as.
#### Returns
`void`
#### Throws
`InvalidArgumentException`
When choosing a format that doesn't exist. ### setOutputMask() public static
```
setOutputMask(array<string, string> $value, bool $merge = true): void
```
Sets configurable masking of debugger output by property name and array key names.
### Example
Debugger::setOutputMask(['password' => '[\*****\*\*\*\*****]');
#### Parameters
`array<string, string>` $value An array where keys are replaced by their values in output.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`void`
### trace() public static
```
trace(array<string, mixed> $options = []): array|string
```
Outputs a stack trace based on the supplied options.
### Options
* `depth` - The number of stack frames to return. Defaults to 999
* `format` - The format you want the return. Defaults to the currently selected format. If format is 'array' or 'points' the return will be an array.
* `args` - Should arguments for functions be shown? If true, the arguments for each method call will be displayed.
* `start` - The stack frame to start generating a trace from. Defaults to 0
#### Parameters
`array<string, mixed>` $options optional Format for outputting stack trace.
#### Returns
`array|string`
#### Links
https://book.cakephp.org/4/en/development/debugging.html#generating-stack-traces
### trimPath() public static
```
trimPath(string $path): string
```
Shortens file paths by replacing the application base path with 'APP', and the CakePHP core path with 'CORE'.
#### Parameters
`string` $path Path to shorten.
#### Returns
`string`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_data protected
Holds current output data when outputFormat is false.
#### Type
`array`
### $\_defaultConfig protected
Default configuration
#### Type
`array<string, mixed>`
### $\_outputFormat protected
The current output format.
#### Type
`string`
### $\_templates protected
Templates used when generating trace or error strings. Can be global or indexed by the format value used in $\_outputFormat.
#### Type
`array<string, array<string, mixed>>`
### $editors protected
A map of editors to their link templates.
#### Type
`array<string, string|callable>`
### $renderers protected
Mapping for error renderers.
Error renderers are replacing output formatting with an object based system. Having Debugger handle and render errors will be deprecated and the new ErrorTrap system should be used instead.
#### Type
`array<string, class-string>`
| programming_docs |
cakephp Class ConnectionRegistry Class ConnectionRegistry
=========================
A registry object for connection instances.
**Namespace:** [Cake\Datasource](namespace-cake.datasource)
**See:** \Cake\Datasource\ConnectionManager
Property Summary
----------------
* [$\_loaded](#%24_loaded) protected `array<object>` Map of loaded objects.
Method Summary
--------------
* ##### [\_\_debugInfo()](#__debugInfo()) public
Debug friendly object properties.
* ##### [\_\_get()](#__get()) public
Provide public read access to the loaded objects
* ##### [\_\_isset()](#__isset()) public
Provide isset access to \_loaded
* ##### [\_\_set()](#__set()) public
Sets an object.
* ##### [\_\_unset()](#__unset()) public
Unsets an object.
* ##### [\_checkDuplicate()](#_checkDuplicate()) protected
Check for duplicate object loading.
* ##### [\_create()](#_create()) protected
Create the connection object with the correct settings.
* ##### [\_resolveClassName()](#_resolveClassName()) protected
Resolve a datasource classname.
* ##### [\_throwMissingClassError()](#_throwMissingClassError()) protected
Throws an exception when a datasource is missing
* ##### [count()](#count()) public
Returns the number of loaded objects.
* ##### [get()](#get()) public
Get loaded object instance.
* ##### [getIterator()](#getIterator()) public
Returns an array iterator.
* ##### [has()](#has()) public
Check whether a given object is loaded.
* ##### [load()](#load()) public
Loads/constructs an object instance.
* ##### [loaded()](#loaded()) public
Get the list of loaded objects.
* ##### [normalizeArray()](#normalizeArray()) public
Normalizes an object array, creates an array that makes lazy loading easier
* ##### [reset()](#reset()) public
Clear loaded instances in the registry.
* ##### [set()](#set()) public
Set an object directly into the registry by name.
* ##### [unload()](#unload()) public
Remove a single adapter from the registry.
Method Detail
-------------
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Debug friendly object properties.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): object|null
```
Provide public read access to the loaded objects
#### Parameters
`string` $name Name of property to read
#### Returns
`object|null`
### \_\_isset() public
```
__isset(string $name): bool
```
Provide isset access to \_loaded
#### Parameters
`string` $name Name of object being checked.
#### Returns
`bool`
### \_\_set() public
```
__set(string $name, object $object): void
```
Sets an object.
#### Parameters
`string` $name Name of a property to set.
`object` $object Object to set.
#### Returns
`void`
### \_\_unset() public
```
__unset(string $name): void
```
Unsets an object.
#### Parameters
`string` $name Name of a property to unset.
#### Returns
`void`
### \_checkDuplicate() protected
```
_checkDuplicate(string $name, array<string, mixed> $config): void
```
Check for duplicate object loading.
If a duplicate is being loaded and has different configuration, that is bad and an exception will be raised.
An exception is raised, as replacing the object will not update any references other objects may have. Additionally, simply updating the runtime configuration is not a good option as we may be missing important constructor logic dependent on the configuration.
#### Parameters
`string` $name The name of the alias in the registry.
`array<string, mixed>` $config The config data for the new instance.
#### Returns
`void`
#### Throws
`RuntimeException`
When a duplicate is found. ### \_create() protected
```
_create(object|string $class, string $alias, array<string, mixed> $config): Cake\Datasource\ConnectionInterface
```
Create the connection object with the correct settings.
Part of the template method for Cake\Core\ObjectRegistry::load()
If a callable is passed as first argument, The returned value of this function will be the result of the callable.
#### Parameters
`object|string` $class The classname or object to make.
`string` $alias The alias of the object.
`array<string, mixed>` $config An array of settings to use for the datasource.
#### Returns
`Cake\Datasource\ConnectionInterface`
### \_resolveClassName() protected
```
_resolveClassName(string $class): string|null
```
Resolve a datasource classname.
Part of the template method for Cake\Core\ObjectRegistry::load()
#### Parameters
`string` $class Partial classname to resolve.
#### Returns
`string|null`
### \_throwMissingClassError() protected
```
_throwMissingClassError(string $class, string|null $plugin): void
```
Throws an exception when a datasource is missing
Part of the template method for Cake\Core\ObjectRegistry::load()
#### Parameters
`string` $class The classname that is missing.
`string|null` $plugin The plugin the datasource is missing in.
#### Returns
`void`
#### Throws
`Cake\Datasource\Exception\MissingDatasourceException`
### count() public
```
count(): int
```
Returns the number of loaded objects.
#### Returns
`int`
### get() public
```
get(string $name): object
```
Get loaded object instance.
#### Parameters
`string` $name Name of object.
#### Returns
`object`
#### Throws
`RuntimeException`
If not loaded or found. ### getIterator() public
```
getIterator(): Traversable
```
Returns an array iterator.
#### Returns
`Traversable`
### has() public
```
has(string $name): bool
```
Check whether a given object is loaded.
#### Parameters
`string` $name The object name to check for.
#### Returns
`bool`
### load() public
```
load(string $name, array<string, mixed> $config = []): mixed
```
Loads/constructs an object instance.
Will return the instance in the registry if it already exists. If a subclass provides event support, you can use `$config['enabled'] = false` to exclude constructed objects from being registered for events.
Using {@link \Cake\Controller\Component::$components} as an example. You can alias an object by setting the 'className' key, i.e.,
```
protected $components = [
'Email' => [
'className' => 'App\Controller\Component\AliasedEmailComponent'
];
];
```
All calls to the `Email` component would use `AliasedEmail` instead.
#### Parameters
`string` $name The name/class of the object to load.
`array<string, mixed>` $config optional Additional settings to use when loading the object.
#### Returns
`mixed`
#### Throws
`Exception`
If the class cannot be found. ### loaded() public
```
loaded(): array<string>
```
Get the list of loaded objects.
#### Returns
`array<string>`
### normalizeArray() public
```
normalizeArray(array $objects): array<string, array>
```
Normalizes an object array, creates an array that makes lazy loading easier
#### Parameters
`array` $objects Array of child objects to normalize.
#### Returns
`array<string, array>`
### reset() public
```
reset(): $this
```
Clear loaded instances in the registry.
If the registry subclass has an event manager, the objects will be detached from events as well.
#### Returns
`$this`
### set() public
```
set(string $name, object $object): $this
```
Set an object directly into the registry by name.
If this collection implements events, the passed object will be attached into the event manager
#### Parameters
`string` $name The name of the object to set in the registry.
`object` $object instance to store in the registry
#### Returns
`$this`
### unload() public
```
unload(string $name): $this
```
Remove a single adapter from the registry.
If this registry has an event manager, the object will be detached from any events as well.
#### Parameters
`string` $name The adapter name.
#### Returns
`$this`
Property Detail
---------------
### $\_loaded protected
Map of loaded objects.
#### Type
`array<object>`
cakephp Class Xml Class Xml
==========
XML handling for CakePHP.
The methods in these classes enable the datasources that use XML to work.
**Namespace:** [Cake\Utility](namespace-cake.utility)
Method Summary
--------------
* ##### [\_createChild()](#_createChild()) protected static
Helper to \_fromArray(). It will create children of arrays
* ##### [\_fromArray()](#_fromArray()) protected static
Recursive method to create children from array
* ##### [\_loadXml()](#_loadXml()) protected static
Parse the input data and create either a SimpleXmlElement object or a DOMDocument.
* ##### [\_toArray()](#_toArray()) protected static
Recursive method to toArray
* ##### [build()](#build()) public static
Initialize SimpleXMLElement or DOMDocument from a given XML string, file path, URL or array.
* ##### [fromArray()](#fromArray()) public static
Transform an array into a SimpleXMLElement
* ##### [load()](#load()) protected static
Parse the input data and create either a SimpleXmlElement object or a DOMDocument.
* ##### [loadHtml()](#loadHtml()) public static
Parse the input html string and create either a SimpleXmlElement object or a DOMDocument.
* ##### [toArray()](#toArray()) public static
Returns this XML structure as an array.
Method Detail
-------------
### \_createChild() protected static
```
_createChild(array<string, mixed> $data): void
```
Helper to \_fromArray(). It will create children of arrays
#### Parameters
`array<string, mixed>` $data Array with information to create children
#### Returns
`void`
### \_fromArray() protected static
```
_fromArray(DOMDocument $dom, DOMDocumentDOMElement $node, array $data, string $format): void
```
Recursive method to create children from array
#### Parameters
`DOMDocument` $dom Handler to DOMDocument
`DOMDocumentDOMElement` $node Handler to DOMElement (child)
`array` $data Array of data to append to the $node.
`string` $format Either 'attributes' or 'tags'. This determines where nested keys go.
#### Returns
`void`
#### Throws
`Cake\Utility\Exception\XmlException`
### \_loadXml() protected static
```
_loadXml(string $input, array<string, mixed> $options): SimpleXMLElementDOMDocument
```
Parse the input data and create either a SimpleXmlElement object or a DOMDocument.
#### Parameters
`string` $input The input to load.
`array<string, mixed>` $options The options to use. See Xml::build()
#### Returns
`SimpleXMLElementDOMDocument`
#### Throws
`Cake\Utility\Exception\XmlException`
### \_toArray() protected static
```
_toArray(SimpleXMLElement $xml, array<string, mixed> $parentData, string $ns, array<string> $namespaces): void
```
Recursive method to toArray
#### Parameters
`SimpleXMLElement` $xml SimpleXMLElement object
`array<string, mixed>` $parentData Parent array with data
`string` $ns Namespace of current child
`array<string>` $namespaces List of namespaces in XML
#### Returns
`void`
### build() public static
```
build(object|array|string $input, array<string, mixed> $options = []): SimpleXMLElementDOMDocument
```
Initialize SimpleXMLElement or DOMDocument from a given XML string, file path, URL or array.
### Usage:
Building XML from a string:
```
$xml = Xml::build('<example>text</example>');
```
Building XML from string (output DOMDocument):
```
$xml = Xml::build('<example>text</example>', ['return' => 'domdocument']);
```
Building XML from a file path:
```
$xml = Xml::build('/path/to/an/xml/file.xml');
```
Building XML from a remote URL:
```
use Cake\Http\Client;
$http = new Client();
$response = $http->get('http://example.com/example.xml');
$xml = Xml::build($response->body());
```
Building from an array:
```
$value = [
'tags' => [
'tag' => [
[
'id' => '1',
'name' => 'defect'
],
[
'id' => '2',
'name' => 'enhancement'
]
]
]
];
$xml = Xml::build($value);
```
When building XML from an array ensure that there is only one top level element.
### Options
* `return` Can be 'simplexml' to return object of SimpleXMLElement or 'domdocument' to return DOMDocument.
* `loadEntities` Defaults to false. Set to true to enable loading of `<!ENTITY` definitions. This is disabled by default for security reasons.
* `readFile` Set to true to enable file reading. This is disabled by default to prevent local filesystem access. Only enable this setting when the input is safe.
* `parseHuge` Enable the `LIBXML_PARSEHUGE` flag.
If using array as input, you can pass `options` from Xml::fromArray.
#### Parameters
`object|array|string` $input XML string, a path to a file, a URL or an array
`array<string, mixed>` $options optional The options to use
#### Returns
`SimpleXMLElementDOMDocument`
#### Throws
`Cake\Utility\Exception\XmlException`
### fromArray() public static
```
fromArray(object|array $input, array<string, mixed> $options = []): SimpleXMLElementDOMDocument
```
Transform an array into a SimpleXMLElement
### Options
* `format` If create children ('tags') or attributes ('attributes').
* `pretty` Returns formatted Xml when set to `true`. Defaults to `false`
* `version` Version of XML document. Default is 1.0.
* `encoding` Encoding of XML document. If null remove from XML header. Defaults to the application's encoding
* `return` If return object of SimpleXMLElement ('simplexml') or DOMDocument ('domdocument'). Default is SimpleXMLElement.
Using the following data:
```
$value = [
'root' => [
'tag' => [
'id' => 1,
'value' => 'defect',
'@' => 'description'
]
]
];
```
Calling `Xml::fromArray($value, 'tags');` Will generate:
`<root><tag><id>1</id><value>defect</value>description</tag></root>`
And calling `Xml::fromArray($value, 'attributes');` Will generate:
`<root><tag id="1" value="defect">description</tag></root>`
#### Parameters
`object|array` $input Array with data or a collection instance.
`array<string, mixed>` $options optional The options to use.
#### Returns
`SimpleXMLElementDOMDocument`
#### Throws
`Cake\Utility\Exception\XmlException`
### load() protected static
```
load(string $input, array<string, mixed> $options, Closure $callable): SimpleXMLElementDOMDocument
```
Parse the input data and create either a SimpleXmlElement object or a DOMDocument.
#### Parameters
`string` $input The input to load.
`array<string, mixed>` $options The options to use. See Xml::build()
`Closure` $callable Closure that should return SimpleXMLElement or DOMDocument instance.
#### Returns
`SimpleXMLElementDOMDocument`
#### Throws
`Cake\Utility\Exception\XmlException`
### loadHtml() public static
```
loadHtml(string $input, array<string, mixed> $options = []): SimpleXMLElementDOMDocument
```
Parse the input html string and create either a SimpleXmlElement object or a DOMDocument.
#### Parameters
`string` $input The input html string to load.
`array<string, mixed>` $options optional The options to use. See Xml::build()
#### Returns
`SimpleXMLElementDOMDocument`
#### Throws
`Cake\Utility\Exception\XmlException`
### toArray() public static
```
toArray(SimpleXMLElementDOMDocumentDOMNode $obj): array
```
Returns this XML structure as an array.
#### Parameters
`SimpleXMLElementDOMDocumentDOMNode` $obj SimpleXMLElement, DOMDocument or DOMNode instance
#### Returns
`array`
#### Throws
`Cake\Utility\Exception\XmlException`
cakephp Class ExtractIterator Class ExtractIterator
======================
Creates an iterator from another iterator that extract the requested column or property based on a path
**Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator)
Property Summary
----------------
* [$\_extractor](#%24_extractor) protected `callable` A callable responsible for extracting a single value for each item in the collection.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Creates the iterator that will return the requested property for each value in the collection expressed in $path
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_serialize()](#__serialize()) public
Returns an array for serializing this of this object.
* ##### [\_\_unserialize()](#__unserialize()) public
Rebuilds the Collection instance.
* ##### [\_createMatcherFilter()](#_createMatcherFilter()) protected
Returns a callable that receives a value and will return whether it matches certain condition.
* ##### [\_extract()](#_extract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
* ##### [\_propertyExtractor()](#_propertyExtractor()) protected
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
* ##### [\_simpleExtract()](#_simpleExtract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path
* ##### [append()](#append()) public
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
* ##### [appendItem()](#appendItem()) public
Append a single item creating a new collection.
* ##### [avg()](#avg()) public
Returns the average of all the values extracted with $path or of this collection.
* ##### [buffered()](#buffered()) public
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
* ##### [cartesianProduct()](#cartesianProduct()) public
Create a new collection that is the cartesian product of the current collection
* ##### [chunk()](#chunk()) public
Breaks the collection into smaller arrays of the given size.
* ##### [chunkWithKeys()](#chunkWithKeys()) public
Breaks the collection into smaller arrays of the given size.
* ##### [combine()](#combine()) public
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
* ##### [compile()](#compile()) public
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
* ##### [contains()](#contains()) public
Returns true if $value is present in this collection. Comparisons are made both by value and type.
* ##### [count()](#count()) public
Returns the amount of elements in the collection.
* ##### [countBy()](#countBy()) public
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
* ##### [countKeys()](#countKeys()) public
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
* ##### [current()](#current()) public
Returns the column value defined in $path or null if the path could not be followed
* ##### [each()](#each()) public
Applies a callback to the elements in this collection.
* ##### [every()](#every()) public
Returns true if all values in this collection pass the truth test provided in the callback.
* ##### [extract()](#extract()) public
Returns a new collection containing the column or property value found in each of the elements.
* ##### [filter()](#filter()) public
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
* ##### [first()](#first()) public
Returns the first result in this collection
* ##### [firstMatch()](#firstMatch()) public
Returns the first result matching all the key-value pairs listed in conditions.
* ##### [groupBy()](#groupBy()) public
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
* ##### [indexBy()](#indexBy()) public
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
* ##### [insert()](#insert()) public
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
* ##### [isEmpty()](#isEmpty()) public
Returns whether there are elements in this collection
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
* ##### [last()](#last()) public
Returns the last result in this collection
* ##### [lazy()](#lazy()) public
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
* ##### [listNested()](#listNested()) public
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
* ##### [map()](#map()) public
Returns another collection after modifying each of the values in this one using the provided callable.
* ##### [match()](#match()) public
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
* ##### [max()](#max()) public
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [median()](#median()) public
Returns the median of all the values extracted with $path or of this collection.
* ##### [min()](#min()) public
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [nest()](#nest()) public
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
* ##### [newCollection()](#newCollection()) protected
Returns a new collection.
* ##### [optimizeUnwrap()](#optimizeUnwrap()) protected
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
* ##### [prepend()](#prepend()) public
Prepend a set of items to a collection creating a new collection
* ##### [prependItem()](#prependItem()) public
Prepend a single item creating a new collection.
* ##### [reduce()](#reduce()) public
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
* ##### [reject()](#reject()) public
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
* ##### [sample()](#sample()) public
Returns a new collection with maximum $size random elements from this collection
* ##### [serialize()](#serialize()) public
Returns a string representation of this object that can be used to reconstruct it
* ##### [shuffle()](#shuffle()) public
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
* ##### [skip()](#skip()) public
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
* ##### [some()](#some()) public
Returns true if any of the values in this collection pass the truth test provided in the callback.
* ##### [sortBy()](#sortBy()) public
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
* ##### [stopWhen()](#stopWhen()) public
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
* ##### [sumOf()](#sumOf()) public
Returns the total sum of all the values extracted with $matcher or of this collection.
* ##### [take()](#take()) public
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
* ##### [takeLast()](#takeLast()) public
Returns the last N elements of a collection
* ##### [through()](#through()) public
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
* ##### [toArray()](#toArray()) public
Returns an array representation of the results
* ##### [toList()](#toList()) public
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
* ##### [transpose()](#transpose()) public
Transpose rows and columns into columns and rows
* ##### [unfold()](#unfold()) public
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
* ##### [unserialize()](#unserialize()) public
Unserializes the passed string and rebuilds the Collection instance
* ##### [unwrap()](#unwrap()) public
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
* ##### [zip()](#zip()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
* ##### [zipWith()](#zipWith()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Method Detail
-------------
### \_\_construct() public
```
__construct(iterable $items, callable|string $path)
```
Creates the iterator that will return the requested property for each value in the collection expressed in $path
### Example:
Extract the user name for all comments in the array:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extractor = new ExtractIterator($items, 'comment.user.name'');
```
#### Parameters
`iterable` $items The list of values to iterate
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_serialize() public
```
__serialize(): array
```
Returns an array for serializing this of this object.
#### Returns
`array`
### \_\_unserialize() public
```
__unserialize(array $data): void
```
Rebuilds the Collection instance.
#### Parameters
`array` $data Data array.
#### Returns
`void`
### \_createMatcherFilter() protected
```
_createMatcherFilter(array $conditions): Closure
```
Returns a callable that receives a value and will return whether it matches certain condition.
#### Parameters
`array` $conditions A key-value list of conditions to match where the key is the property path to get from the current item and the value is the value to be compared the item with.
#### Returns
`Closure`
### \_extract() protected
```
_extract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### \_propertyExtractor() protected
```
_propertyExtractor(callable|string $path): callable
```
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
#### Parameters
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
#### Returns
`callable`
### \_simpleExtract() protected
```
_simpleExtract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### append() public
```
append(iterable $items): self
```
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
#### Parameters
`iterable` $items #### Returns
`self`
### appendItem() public
```
appendItem(mixed $item, mixed $key = null): self
```
Append a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### avg() public
```
avg(callable|string|null $path = null): float|int|null
```
Returns the average of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
```
The average of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### buffered() public
```
buffered(): self
```
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
#### Returns
`self`
### cartesianProduct() public
```
cartesianProduct(callable|null $operation = null, callable|null $filter = null): Cake\Collection\CollectionInterface
```
Create a new collection that is the cartesian product of the current collection
In order to create a carteisan product a collection must contain a single dimension of data.
### Example
```
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
```
#### Parameters
`callable|null` $operation optional A callable that allows you to customize the product result.
`callable|null` $filter optional A filtering callback that must return true for a result to be part of the final results.
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### chunk() public
```
chunk(int $chunkSize): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
```
#### Parameters
`int` $chunkSize #### Returns
`self`
### chunkWithKeys() public
```
chunkWithKeys(int $chunkSize, bool $keepKeys = true): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
```
#### Parameters
`int` $chunkSize `bool` $keepKeys optional #### Returns
`self`
### combine() public
```
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): self
```
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
### Examples:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar']
];
```
#### Parameters
`callable|string` $keyPath `callable|string` $valuePath `callable|string|null` $groupPath optional #### Returns
`self`
### compile() public
```
compile(bool $keepKeys = true): self
```
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
### Example:
```
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
```
In the above example, had the collection not been compiled before, the iterations for `map`, `sortBy` and `extract` would've been executed twice: once for getting `$isJohnHere` and once for `$allButJohn`
You can think of this method as a way to create save points for complex calculations in a collection.
#### Parameters
`bool` $keepKeys optional #### Returns
`self`
### contains() public
```
contains(mixed $value): bool
```
Returns true if $value is present in this collection. Comparisons are made both by value and type.
#### Parameters
`mixed` $value #### Returns
`bool`
### count() public
```
count(): int
```
Returns the amount of elements in the collection.
WARNINGS:
---------
### Will change the current position of the iterator:
Calling this method at the same time that you are iterating this collections, for example in a foreach, will result in undefined behavior. Avoid doing this.
### Consumes all elements for NoRewindIterator collections:
On certain type of collections, calling this method may render unusable afterwards. That is, you may not be able to get elements out of it, or to iterate on it anymore.
Specifically any collection wrapping a Generator (a function with a yield statement) or a unbuffered database cursor will not accept any other function calls after calling `count()` on it.
Create a new collection with `buffered()` method to overcome this problem.
### Can report more elements than unique keys:
Any collection constructed by appending collections together, or by having internal iterators returning duplicate keys, will report a larger amount of elements using this functions than the final amount of elements when converting the collections to a keyed array. This is because duplicate keys will be collapsed into a single one in the final array, whereas this count method is only concerned by the amount of elements after converting it to a plain list.
If you need the count of elements after taking the keys in consideration (the count of unique keys), you can call `countKeys()`
#### Returns
`int`
### countBy() public
```
countBy(callable|string $path): self
```
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### countKeys() public
```
countKeys(): int
```
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
This method comes with a number of caveats. Please refer to `CollectionInterface::count()` for details.
#### Returns
`int`
### current() public
```
current(): mixed
```
Returns the column value defined in $path or null if the path could not be followed
#### Returns
`mixed`
### each() public
```
each(callable $callback): $this
```
Applies a callback to the elements in this collection.
### Example:
```
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
```
#### Parameters
`callable` $callback #### Returns
`$this`
### every() public
```
every(callable $callback): bool
```
Returns true if all values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
```
Empty collections always return true.
#### Parameters
`callable` $callback #### Returns
`bool`
### extract() public
```
extract(callable|string $path): self
```
Returns a new collection containing the column or property value found in each of the elements.
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
### Example:
Extract the user name for all comments in the array:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
```
It is also possible to extract a flattened collection out of nested properties
```
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
```
#### Parameters
`callable|string` $path #### Returns
`self`
### filter() public
```
filter(callable|null $callback = null): self
```
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### first() public
```
first(): mixed
```
Returns the first result in this collection
#### Returns
`mixed`
### firstMatch() public
```
firstMatch(array $conditions): mixed
```
Returns the first result matching all the key-value pairs listed in conditions.
#### Parameters
`array` $conditions #### Returns
`mixed`
### groupBy() public
```
groupBy(callable|string $path): self
```
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### indexBy() public
```
indexBy(callable|string $path): self
```
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### insert() public
```
insert(string $path, mixed $values): self
```
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
### Example:
Insert ages into a collection containing users:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
```
#### Parameters
`string` $path `mixed` $values #### Returns
`self`
### isEmpty() public
```
isEmpty(): bool
```
Returns whether there are elements in this collection
### Example:
```
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
```
```
(new Collection([]))->isEmpty(); // true
```
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): array
```
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
Part of JsonSerializable interface.
#### Returns
`array`
### last() public
```
last(): mixed
```
Returns the last result in this collection
#### Returns
`mixed`
### lazy() public
```
lazy(): self
```
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
A lazy collection can only be iterated once. A second attempt results in an error.
#### Returns
`self`
### listNested() public
```
listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): self
```
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
* desc: RecursiveIteratorIterator::SELF\_FIRST
* asc: RecursiveIteratorIterator::CHILD\_FIRST
* leaves: RecursiveIteratorIterator::LEAVES\_ONLY
### Example:
```
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
```
#### Parameters
`string|int` $order optional `callable|string` $nestingKey optional #### Returns
`self`
### map() public
```
map(callable $callback): self
```
Returns another collection after modifying each of the values in this one using the provided callable.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Getting a collection of booleans where true indicates if a person is female:
```
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### match() public
```
match(array $conditions): self
```
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
### Example:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
]
```
#### Parameters
`array` $conditions #### Returns
`self`
### max() public
```
max(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### median() public
```
median(callable|string|null $path = null): float|int|null
```
Returns the median of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
```
The median of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### min() public
```
min(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### nest() public
```
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self
```
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
#### Parameters
`callable|string` $idPath `callable|string` $parentPath `string` $nestingKey optional #### Returns
`self`
### newCollection() protected
```
newCollection(mixed ...$args): Cake\Collection\CollectionInterface
```
Returns a new collection.
Allows classes which use this trait to determine their own type of returned collection interface
#### Parameters
`mixed` ...$args Constructor arguments.
#### Returns
`Cake\Collection\CollectionInterface`
### optimizeUnwrap() protected
```
optimizeUnwrap(): iterable
```
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
#### Returns
`iterable`
### prepend() public
```
prepend(mixed $items): self
```
Prepend a set of items to a collection creating a new collection
#### Parameters
`mixed` $items #### Returns
`self`
### prependItem() public
```
prependItem(mixed $item, mixed $key = null): self
```
Prepend a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### reduce() public
```
reduce(callable $callback, mixed $initial = null): mixed
```
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
#### Parameters
`callable` $callback `mixed` $initial optional #### Returns
`mixed`
### reject() public
```
reject(callable $callback): self
```
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### sample() public
```
sample(int $length = 10): self
```
Returns a new collection with maximum $size random elements from this collection
#### Parameters
`int` $length optional #### Returns
`self`
### serialize() public
```
serialize(): string
```
Returns a string representation of this object that can be used to reconstruct it
#### Returns
`string`
### shuffle() public
```
shuffle(): self
```
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
#### Returns
`self`
### skip() public
```
skip(int $length): self
```
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
#### Parameters
`int` $length #### Returns
`self`
### some() public
```
some(callable $callback): bool
```
Returns true if any of the values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
```
#### Parameters
`callable` $callback #### Returns
`bool`
### sortBy() public
```
sortBy(callable|string $path, int $order = \SORT_DESC, int $sort = \SORT_NUMERIC): self
```
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
### Example:
```
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
```
#### Parameters
`callable|string` $path `int` $order optional `int` $sort optional #### Returns
`self`
### stopWhen() public
```
stopWhen(callable|array $condition): self
```
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
### Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
```
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
```
Get elements until the first unapproved message is found:
```
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
```
#### Parameters
`callable|array` $condition #### Returns
`self`
### sumOf() public
```
sumOf(callable|string|null $path = null): float|int
```
Returns the total sum of all the values extracted with $matcher or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
```
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int`
### take() public
```
take(int $length = 1, int $offset = 0): self
```
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
#### Parameters
`int` $length optional `int` $offset optional #### Returns
`self`
### takeLast() public
```
takeLast(int $length): self
```
Returns the last N elements of a collection
### Example:
```
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
```
#### Parameters
`int` $length #### Returns
`self`
### through() public
```
through(callable $callback): self
```
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
### Example:
```
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### toArray() public
```
toArray(bool $keepKeys = true): array
```
Returns an array representation of the results
#### Parameters
`bool` $keepKeys optional #### Returns
`array`
### toList() public
```
toList(): array
```
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
#### Returns
`array`
### transpose() public
```
transpose(): Cake\Collection\CollectionInterface
```
Transpose rows and columns into columns and rows
### Example:
```
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
```
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### unfold() public
```
unfold(callable|null $callback = null): self
```
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
### Example:
```
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
```
Using a transformer
```
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### unserialize() public
```
unserialize(string $collection): void
```
Unserializes the passed string and rebuilds the Collection instance
#### Parameters
`string` $collection The serialized collection
#### Returns
`void`
### unwrap() public
```
unwrap(): Traversable
```
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
#### Returns
`Traversable`
### zip() public
```
zip(iterable $items): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
### Example:
```
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
```
#### Parameters
`iterable` $items #### Returns
`self`
### zipWith() public
```
zipWith(iterable $items, callable $callback): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
The resulting element will be the return value of the $callable function.
### Example:
```
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
```
#### Parameters
`iterable` $items `callable` $callback #### Returns
`self`
Property Detail
---------------
### $\_extractor protected
A callable responsible for extracting a single value for each item in the collection.
#### Type
`callable`
| programming_docs |
cakephp Namespace Exception Namespace Exception
===================
### Classes
* ##### [XmlException](class-cake.utility.exception.xmlexception)
Exception class for Xml. This exception will be thrown from Xml when it encounters an error.
cakephp Class ConsoleInputSubcommand Class ConsoleInputSubcommand
=============================
An object to represent a single subcommand used in the command line. Created when you call ConsoleOptionParser::addSubcommand()
**Namespace:** [Cake\Console](namespace-cake.console)
**See:** \Cake\Console\ConsoleOptionParser::addSubcommand()
Property Summary
----------------
* [$\_help](#%24_help) protected `string` Help string for the subcommand
* [$\_name](#%24_name) protected `string` Name of the subcommand
* [$\_parser](#%24_parser) protected `Cake\Console\ConsoleOptionParser|null` The ConsoleOptionParser for this subcommand.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Make a new Subcommand
* ##### [getRawHelp()](#getRawHelp()) public
Get the raw help string for this command
* ##### [help()](#help()) public
Generate the help for this this subcommand.
* ##### [name()](#name()) public
Get the value of the name attribute.
* ##### [parser()](#parser()) public
Get the usage value for this option
* ##### [xml()](#xml()) public
Append this subcommand to the Parent element
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed>|string $name, string $help = '', Cake\Console\ConsoleOptionParser|array<string, mixed>|null $parser = null)
```
Make a new Subcommand
#### Parameters
`array<string, mixed>|string` $name The long name of the subcommand, or an array with all the properties.
`string` $help optional The help text for this option.
`Cake\Console\ConsoleOptionParser|array<string, mixed>|null` $parser optional A parser for this subcommand. Either a ConsoleOptionParser, or an array that can be used with ConsoleOptionParser::buildFromArray().
### getRawHelp() public
```
getRawHelp(): string
```
Get the raw help string for this command
#### Returns
`string`
### help() public
```
help(int $width = 0): string
```
Generate the help for this this subcommand.
#### Parameters
`int` $width optional The width to make the name of the subcommand.
#### Returns
`string`
### name() public
```
name(): string
```
Get the value of the name attribute.
#### Returns
`string`
### parser() public
```
parser(): Cake\Console\ConsoleOptionParser|null
```
Get the usage value for this option
#### Returns
`Cake\Console\ConsoleOptionParser|null`
### xml() public
```
xml(SimpleXMLElement $parent): SimpleXMLElement
```
Append this subcommand to the Parent element
#### Parameters
`SimpleXMLElement` $parent The parent element.
#### Returns
`SimpleXMLElement`
Property Detail
---------------
### $\_help protected
Help string for the subcommand
#### Type
`string`
### $\_name protected
Name of the subcommand
#### Type
`string`
### $\_parser protected
The ConsoleOptionParser for this subcommand.
#### Type
`Cake\Console\ConsoleOptionParser|null`
cakephp Namespace Routing Namespace Routing
=================
### Namespaces
* [Cake\Routing\Exception](namespace-cake.routing.exception)
* [Cake\Routing\Middleware](namespace-cake.routing.middleware)
* [Cake\Routing\Route](namespace-cake.routing.route)
### Interfaces
* ##### [RoutingApplicationInterface](interface-cake.routing.routingapplicationinterface)
Interface for applications that use routing.
### Classes
* ##### [Asset](class-cake.routing.asset)
Class for generating asset URLs.
* ##### [RouteBuilder](class-cake.routing.routebuilder)
Provides features for building routes inside scopes.
* ##### [RouteCollection](class-cake.routing.routecollection)
Contains a collection of routes.
* ##### [Router](class-cake.routing.router)
Parses the request URL into controller, action, and parameters. Uses the connected routes to match the incoming URL string to parameters that will allow the request to be dispatched. Also handles converting parameter lists into URL strings, using the connected routes. Routing allows you to decouple the way the world interacts with your application (URLs) and the implementation (controllers and actions).
cakephp Interface PropertyMarshalInterface Interface PropertyMarshalInterface
===================================
Behaviors implementing this interface can participate in entity marshalling.
This enables behaviors to define behavior for how the properties they provide/manage should be marshalled.
**Namespace:** [Cake\ORM](namespace-cake.orm)
Method Summary
--------------
* ##### [buildMarshalMap()](#buildMarshalMap()) public
Build a set of properties that should be included in the marshalling process.
Method Detail
-------------
### buildMarshalMap() public
```
buildMarshalMap(Cake\ORM\Marshaller $marshaller, array $map, array<string, mixed> $options): array
```
Build a set of properties that should be included in the marshalling process.
#### Parameters
`Cake\ORM\Marshaller` $marshaller The marhshaller of the table the behavior is attached to.
`array` $map The property map being built.
`array<string, mixed>` $options The options array used in the marshalling call.
#### Returns
`array`
cakephp Trait ModelAwareTrait Trait ModelAwareTrait
======================
Provides functionality for loading table classes and other repositories onto properties of the host object.
Example users of this trait are Cake\Controller\Controller and Cake\Console\Shell.
**Namespace:** [Cake\Datasource](namespace-cake.datasource)
**Deprecated:** 4.3.0 Use `Cake\ORM\Locator\LocatorAwareTrait` instead.
Property Summary
----------------
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Method Summary
--------------
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
Method Detail
-------------
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
Property Detail
---------------
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
cakephp Trait RulesAwareTrait Trait RulesAwareTrait
======================
A trait that allows a class to build and apply application. rules.
If the implementing class also implements EventAwareTrait, then events will be emitted when rules are checked.
The implementing class is expected to define the `RULES_CLASS` constant if they need to customize which class is used for rules objects.
**Namespace:** [Cake\Datasource](namespace-cake.datasource)
Property Summary
----------------
* [$\_rulesChecker](#%24_rulesChecker) protected `Cake\Datasource\RulesChecker` The domain rules to be applied to entities saved by this table
Method Summary
--------------
* ##### [buildRules()](#buildRules()) public
Returns a RulesChecker object after modifying the one that was supplied.
* ##### [checkRules()](#checkRules()) public
Returns whether the passed entity complies with all the rules stored in the rules checker.
* ##### [rulesChecker()](#rulesChecker()) public
Returns the RulesChecker for this instance.
Method Detail
-------------
### buildRules() public
```
buildRules(Cake\Datasource\RulesChecker $rules): Cake\Datasource\RulesChecker
```
Returns a RulesChecker object after modifying the one that was supplied.
Subclasses should override this method in order to initialize the rules to be applied to entities saved by this instance.
#### Parameters
`Cake\Datasource\RulesChecker` $rules The rules object to be modified.
#### Returns
`Cake\Datasource\RulesChecker`
### checkRules() public
```
checkRules(Cake\Datasource\EntityInterface $entity, string $operation = RulesChecker::CREATE, ArrayObject|array|null $options = null): bool
```
Returns whether the passed entity complies with all the rules stored in the rules checker.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for validity.
`string` $operation optional The operation being run. Either 'create', 'update' or 'delete'.
`ArrayObject|array|null` $options optional The options To be passed to the rules.
#### Returns
`bool`
### rulesChecker() public
```
rulesChecker(): Cake\Datasource\RulesChecker
```
Returns the RulesChecker for this instance.
A RulesChecker object is used to test an entity for validity on rules that may involve complex logic or data that needs to be fetched from relevant datasources.
#### Returns
`Cake\Datasource\RulesChecker`
#### See Also
\Cake\Datasource\RulesChecker Property Detail
---------------
### $\_rulesChecker protected
The domain rules to be applied to entities saved by this table
#### Type
`Cake\Datasource\RulesChecker`
cakephp Class IsUnique Class IsUnique
===============
Checks that a list of fields from an entity are unique in the table
**Namespace:** [Cake\ORM\Rule](namespace-cake.orm.rule)
Property Summary
----------------
* [$\_fields](#%24_fields) protected `array<string>` The list of fields to check
* [$\_options](#%24_options) protected `array<string, mixed>` The unique check options
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_\_invoke()](#__invoke()) public
Performs the uniqueness check
* ##### [\_alias()](#_alias()) protected
Add a model alias to all the keys in a set of conditions.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string> $fields, array<string, mixed> $options = [])
```
Constructor.
### Options
* `allowMultipleNulls` Allows any field to have multiple null values. Defaults to false.
#### Parameters
`array<string>` $fields The list of fields to check uniqueness for
`array<string, mixed>` $options optional The options for unique checks.
### \_\_invoke() public
```
__invoke(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options): bool
```
Performs the uniqueness check
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity from where to extract the fields where the `repository` key is required.
`array<string, mixed>` $options Options passed to the check,
#### Returns
`bool`
### \_alias() protected
```
_alias(string $alias, array $conditions): array<string, mixed>
```
Add a model alias to all the keys in a set of conditions.
#### Parameters
`string` $alias The alias to add.
`array` $conditions The conditions to alias.
#### Returns
`array<string, mixed>`
Property Detail
---------------
### $\_fields protected
The list of fields to check
#### Type
`array<string>`
### $\_options protected
The unique check options
#### Type
`array<string, mixed>`
cakephp Class MissingHelperException Class MissingHelperException
=============================
Used when a helper cannot be found.
**Namespace:** [Cake\View\Exception](namespace-cake.view.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional Either the string of the error message, or an array of attributes that are made available in the view, and sprintf()'d into Exception::$\_messageTemplate
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Trait FieldTrait Trait FieldTrait
=================
Contains the field property with a getter and a setter for it
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
Property Summary
----------------
* [$\_field](#%24_field) protected `Cake\Database\ExpressionInterface|array|string` The field name or expression to be used in the left hand side of the operator
Method Summary
--------------
* ##### [getField()](#getField()) public
Returns the field name
* ##### [setField()](#setField()) public
Sets the field name
Method Detail
-------------
### getField() public
```
getField(): Cake\Database\ExpressionInterface|array|string
```
Returns the field name
#### Returns
`Cake\Database\ExpressionInterface|array|string`
### setField() public
```
setField(Cake\Database\ExpressionInterface|array|string $field): void
```
Sets the field name
#### Parameters
`Cake\Database\ExpressionInterface|array|string` $field The field to compare with.
#### Returns
`void`
Property Detail
---------------
### $\_field protected
The field name or expression to be used in the left hand side of the operator
#### Type
`Cake\Database\ExpressionInterface|array|string`
cakephp Class Hash Class Hash
===========
Library of array functions for manipulating and extracting data from arrays or 'sets' of data.
`Hash` provides an improved interface, more consistent and predictable set of features over `Set`. While it lacks the spotty support for pseudo Xpath, its more fully featured dot notation provides similar features in a more consistent implementation.
**Namespace:** [Cake\Utility](namespace-cake.utility)
**Link:** https://book.cakephp.org/4/en/core-libraries/hash.html
Method Summary
--------------
* ##### [\_filter()](#_filter()) protected static
Callback function for filtering.
* ##### [\_matchToken()](#_matchToken()) protected static
Check a key against a token.
* ##### [\_matches()](#_matches()) protected static
Checks whether $data matches the attribute patterns
* ##### [\_merge()](#_merge()) protected static
Merge helper function to reduce duplicated code between merge() and expand().
* ##### [\_simpleOp()](#_simpleOp()) protected static
Perform a simple insert/remove operation.
* ##### [\_splitConditions()](#_splitConditions()) protected static
Split token conditions
* ##### [\_squash()](#_squash()) protected static
Helper method for sort() Squashes an array to a single hash so it can be sorted.
* ##### [apply()](#apply()) public static
Apply a callback to a set of extracted values using `$function`. The function will get the extracted values as the first argument.
* ##### [check()](#check()) public static
Test whether a given path exists in $data. This method uses the same path syntax as Hash::extract()
* ##### [combine()](#combine()) public static
Creates an associative array using `$keyPath` as the path to build its keys, and optionally `$valuePath` as path to get the values. If `$valuePath` is not specified, all values will be initialized to null (useful for Hash::merge). You can optionally group the values by what is obtained when following the path specified in `$groupPath`.
* ##### [contains()](#contains()) public static
Determines if one array contains the exact keys and values of another.
* ##### [diff()](#diff()) public static
Computes the difference between two complex arrays. This method differs from the built-in array\_diff() in that it will preserve keys and work on multi-dimensional arrays.
* ##### [dimensions()](#dimensions()) public static
Counts the dimensions of an array. Only considers the dimension of the first element in the array.
* ##### [expand()](#expand()) public static
Expands a flat array to a nested array.
* ##### [extract()](#extract()) public static
Gets the values from an array matching the $path expression. The path expression is a dot separated expression, that can contain a set of patterns and expressions:
* ##### [filter()](#filter()) public static
Recursively filters a data set.
* ##### [flatten()](#flatten()) public static
Collapses a multi-dimensional array into a single dimension, using a delimited array path for each array element's key, i.e. [['Foo' => ['Bar' => 'Far']]] becomes ['0.Foo.Bar' => 'Far'].)
* ##### [format()](#format()) public static
Returns a formatted series of values extracted from `$data`, using `$format` as the format and `$paths` as the values to extract.
* ##### [get()](#get()) public static
Get a single value specified by $path out of $data. Does not support the full dot notation feature set, but is faster for simple read operations.
* ##### [insert()](#insert()) public static
Insert $values into an array with the given $path. You can use `{n}` and `{s}` elements to insert $data multiple times.
* ##### [map()](#map()) public static
Map a callback across all elements in a set. Can be provided a path to only modify slices of the set.
* ##### [maxDimensions()](#maxDimensions()) public static
Counts the dimensions of *all* array elements. Useful for finding the maximum number of dimensions in a mixed array.
* ##### [merge()](#merge()) public static
This function can be thought of as a hybrid between PHP's `array_merge` and `array_merge_recursive`.
* ##### [mergeDiff()](#mergeDiff()) public static
Merges the difference between $data and $compare onto $data.
* ##### [nest()](#nest()) public static
Takes in a flat array and returns a nested array
* ##### [normalize()](#normalize()) public static
Normalizes an array, and converts it to a standard format.
* ##### [numeric()](#numeric()) public static
Checks to see if all the values in the array are numeric
* ##### [reduce()](#reduce()) public static
Reduce a set of extracted values using `$function`.
* ##### [remove()](#remove()) public static
Remove data matching $path from the $data array. You can use `{n}` and `{s}` to remove multiple elements from $data.
* ##### [sort()](#sort()) public static
Sorts an array by any value, determined by a Set-compatible path
Method Detail
-------------
### \_filter() protected static
```
_filter(mixed $var): bool
```
Callback function for filtering.
#### Parameters
`mixed` $var Array to filter.
#### Returns
`bool`
### \_matchToken() protected static
```
_matchToken(mixed $key, string $token): bool
```
Check a key against a token.
#### Parameters
`mixed` $key The key in the array being searched.
`string` $token The token being matched.
#### Returns
`bool`
### \_matches() protected static
```
_matches(ArrayAccess|array $data, string $selector): bool
```
Checks whether $data matches the attribute patterns
#### Parameters
`ArrayAccess|array` $data Array of data to match.
`string` $selector The patterns to match.
#### Returns
`bool`
### \_merge() protected static
```
_merge(array $stack, array $return): void
```
Merge helper function to reduce duplicated code between merge() and expand().
#### Parameters
`array` $stack The stack of operations to work with.
`array` $return The return value to operate on.
#### Returns
`void`
### \_simpleOp() protected static
```
_simpleOp(string $op, array $data, array<string> $path, mixed $values = null): array
```
Perform a simple insert/remove operation.
#### Parameters
`string` $op The operation to do.
`array` $data The data to operate on.
`array<string>` $path The path to work on.
`mixed` $values optional The values to insert when doing inserts.
#### Returns
`array`
### \_splitConditions() protected static
```
_splitConditions(string $token): array
```
Split token conditions
#### Parameters
`string` $token the token being splitted.
#### Returns
`array`
### \_squash() protected static
```
_squash(array $data, mixed $key = null): array
```
Helper method for sort() Squashes an array to a single hash so it can be sorted.
#### Parameters
`array` $data The data to squash.
`mixed` $key optional The key for the data.
#### Returns
`array`
### apply() public static
```
apply(array $data, string $path, callable $function): mixed
```
Apply a callback to a set of extracted values using `$function`. The function will get the extracted values as the first argument.
### Example
You can easily count the results of an extract using apply(). For example to count the comments on an Article:
```
$count = Hash::apply($data, 'Article.Comment.{n}', 'count');
```
You could also use a function like `array_sum` to sum the results.
```
$total = Hash::apply($data, '{n}.Item.price', 'array_sum');
```
#### Parameters
`array` $data The data to reduce.
`string` $path The path to extract from $data.
`callable` $function The function to call on each extracted value.
#### Returns
`mixed`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::apply
### check() public static
```
check(array $data, string $path): bool
```
Test whether a given path exists in $data. This method uses the same path syntax as Hash::extract()
Checking for paths that could target more than one element will make sure that at least one matching element exists.
#### Parameters
`array` $data The data to check.
`string` $path The path to check for.
#### Returns
`bool`
#### See Also
\Cake\Utility\Hash::extract() #### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::check
### combine() public static
```
combine(array $data, array<string>|string|null $keyPath, array<string>|string|null $valuePath = null, string|null $groupPath = null): array
```
Creates an associative array using `$keyPath` as the path to build its keys, and optionally `$valuePath` as path to get the values. If `$valuePath` is not specified, all values will be initialized to null (useful for Hash::merge). You can optionally group the values by what is obtained when following the path specified in `$groupPath`.
#### Parameters
`array` $data Array from where to extract keys and values
`array<string>|string|null` $keyPath A dot-separated string.
`array<string>|string|null` $valuePath optional A dot-separated string.
`string|null` $groupPath optional A dot-separated string.
#### Returns
`array`
#### Throws
`RuntimeException`
When keys and values count is unequal. #### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::combine
### contains() public static
```
contains(array $data, array $needle): bool
```
Determines if one array contains the exact keys and values of another.
#### Parameters
`array` $data The data to search through.
`array` $needle The values to file in $data
#### Returns
`bool`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::contains
### diff() public static
```
diff(array $data, array $compare): array
```
Computes the difference between two complex arrays. This method differs from the built-in array\_diff() in that it will preserve keys and work on multi-dimensional arrays.
#### Parameters
`array` $data First value
`array` $compare Second value
#### Returns
`array`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::diff
### dimensions() public static
```
dimensions(array $data): int
```
Counts the dimensions of an array. Only considers the dimension of the first element in the array.
If you have an un-even or heterogeneous array, consider using Hash::maxDimensions() to get the dimensions of the array.
#### Parameters
`array` $data Array to count dimensions on
#### Returns
`int`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::dimensions
### expand() public static
```
expand(array $data, string $separator = '.'): array
```
Expands a flat array to a nested array.
For example, unflattens an array that was collapsed with `Hash::flatten()` into a multi-dimensional array. So, `['0.Foo.Bar' => 'Far']` becomes `[['Foo' => ['Bar' => 'Far']]]`.
#### Parameters
`array` $data Flattened array
`string` $separator optional The delimiter used
#### Returns
`array`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::expand
### extract() public static
```
extract(ArrayAccess|array $data, string $path): ArrayAccess|array
```
Gets the values from an array matching the $path expression. The path expression is a dot separated expression, that can contain a set of patterns and expressions:
* `{n}` Matches any numeric key, or integer.
* `{s}` Matches any string key.
* `{*}` Matches any value.
* `Foo` Matches any key with the exact same value.
There are a number of attribute operators:
* `=`, `!=` Equality.
+ `>`, `<`, `>=`, `<=` Value comparison.
+ `=/.../` Regular expression pattern match.
Given a set of User array data, from a `$usersTable->find('all')` call:
* `1.User.name` Get the name of the user at index 1.
* `{n}.User.name` Get the name of every user in the set of users.
* `{n}.User[id].name` Get the name of every user with an id key.
* `{n}.User[id>=2].name` Get the name of every user with an id key greater than or equal to 2.
* `{n}.User[username=/^paul/]` Get User elements with username matching `^paul`.
* `{n}.User[id=1].name` Get the Users name with id matching `1`.
#### Parameters
`ArrayAccess|array` $data The data to extract from.
`string` $path The path to extract.
#### Returns
`ArrayAccess|array`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::extract
### filter() public static
```
filter(array $data, callable|array $callback = [Hash::class, '_filter']): array
```
Recursively filters a data set.
#### Parameters
`array` $data Either an array to filter, or value when in callback
`callable|array` $callback optional A function to filter the data with. Defaults to `static::_filter()` Which strips out all non-zero empty values.
#### Returns
`array`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::filter
### flatten() public static
```
flatten(array $data, string $separator = '.'): array
```
Collapses a multi-dimensional array into a single dimension, using a delimited array path for each array element's key, i.e. [['Foo' => ['Bar' => 'Far']]] becomes ['0.Foo.Bar' => 'Far'].)
#### Parameters
`array` $data Array to flatten
`string` $separator optional String used to separate array key elements in a path, defaults to '.'
#### Returns
`array`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::flatten
### format() public static
```
format(array $data, array<string> $paths, string $format): array<string>|null
```
Returns a formatted series of values extracted from `$data`, using `$format` as the format and `$paths` as the values to extract.
Usage:
```
$result = Hash::format($users, ['{n}.User.id', '{n}.User.name'], '%s : %s');
```
The `$format` string can use any format options that `vsprintf()` and `sprintf()` do.
#### Parameters
`array` $data Source array from which to extract the data
`array<string>` $paths An array containing one or more Hash::extract()-style key paths
`string` $format Format string into which values will be inserted, see sprintf()
#### Returns
`array<string>|null`
#### See Also
sprintf()
\Cake\Utility\Hash::extract() #### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::format
### get() public static
```
get(ArrayAccess|array $data, array<string>|string|int|null $path, mixed $default = null): mixed
```
Get a single value specified by $path out of $data. Does not support the full dot notation feature set, but is faster for simple read operations.
#### Parameters
`ArrayAccess|array` $data Array of data or object implementing \ArrayAccess interface to operate on.
`array<string>|string|int|null` $path The path being searched for. Either a dot separated string, or an array of path segments.
`mixed` $default optional The return value when the path does not exist
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::get
### insert() public static
```
insert(array $data, string $path, mixed $values = null): array
```
Insert $values into an array with the given $path. You can use `{n}` and `{s}` elements to insert $data multiple times.
#### Parameters
`array` $data The data to insert into.
`string` $path The path to insert at.
`mixed` $values optional The values to insert.
#### Returns
`array`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::insert
### map() public static
```
map(array $data, string $path, callable $function): array
```
Map a callback across all elements in a set. Can be provided a path to only modify slices of the set.
#### Parameters
`array` $data The data to map over, and extract data out of.
`string` $path The path to extract for mapping over.
`callable` $function The function to call on each extracted value.
#### Returns
`array`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::map
### maxDimensions() public static
```
maxDimensions(array $data): int
```
Counts the dimensions of *all* array elements. Useful for finding the maximum number of dimensions in a mixed array.
#### Parameters
`array` $data Array to count dimensions on
#### Returns
`int`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::maxDimensions
### merge() public static
```
merge(array $data, mixed $merge): array
```
This function can be thought of as a hybrid between PHP's `array_merge` and `array_merge_recursive`.
The difference between this method and the built-in ones, is that if an array key contains another array, then Hash::merge() will behave in a recursive fashion (unlike `array_merge`). But it will not act recursively for keys that contain scalar values (unlike `array_merge_recursive`).
This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.
#### Parameters
`array` $data Array to be merged
`mixed` $merge Array to merge with. The argument and all trailing arguments will be array cast when merged
#### Returns
`array`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::merge
### mergeDiff() public static
```
mergeDiff(array $data, array $compare): array
```
Merges the difference between $data and $compare onto $data.
#### Parameters
`array` $data The data to append onto.
`array` $compare The data to compare and append onto.
#### Returns
`array`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::mergeDiff
### nest() public static
```
nest(array $data, array<string, mixed> $options = []): array<array>
```
Takes in a flat array and returns a nested array
### Options:
* `children` The key name to use in the resultset for children.
* `idPath` The path to a key that identifies each entry. Should be compatible with Hash::extract(). Defaults to `{n}.$alias.id`
* `parentPath` The path to a key that identifies the parent of each entry. Should be compatible with Hash::extract(). Defaults to `{n}.$alias.parent_id`
* `root` The id of the desired top-most result.
#### Parameters
`array` $data The data to nest.
`array<string, mixed>` $options optional Options are:
#### Returns
`array<array>`
#### Throws
`InvalidArgumentException`
When providing invalid data. #### See Also
\Cake\Utility\Hash::extract() #### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::nest
### normalize() public static
```
normalize(array $data, bool $assoc = true): array
```
Normalizes an array, and converts it to a standard format.
#### Parameters
`array` $data List to normalize
`bool` $assoc optional If true, $data will be converted to an associative array.
#### Returns
`array`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::normalize
### numeric() public static
```
numeric(array $data): bool
```
Checks to see if all the values in the array are numeric
#### Parameters
`array` $data The array to check.
#### Returns
`bool`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::numeric
### reduce() public static
```
reduce(array $data, string $path, callable $function): mixed
```
Reduce a set of extracted values using `$function`.
#### Parameters
`array` $data The data to reduce.
`string` $path The path to extract from $data.
`callable` $function The function to call on each extracted value.
#### Returns
`mixed`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::reduce
### remove() public static
```
remove(array $data, string $path): array
```
Remove data matching $path from the $data array. You can use `{n}` and `{s}` to remove multiple elements from $data.
#### Parameters
`array` $data The data to operate on
`string` $path A path expression to use to remove.
#### Returns
`array`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::remove
### sort() public static
```
sort(array $data, string $path, string|int $dir = 'asc', array<string, mixed>|string $type = 'regular'): array
```
Sorts an array by any value, determined by a Set-compatible path
### Sort directions
* `asc` or \SORT\_ASC Sort ascending.
* `desc` or \SORT\_DESC Sort descending.
### Sort types
* `regular` For regular sorting (don't change types)
* `numeric` Compare values numerically
* `string` Compare values as strings
* `locale` Compare items as strings, based on the current locale
* `natural` Compare items as strings using "natural ordering" in a human friendly way Will sort foo10 below foo2 as an example.
To do case insensitive sorting, pass the type as an array as follows:
```
Hash::sort($data, 'some.attribute', 'asc', ['type' => 'regular', 'ignoreCase' => true]);
```
When using the array form, `type` defaults to 'regular'. The `ignoreCase` option defaults to `false`.
#### Parameters
`array` $data An array of data to sort
`string` $path A Set-compatible path to the array value
`string|int` $dir optional See directions above. Defaults to 'asc'.
`array<string, mixed>|string` $type optional See direction types above. Defaults to 'regular'.
#### Returns
`array`
#### Links
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::sort
| programming_docs |
cakephp Trait TypeConverterTrait Trait TypeConverterTrait
=========================
Type converter trait
**Namespace:** [Cake\Database](namespace-cake.database)
Method Summary
--------------
* ##### [cast()](#cast()) public
Converts a give value to a suitable database value based on type and return relevant internal statement type
* ##### [matchTypes()](#matchTypes()) public
Matches columns to corresponding types
Method Detail
-------------
### cast() public
```
cast(mixed $value, Cake\Database\TypeInterface|string|int $type = 'string'): array
```
Converts a give value to a suitable database value based on type and return relevant internal statement type
#### Parameters
`mixed` $value The value to cast
`Cake\Database\TypeInterface|string|int` $type optional The type name or type instance to use.
#### Returns
`array`
### matchTypes() public
```
matchTypes(array $columns, array $types): array
```
Matches columns to corresponding types
Both $columns and $types should either be numeric based or string key based at the same time.
#### Parameters
`array` $columns list or associative array of columns and parameters to be bound with types
`array` $types list or associative array of types
#### Returns
`array`
cakephp Class FormatterLocator Class FormatterLocator
=======================
A ServiceLocator implementation for loading and retaining formatter objects.
**Namespace:** [Cake\I18n](namespace-cake.i18n)
Property Summary
----------------
* [$converted](#%24converted) protected `array<bool>` Tracks whether a registry entry has been converted from a FQCN to a formatter object.
* [$registry](#%24registry) protected `array<string,Cake\I18n\FormatterInterface|class-stringCake\I18n\FormatterInterface>>` A registry to retain formatter objects.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [get()](#get()) public
Gets a formatter from the registry by name.
* ##### [set()](#set()) public
Sets a formatter into the registry by name.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, class-stringCake\I18n\FormatterInterface>> $registry = [])
```
Constructor.
#### Parameters
`array<string, class-stringCake\I18n\FormatterInterface>>` $registry optional An array of key-value pairs where the key is the formatter name the value is a FQCN for the formatter.
### get() public
```
get(string $name): Cake\I18n\FormatterInterface
```
Gets a formatter from the registry by name.
#### Parameters
`string` $name The formatter to retrieve.
#### Returns
`Cake\I18n\FormatterInterface`
#### Throws
`Cake\I18n\Exception\I18nException`
### set() public
```
set(string $name, class-stringCake\I18n\FormatterInterface> $className): void
```
Sets a formatter into the registry by name.
#### Parameters
`string` $name The formatter name.
`class-stringCake\I18n\FormatterInterface>` $className A FQCN for a formatter.
#### Returns
`void`
Property Detail
---------------
### $converted protected
Tracks whether a registry entry has been converted from a FQCN to a formatter object.
#### Type
`array<bool>`
### $registry protected
A registry to retain formatter objects.
#### Type
`array<string,Cake\I18n\FormatterInterface|class-stringCake\I18n\FormatterInterface>>`
cakephp Class MissingBehaviorException Class MissingBehaviorException
===============================
Used when a behavior cannot be found.
**Namespace:** [Cake\ORM\Exception](namespace-cake.orm.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional Either the string of the error message, or an array of attributes that are made available in the view, and sprintf()'d into Exception::$\_messageTemplate
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class HelpFormatter Class HelpFormatter
====================
HelpFormatter formats help for console shells. Can format to either text or XML formats. Uses ConsoleOptionParser methods to generate help.
Generally not directly used. Using $parser->help($command, 'xml'); is usually how you would access help. Or via the `--help=xml` option on the command line.
Xml output is useful for integration with other tools like IDE's or other build tools.
**Namespace:** [Cake\Console](namespace-cake.console)
Property Summary
----------------
* [$\_alias](#%24_alias) protected `string` Alias to display in the output.
* [$\_maxArgs](#%24_maxArgs) protected `int` The maximum number of arguments shown when generating usage.
* [$\_maxOptions](#%24_maxOptions) protected `int` The maximum number of options shown when generating usage.
* [$\_parser](#%24_parser) protected `Cake\Console\ConsoleOptionParser` Option parser.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Build the help formatter for an OptionParser
* ##### [\_generateUsage()](#_generateUsage()) protected
Generate the usage for a shell based on its arguments and options. Usage strings favor short options over the long ones. and optional args will be indicated with []
* ##### [\_getMaxLength()](#_getMaxLength()) protected
Iterate over a collection and find the longest named thing.
* ##### [setAlias()](#setAlias()) public
Set the alias
* ##### [text()](#text()) public
Get the help as formatted text suitable for output on the command line.
* ##### [xml()](#xml()) public
Get the help as an XML string.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Console\ConsoleOptionParser $parser)
```
Build the help formatter for an OptionParser
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser help is being generated for.
### \_generateUsage() protected
```
_generateUsage(): string
```
Generate the usage for a shell based on its arguments and options. Usage strings favor short options over the long ones. and optional args will be indicated with []
#### Returns
`string`
### \_getMaxLength() protected
```
_getMaxLength(arrayCake\Console\ConsoleInputOptionCake\Console\ConsoleInputArgumentCake\Console\ConsoleInputSubcommand> $collection): int
```
Iterate over a collection and find the longest named thing.
#### Parameters
`arrayCake\Console\ConsoleInputOptionCake\Console\ConsoleInputArgumentCake\Console\ConsoleInputSubcommand>` $collection The collection to find a max length of.
#### Returns
`int`
### setAlias() public
```
setAlias(string $alias): void
```
Set the alias
#### Parameters
`string` $alias The alias
#### Returns
`void`
### text() public
```
text(int $width = 72): string
```
Get the help as formatted text suitable for output on the command line.
#### Parameters
`int` $width optional The width of the help output.
#### Returns
`string`
### xml() public
```
xml(bool $string = true): SimpleXMLElement|string
```
Get the help as an XML string.
#### Parameters
`bool` $string optional Return the SimpleXml object or a string. Defaults to true.
#### Returns
`SimpleXMLElement|string`
Property Detail
---------------
### $\_alias protected
Alias to display in the output.
#### Type
`string`
### $\_maxArgs protected
The maximum number of arguments shown when generating usage.
#### Type
`int`
### $\_maxOptions protected
The maximum number of options shown when generating usage.
#### Type
`int`
### $\_parser protected
Option parser.
#### Type
`Cake\Console\ConsoleOptionParser`
cakephp Class ConsoleLog Class ConsoleLog
=================
Console logging. Writes logs to console output.
**Namespace:** [Cake\Log\Engine](namespace-cake.log.engine)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
* [$\_output](#%24_output) protected `Cake\Console\ConsoleOutput` Output stream
* [$formatter](#%24formatter) protected `Cake\Log\Formatter\AbstractFormatter`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructs a new Console Logger.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_format()](#_format()) protected deprecated
Formats the message to be logged.
* ##### [alert()](#alert()) public
Action must be taken immediately.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [critical()](#critical()) public
Critical conditions.
* ##### [debug()](#debug()) public
Detailed debug information.
* ##### [emergency()](#emergency()) public
System is unusable.
* ##### [error()](#error()) public
Runtime errors that do not require immediate action but should typically be logged and monitored.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [info()](#info()) public
Interesting events.
* ##### [interpolate()](#interpolate()) protected
Replaces placeholders in message string with context values.
* ##### [levels()](#levels()) public
Get the levels this logger is interested in.
* ##### [log()](#log()) public
Implements writing to console.
* ##### [notice()](#notice()) public
Normal but significant events.
* ##### [scopes()](#scopes()) public
Get the scopes this logger is interested in.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [warning()](#warning()) public
Exceptional occurrences that are not errors.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructs a new Console Logger.
Config
* `levels` string or array, levels the engine is interested in
* `scopes` string or array, scopes the engine is interested in
* `stream` the path to save logs on.
* `outputAs` integer or ConsoleOutput::[RAW|PLAIN|COLOR]
* `dateFormat` PHP date() format.
#### Parameters
`array<string, mixed>` $config optional Options for the FileLog, see above.
#### Throws
`InvalidArgumentException`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_format() protected
```
_format(string $message, array $context = []): string
```
Formats the message to be logged.
The context can optionally be used by log engines to interpolate variables or add additional info to the logged message.
#### Parameters
`string` $message The message to be formatted.
`array` $context optional Additional logging information for the message.
#### Returns
`string`
### alert() public
```
alert(string $message, mixed[] $context = array()): void
```
Action must be taken immediately.
Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
```
$this->configShallow('key', $value);
```
Setting a nested value:
```
$this->configShallow('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->configShallow(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### critical() public
```
critical(string $message, mixed[] $context = array()): void
```
Critical conditions.
Example: Application component unavailable, unexpected exception.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### debug() public
```
debug(string $message, mixed[] $context = array()): void
```
Detailed debug information.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### emergency() public
```
emergency(string $message, mixed[] $context = array()): void
```
System is unusable.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### error() public
```
error(string $message, mixed[] $context = array()): void
```
Runtime errors that do not require immediate action but should typically be logged and monitored.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### Usage
Reading the whole config:
```
$this->getConfig();
```
Reading a specific value:
```
$this->getConfig('key');
```
Reading a nested value:
```
$this->getConfig('some.nested.key');
```
Reading with default value:
```
$this->getConfig('some-key', 'default-value');
```
#### Parameters
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### info() public
```
info(string $message, mixed[] $context = array()): void
```
Interesting events.
Example: User logs in, SQL logs.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### interpolate() protected
```
interpolate(string $message, array $context = []): string
```
Replaces placeholders in message string with context values.
#### Parameters
`string` $message Formatted string
`array` $context optional Context for placeholder values.
#### Returns
`string`
### levels() public
```
levels(): array<string>
```
Get the levels this logger is interested in.
#### Returns
`array<string>`
### log() public
```
log(mixed $level, string $message, mixed[] $context = []): void
```
Implements writing to console.
#### Parameters
`mixed` $level The severity level of log you are making.
`string` $message The message you want to log.
`mixed[]` $context optional Additional information about the logged message
#### Returns
`void`
#### See Also
\Cake\Log\Log::$\_levels ### notice() public
```
notice(string $message, mixed[] $context = array()): void
```
Normal but significant events.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### scopes() public
```
scopes(): array<string>|false
```
Get the scopes this logger is interested in.
#### Returns
`array<string>|false`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### Usage
Setting a specific value:
```
$this->setConfig('key', $value);
```
Setting a nested value:
```
$this->setConfig('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->setConfig(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### warning() public
```
warning(string $message, mixed[] $context = array()): void
```
Exceptional occurrences that are not errors.
Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
### $\_output protected
Output stream
#### Type
`Cake\Console\ConsoleOutput`
### $formatter protected
#### Type
`Cake\Log\Formatter\AbstractFormatter`
| programming_docs |
cakephp Class Response Class Response
===============
Implements methods for HTTP responses.
All the following examples assume that `$response` is an instance of this class.
### Get header values
Header names are case-insensitive, but normalized to Title-Case when the response is parsed.
```
$val = $response->getHeaderLine('content-type');
```
Will read the Content-Type header. You can get all set headers using:
```
$response->getHeaders();
```
### Get the response body
You can access the response body stream using:
```
$content = $response->getBody();
```
You can get the body string using:
```
$content = $response->getStringBody();
```
If your response body is in XML or JSON you can use special content type specific accessors to read the decoded data. JSON data will be returned as arrays, while XML data will be returned as SimpleXML nodes:
```
// Get as XML
$content = $response->getXml()
// Get as JSON
$content = $response->getJson()
```
If the response cannot be decoded, null will be returned.
### Check the status code
You can access the response status code using:
```
$content = $response->getStatusCode();
```
**Namespace:** [Cake\Http\Client](namespace-cake.http.client)
Constants
---------
* `string` **METHOD\_DELETE**
```
'DELETE'
```
HTTP DELETE method
* `string` **METHOD\_GET**
```
'GET'
```
HTTP GET method
* `string` **METHOD\_HEAD**
```
'HEAD'
```
HTTP HEAD method
* `string` **METHOD\_OPTIONS**
```
'OPTIONS'
```
HTTP OPTIONS method
* `string` **METHOD\_PATCH**
```
'PATCH'
```
HTTP PATCH method
* `string` **METHOD\_POST**
```
'POST'
```
HTTP POST method
* `string` **METHOD\_PUT**
```
'PUT'
```
HTTP PUT method
* `string` **METHOD\_TRACE**
```
'TRACE'
```
HTTP TRACE method
* `int` **STATUS\_ACCEPTED**
```
202
```
HTTP 202 code
* `int` **STATUS\_CREATED**
```
201
```
HTTP 201 code
* `int` **STATUS\_FOUND**
```
302
```
HTTP 302 code
* `int` **STATUS\_MOVED\_PERMANENTLY**
```
301
```
HTTP 301 code
* `int` **STATUS\_NON\_AUTHORITATIVE\_INFORMATION**
```
203
```
HTTP 203 code
* `int` **STATUS\_NO\_CONTENT**
```
204
```
HTTP 204 code
* `int` **STATUS\_OK**
```
200
```
HTTP 200 code
* `int` **STATUS\_PERMANENT\_REDIRECT**
```
308
```
HTTP 308 code
* `int` **STATUS\_SEE\_OTHER**
```
303
```
HTTP 303 code
* `int` **STATUS\_TEMPORARY\_REDIRECT**
```
307
```
HTTP 307 code
Property Summary
----------------
* [$\_cookies](#%24_cookies) protected `array` The array of cookies in the response.
* [$\_json](#%24_json) protected `mixed` Cached decoded JSON data.
* [$\_xml](#%24_xml) protected `SimpleXMLElement` Cached decoded XML data.
* [$code](#%24code) protected `int` The status code of the response.
* [$cookies](#%24cookies) protected `Cake\Http\Cookie\CookieCollection` Cookie Collection instance
* [$headerNames](#%24headerNames) protected `array` Map of normalized header name to original name used to register header.
* [$headers](#%24headers) protected `array` List of all registered headers, as key => array of values.
* [$reasonPhrase](#%24reasonPhrase) protected `string` The reason phrase for the status code
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_decodeGzipBody()](#_decodeGzipBody()) protected
Uncompress a gzip response.
* ##### [\_getBody()](#_getBody()) protected
Provides magic \_\_get() support.
* ##### [\_getCookies()](#_getCookies()) protected
Property accessor for `$this->cookies`
* ##### [\_getHeaders()](#_getHeaders()) protected
Provides magic \_\_get() support.
* ##### [\_getJson()](#_getJson()) protected
Get the response body as JSON decoded data.
* ##### [\_getXml()](#_getXml()) protected
Get the response body as XML decoded data.
* ##### [\_parseHeaders()](#_parseHeaders()) protected
Parses headers if necessary.
* ##### [buildCookieCollection()](#buildCookieCollection()) protected
Lazily build the CookieCollection and cookie objects from the response header
* ##### [cookies()](#cookies()) public
Get all cookies
* ##### [getBody()](#getBody()) public
Gets the body of the message.
* ##### [getCookie()](#getCookie()) public
Get the value of a single cookie.
* ##### [getCookieCollection()](#getCookieCollection()) public
Get the cookie collection from this response.
* ##### [getCookieData()](#getCookieData()) public
Get the full data for a single cookie.
* ##### [getCookies()](#getCookies()) public
Get the all cookie data.
* ##### [getEncoding()](#getEncoding()) public
Get the encoding if it was set.
* ##### [getHeader()](#getHeader()) public
Retrieves a message header value by the given case-insensitive name.
* ##### [getHeaderLine()](#getHeaderLine()) public
Retrieves a comma-separated string of the values for a single header.
* ##### [getHeaders()](#getHeaders()) public
Retrieves all message headers.
* ##### [getJson()](#getJson()) public
Get the response body as JSON decoded data.
* ##### [getProtocolVersion()](#getProtocolVersion()) public
Retrieves the HTTP protocol version as a string.
* ##### [getReasonPhrase()](#getReasonPhrase()) public
Gets the response reason phrase associated with the status code.
* ##### [getStatusCode()](#getStatusCode()) public
Gets the response status code.
* ##### [getStringBody()](#getStringBody()) public
Get the response body as string.
* ##### [getXml()](#getXml()) public
Get the response body as XML decoded data.
* ##### [hasHeader()](#hasHeader()) public
Checks if a header exists by the given case-insensitive name.
* ##### [isOk()](#isOk()) public
Check if the response status code was in the 2xx/3xx range
* ##### [isRedirect()](#isRedirect()) public
Check if the response had a redirect status code.
* ##### [isSuccess()](#isSuccess()) public
Check if the response status code was in the 2xx range
* ##### [withAddedHeader()](#withAddedHeader()) public
Return an instance with the specified header appended with the given value.
* ##### [withBody()](#withBody()) public
Return an instance with the specified message body.
* ##### [withHeader()](#withHeader()) public
Return an instance with the provided header, replacing any existing values of any headers with the same case-insensitive name.
* ##### [withProtocolVersion()](#withProtocolVersion()) public
Return an instance with the specified HTTP protocol version.
* ##### [withStatus()](#withStatus()) public
Return an instance with the specified status code and, optionally, reason phrase.
* ##### [withoutHeader()](#withoutHeader()) public
Return an instance without the specified header.
Method Detail
-------------
### \_\_construct() public
```
__construct(array $headers = [], string $body = '')
```
Constructor
#### Parameters
`array` $headers optional Unparsed headers.
`string` $body optional The response body.
### \_decodeGzipBody() protected
```
_decodeGzipBody(string $body): string
```
Uncompress a gzip response.
Looks for gzip signatures, and if gzinflate() exists, the body will be decompressed.
#### Parameters
`string` $body Gzip encoded body.
#### Returns
`string`
#### Throws
`RuntimeException`
When attempting to decode gzip content without gzinflate. ### \_getBody() protected
```
_getBody(): string
```
Provides magic \_\_get() support.
#### Returns
`string`
### \_getCookies() protected
```
_getCookies(): array
```
Property accessor for `$this->cookies`
#### Returns
`array`
### \_getHeaders() protected
```
_getHeaders(): array<string>
```
Provides magic \_\_get() support.
#### Returns
`array<string>`
### \_getJson() protected
```
_getJson(): mixed
```
Get the response body as JSON decoded data.
#### Returns
`mixed`
### \_getXml() protected
```
_getXml(): SimpleXMLElement|null
```
Get the response body as XML decoded data.
#### Returns
`SimpleXMLElement|null`
### \_parseHeaders() protected
```
_parseHeaders(array $headers): void
```
Parses headers if necessary.
* Decodes the status code and reasonphrase.
* Parses and normalizes header names + values.
#### Parameters
`array` $headers Headers to parse.
#### Returns
`void`
### buildCookieCollection() protected
```
buildCookieCollection(): void
```
Lazily build the CookieCollection and cookie objects from the response header
#### Returns
`void`
### cookies() public
```
cookies(): array
```
Get all cookies
#### Returns
`array`
### getBody() public
```
getBody(): StreamInterface
```
Gets the body of the message.
#### Returns
`StreamInterface`
### getCookie() public
```
getCookie(string $name): array|string|null
```
Get the value of a single cookie.
#### Parameters
`string` $name The name of the cookie value.
#### Returns
`array|string|null`
### getCookieCollection() public
```
getCookieCollection(): Cake\Http\Cookie\CookieCollection
```
Get the cookie collection from this response.
This method exposes the response's CookieCollection instance allowing you to interact with cookie objects directly.
#### Returns
`Cake\Http\Cookie\CookieCollection`
### getCookieData() public
```
getCookieData(string $name): array|null
```
Get the full data for a single cookie.
#### Parameters
`string` $name The name of the cookie value.
#### Returns
`array|null`
### getCookies() public
```
getCookies(): array
```
Get the all cookie data.
#### Returns
`array`
### getEncoding() public
```
getEncoding(): string|null
```
Get the encoding if it was set.
#### Returns
`string|null`
### getHeader() public
```
getHeader(string $header): string[]
```
Retrieves a message header value by the given case-insensitive name.
This method returns an array of all the header values of the given case-insensitive header name.
If the header does not appear in the message, this method MUST return an empty array.
#### Parameters
`string` $header Case-insensitive header field name.
#### Returns
`string[]`
### getHeaderLine() public
```
getHeaderLine(string $name): string
```
Retrieves a comma-separated string of the values for a single header.
This method returns all of the header values of the given case-insensitive header name as a string concatenated together using a comma.
NOTE: Not all header values may be appropriately represented using comma concatenation. For such headers, use getHeader() instead and supply your own delimiter when concatenating.
If the header does not appear in the message, this method MUST return an empty string.
#### Parameters
`string` $name Case-insensitive header field name.
#### Returns
`string`
### getHeaders() public
```
getHeaders(): array
```
Retrieves all message headers.
The keys represent the header name as it will be sent over the wire, and each value is an array of strings associated with the header.
// Represent the headers as a string foreach ($message->getHeaders() as $name => $values) { echo $name . ": " . implode(", ", $values); }
// Emit headers iteratively: foreach ($message->getHeaders() as $name => $values) { foreach ($values as $value) { header(sprintf('%s: %s', $name, $value), false); } }
#### Returns
`array`
### getJson() public
```
getJson(): mixed
```
Get the response body as JSON decoded data.
#### Returns
`mixed`
### getProtocolVersion() public
```
getProtocolVersion(): string
```
Retrieves the HTTP protocol version as a string.
The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
#### Returns
`string`
### getReasonPhrase() public
```
getReasonPhrase(): string
```
Gets the response reason phrase associated with the status code.
Because a reason phrase is not a required element in a response status line, the reason phrase value MAY be null. Implementations MAY choose to return the default RFC 7231 recommended reason phrase (or those listed in the IANA HTTP Status Code Registry) for the response's status code.
#### Returns
`string`
### getStatusCode() public
```
getStatusCode(): int
```
Gets the response status code.
The status code is a 3-digit integer result code of the server's attempt to understand and satisfy the request.
#### Returns
`int`
### getStringBody() public
```
getStringBody(): string
```
Get the response body as string.
#### Returns
`string`
### getXml() public
```
getXml(): SimpleXMLElement|null
```
Get the response body as XML decoded data.
#### Returns
`SimpleXMLElement|null`
### hasHeader() public
```
hasHeader(string $header): bool
```
Checks if a header exists by the given case-insensitive name.
#### Parameters
`string` $header Case-insensitive header name.
#### Returns
`bool`
### isOk() public
```
isOk(): bool
```
Check if the response status code was in the 2xx/3xx range
#### Returns
`bool`
### isRedirect() public
```
isRedirect(): bool
```
Check if the response had a redirect status code.
#### Returns
`bool`
### isSuccess() public
```
isSuccess(): bool
```
Check if the response status code was in the 2xx range
#### Returns
`bool`
### withAddedHeader() public
```
withAddedHeader(string $name, string|string[] $value): static
```
Return an instance with the specified header appended with the given value.
Existing values for the specified header will be maintained. The new value(s) will be appended to the existing list. If the header did not exist previously, it will be added.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new header and/or value.
#### Parameters
`string` $name Case-insensitive header field name to add.
`string|string[]` $value Header value(s).
#### Returns
`static`
#### Throws
`Exception\InvalidArgumentException`
For invalid header names or values. ### withBody() public
```
withBody(StreamInterface $body): static
```
Return an instance with the specified message body.
The body MUST be a StreamInterface object.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return a new instance that has the new body stream.
#### Parameters
`StreamInterface` $body Body.
#### Returns
`static`
#### Throws
`Exception\InvalidArgumentException`
When the body is not valid. ### withHeader() public
```
withHeader(string $name, string|string[] $value): static
```
Return an instance with the provided header, replacing any existing values of any headers with the same case-insensitive name.
While header names are case-insensitive, the casing of the header will be preserved by this function, and returned from getHeaders().
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new and/or updated header and value.
#### Parameters
`string` $name Case-insensitive header field name.
`string|string[]` $value Header value(s).
#### Returns
`static`
#### Throws
`Exception\InvalidArgumentException`
For invalid header names or values. ### withProtocolVersion() public
```
withProtocolVersion(string $version): static
```
Return an instance with the specified HTTP protocol version.
The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new protocol version.
#### Parameters
`string` $version HTTP protocol version
#### Returns
`static`
### withStatus() public
```
withStatus(int $code, string $reasonPhrase = ''): static
```
Return an instance with the specified status code and, optionally, reason phrase.
If no reason phrase is specified, implementations MAY choose to default to the RFC 7231 or IANA recommended reason phrase for the response's status code.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated status and reason phrase.
#### Parameters
`int` $code The status code to set.
`string` $reasonPhrase optional The status reason phrase.
#### Returns
`static`
### withoutHeader() public
```
withoutHeader(string $name): static
```
Return an instance without the specified header.
Header resolution MUST be done without case-sensitivity.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that removes the named header.
#### Parameters
`string` $name Case-insensitive header field name to remove.
#### Returns
`static`
Property Detail
---------------
### $\_cookies protected
The array of cookies in the response.
#### Type
`array`
### $\_json protected
Cached decoded JSON data.
#### Type
`mixed`
### $\_xml protected
Cached decoded XML data.
#### Type
`SimpleXMLElement`
### $code protected
The status code of the response.
#### Type
`int`
### $cookies protected
Cookie Collection instance
#### Type
`Cake\Http\Cookie\CookieCollection`
### $headerNames protected
Map of normalized header name to original name used to register header.
#### Type
`array`
### $headers protected
List of all registered headers, as key => array of values.
#### Type
`array`
### $reasonPhrase protected
The reason phrase for the status code
#### Type
`string`
cakephp Class NumberHelper Class NumberHelper
===================
Number helper library.
Methods to make numbers more readable.
**Namespace:** [Cake\View\Helper](namespace-cake.view.helper)
**See:** \Cake\I18n\Number
**Link:** https://book.cakephp.org/4/en/views/helpers/number.html
Property Summary
----------------
* [$\_View](#%24_View) protected `Cake\View\View` The View instance this helper is attached to
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
* [$\_engine](#%24_engine) protected `Cake\I18n\Number` Cake\I18n\Number instance
* [$\_helperMap](#%24_helperMap) protected `array<string, array>` A helper lookup table used to lazy load helper objects.
* [$helpers](#%24helpers) protected `array` List of helpers used by this helper
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Call methods from Cake\I18n\Number utility class
* ##### [\_\_construct()](#__construct()) public
Default Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Lazy loads helpers.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_confirm()](#_confirm()) protected
Returns a string to be used as onclick handler for confirm dialogs.
* ##### [addClass()](#addClass()) public
Adds the given class to the element options
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [currency()](#currency()) public
Formats a number into a currency format.
* ##### [defaultCurrency()](#defaultCurrency()) public deprecated
Getter/setter for default currency
* ##### [format()](#format()) public
Formats a number into the correct locale format
* ##### [formatDelta()](#formatDelta()) public
Formats a number into the correct locale format to show deltas (signed differences in value).
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getView()](#getView()) public
Get the view instance this helper is bound to.
* ##### [implementedEvents()](#implementedEvents()) public
Event listeners.
* ##### [initialize()](#initialize()) public
Constructor hook method.
* ##### [ordinal()](#ordinal()) public
Formats a number into locale specific ordinal suffix.
* ##### [precision()](#precision()) public
Formats a number with a level of precision.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [toPercentage()](#toPercentage()) public
Formats a number into a percentage string.
* ##### [toReadableSize()](#toReadableSize()) public
Returns a formatted-for-humans file size.
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $params): mixed
```
Call methods from Cake\I18n\Number utility class
#### Parameters
`string` $method Method to invoke
`array` $params Array of params for the method.
#### Returns
`mixed`
### \_\_construct() public
```
__construct(Cake\View\View $view, array<string, mixed> $config = [])
```
Default Constructor
### Settings:
* `engine` Class name to use to replace Cake\I18n\Number functionality The class needs to be placed in the `Utility` directory.
#### Parameters
`Cake\View\View` $view The View this helper is being attached to.
`array<string, mixed>` $config optional Configuration settings for the helper
#### Throws
`Cake\Core\Exception\CakeException`
When the engine class could not be found. ### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\View\Helper|null|void
```
Lazy loads helpers.
#### Parameters
`string` $name Name of the property being accessed.
#### Returns
`Cake\View\Helper|null|void`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_confirm() protected
```
_confirm(string $okCode, string $cancelCode): string
```
Returns a string to be used as onclick handler for confirm dialogs.
#### Parameters
`string` $okCode Code to be executed after user chose 'OK'
`string` $cancelCode Code to be executed after user chose 'Cancel'
#### Returns
`string`
### addClass() public
```
addClass(array<string, mixed> $options, string $class, string $key = 'class'): array<string, mixed>
```
Adds the given class to the element options
#### Parameters
`array<string, mixed>` $options Array options/attributes to add a class to
`string` $class The class name being added.
`string` $key optional the key to use for class. Defaults to `'class'`.
#### Returns
`array<string, mixed>`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
```
$this->configShallow('key', $value);
```
Setting a nested value:
```
$this->configShallow('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->configShallow(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### currency() public
```
currency(string|float $number, string|null $currency = null, array<string, mixed> $options = []): string
```
Formats a number into a currency format.
### Options
* `locale` - The locale name to use for formatting the number, e.g. fr\_FR
* `fractionSymbol` - The currency symbol to use for fractional numbers.
* `fractionPosition` - The position the fraction symbol should be placed valid options are 'before' & 'after'.
* `before` - Text to display before the rendered number
* `after` - Text to display after the rendered number
* `zero` - The text to use for zero values, can be a string or a number. e.g. 0, 'Free!'
* `places` - Number of decimal places to use. e.g. 2
* `precision` - Maximum Number of decimal places to use, e.g. 2
* `pattern` - An ICU number pattern to use for formatting the number. e.g #,##0.00
* `useIntlCode` - Whether to replace the currency symbol with the international currency code.
* `escape` - Whether to escape html in resulting string
#### Parameters
`string|float` $number Value to format.
`string|null` $currency optional International currency name such as 'USD', 'EUR', 'JPY', 'CAD'
`array<string, mixed>` $options optional Options list.
#### Returns
`string`
### defaultCurrency() public
```
defaultCurrency(string|false|null $currency): string|null
```
Getter/setter for default currency
#### Parameters
`string|false|null` $currency Default currency string to be used by currency() if $currency argument is not provided. If boolean false is passed, it will clear the currently stored value. Null reads the current default.
#### Returns
`string|null`
### format() public
```
format(string|int|float $number, array<string, mixed> $options = []): string
```
Formats a number into the correct locale format
Options:
* `places` - Minimum number or decimals to use, e.g 0
* `precision` - Maximum Number of decimal places to use, e.g. 2
* `locale` - The locale name to use for formatting the number, e.g. fr\_FR
* `before` - The string to place before whole numbers, e.g. '['
* `after` - The string to place after decimal numbers, e.g. ']'
* `escape` - Whether to escape html in resulting string
#### Parameters
`string|int|float` $number A floating point number.
`array<string, mixed>` $options optional An array with options.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/number.html#formatting-numbers
### formatDelta() public
```
formatDelta(string|float $value, array<string, mixed> $options = []): string
```
Formats a number into the correct locale format to show deltas (signed differences in value).
### Options
* `places` - Minimum number or decimals to use, e.g 0
* `precision` - Maximum Number of decimal places to use, e.g. 2
* `locale` - The locale name to use for formatting the number, e.g. fr\_FR
* `before` - The string to place before whole numbers, e.g. '['
* `after` - The string to place after decimal numbers, e.g. ']'
* `escape` - Set to false to prevent escaping
#### Parameters
`string|float` $value A floating point number
`array<string, mixed>` $options optional Options list.
#### Returns
`string`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### Usage
Reading the whole config:
```
$this->getConfig();
```
Reading a specific value:
```
$this->getConfig('key');
```
Reading a nested value:
```
$this->getConfig('some.nested.key');
```
Reading with default value:
```
$this->getConfig('some-key', 'default-value');
```
#### Parameters
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getView() public
```
getView(): Cake\View\View
```
Get the view instance this helper is bound to.
#### Returns
`Cake\View\View`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Event listeners.
By defining one of the callback methods a helper is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want helpers to listen to non-standard events.
#### Returns
`array<string, mixed>`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Constructor hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The configuration settings provided to this helper.
#### Returns
`void`
### ordinal() public
```
ordinal(float|int $value, array<string, mixed> $options = []): string
```
Formats a number into locale specific ordinal suffix.
#### Parameters
`float|int` $value An integer
`array<string, mixed>` $options optional An array with options.
#### Returns
`string`
### precision() public
```
precision(string|float $number, int $precision = 3, array<string, mixed> $options = []): string
```
Formats a number with a level of precision.
#### Parameters
`string|float` $number A floating point number.
`int` $precision optional The precision of the returned number.
`array<string, mixed>` $options optional Additional options.
#### Returns
`string`
#### See Also
\Cake\I18n\Number::precision() #### Links
https://book.cakephp.org/4/en/views/helpers/number.html#formatting-floating-point-numbers
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### Usage
Setting a specific value:
```
$this->setConfig('key', $value);
```
Setting a nested value:
```
$this->setConfig('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->setConfig(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### toPercentage() public
```
toPercentage(string|float $number, int $precision = 2, array<string, mixed> $options = []): string
```
Formats a number into a percentage string.
Options:
* `multiply`: Multiply the input value by 100 for decimal percentages.
#### Parameters
`string|float` $number A floating point number
`int` $precision optional The precision of the returned number
`array<string, mixed>` $options optional Options
#### Returns
`string`
#### See Also
\Cake\I18n\Number::toPercentage() #### Links
https://book.cakephp.org/4/en/views/helpers/number.html#formatting-percentages
### toReadableSize() public
```
toReadableSize(string|int $size): string
```
Returns a formatted-for-humans file size.
#### Parameters
`string|int` $size Size in bytes
#### Returns
`string`
#### See Also
\Cake\I18n\Number::toReadableSize() #### Links
https://book.cakephp.org/4/en/views/helpers/number.html#interacting-with-human-readable-values
Property Detail
---------------
### $\_View protected
The View instance this helper is attached to
#### Type
`Cake\View\View`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
### $\_engine protected
Cake\I18n\Number instance
#### Type
`Cake\I18n\Number`
### $\_helperMap protected
A helper lookup table used to lazy load helper objects.
#### Type
`array<string, array>`
### $helpers protected
List of helpers used by this helper
#### Type
`array`
| programming_docs |
cakephp Namespace Middleware Namespace Middleware
====================
### Classes
* ##### [ErrorHandlerMiddleware](class-cake.error.middleware.errorhandlermiddleware)
Error handling middleware.
cakephp Class Table Class Table
============
Represents a single database table.
Exposes methods for retrieving data out of it, and manages the associations this table has to other tables. Multiple instances of this class can be created for the same database table with different aliases, this allows you to address your database structure in a richer and more expressive way.
### Retrieving data
The primary way to retrieve data is using Table::find(). See that method for more information.
### Dynamic finders
In addition to the standard find($type) finder methods, CakePHP provides dynamic finder methods. These methods allow you to easily set basic conditions up. For example to filter users by username you would call
```
$query = $users->findByUsername('mark');
```
You can also combine conditions on multiple fields using either `Or` or `And`:
```
$query = $users->findByUsernameOrEmail('mark', '[email protected]');
```
### Bulk updates/deletes
You can use Table::updateAll() and Table::deleteAll() to do bulk updates/deletes. You should be aware that events will *not* be fired for bulk updates/deletes.
### Events
Table objects emit several events during as life-cycle hooks during find, delete and save operations. All events use the CakePHP event package:
* `Model.beforeFind` Fired before each find operation. By stopping the event and supplying a return value you can bypass the find operation entirely. Any changes done to the $query instance will be retained for the rest of the find. The `$primary` parameter indicates whether this is the root query, or an associated query.
* `Model.buildValidator` Allows listeners to modify validation rules for the provided named validator.
* `Model.buildRules` Allows listeners to modify the rules checker by adding more rules.
* `Model.beforeRules` Fired before an entity is validated using the rules checker. By stopping this event, you can return the final value of the rules checking operation.
* `Model.afterRules` Fired after the rules have been checked on the entity. By stopping this event, you can return the final value of the rules checking operation.
* `Model.beforeSave` Fired before each entity is saved. Stopping this event will abort the save operation. When the event is stopped the result of the event will be returned.
* `Model.afterSave` Fired after an entity is saved.
* `Model.afterSaveCommit` Fired after the transaction in which the save operation is wrapped has been committed. It’s also triggered for non atomic saves where database operations are implicitly committed. The event is triggered only for the primary table on which save() is directly called. The event is not triggered if a transaction is started before calling save.
* `Model.beforeDelete` Fired before an entity is deleted. By stopping this event you will abort the delete operation.
* `Model.afterDelete` Fired after an entity has been deleted.
### Callbacks
You can subscribe to the events listed above in your table classes by implementing the lifecycle methods below:
* `beforeFind(EventInterface $event, Query $query, ArrayObject $options, boolean $primary)`
* `beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options)`
* `afterMarshal(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
* `buildValidator(EventInterface $event, Validator $validator, string $name)`
* `buildRules(RulesChecker $rules)`
* `beforeRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, string $operation)`
* `afterRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, bool $result, string $operation)`
* `beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
* `afterSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
* `afterSaveCommit(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
* `beforeDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
* `afterDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
* `afterDeleteCommit(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
**Namespace:** [Cake\ORM](namespace-cake.orm)
**See:** \Cake\Event\EventManager for reference on the events system.
**Link:** https://book.cakephp.org/4/en/orm/table-objects.html#event-list
Constants
---------
* `string` **BUILD\_VALIDATOR\_EVENT**
```
'Model.buildValidator'
```
The name of the event dispatched when a validator has been built.
* `string` **DEFAULT\_VALIDATOR**
```
'default'
```
Name of default validation set.
* `string` **IS\_UNIQUE\_CLASS**
```
IsUnique::class
```
The IsUnique class name that is used.
* `string` **RULES\_CLASS**
```
RulesChecker::class
```
The rules class name that is used.
* `string` **VALIDATOR\_PROVIDER\_NAME**
```
'table'
```
The alias this object is assigned to validators as.
Property Summary
----------------
* [$\_alias](#%24_alias) protected `string|null` Human name giving to this particular instance. Multiple objects representing the same database table can exist by using different aliases.
* [$\_associations](#%24_associations) protected `Cake\ORM\AssociationCollection` The associations container for this Table.
* [$\_behaviors](#%24_behaviors) protected `Cake\ORM\BehaviorRegistry` BehaviorRegistry for this table
* [$\_connection](#%24_connection) protected `Cake\Database\Connection|null` Connection instance
* [$\_displayField](#%24_displayField) protected `array<string>|string|null` The name of the field that represents a human-readable representation of a row
* [$\_entityClass](#%24_entityClass) protected `string` The name of the class that represent a single row for this table
* [$\_eventClass](#%24_eventClass) protected `string` Default class name for new event objects.
* [$\_eventManager](#%24_eventManager) protected `Cake\Event\EventManagerInterface|null` Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
* [$\_primaryKey](#%24_primaryKey) protected `array<string>|string|null` The name of the field that represents the primary key in the table
* [$\_registryAlias](#%24_registryAlias) protected `string|null` Registry key used to create this table object
* [$\_rulesChecker](#%24_rulesChecker) protected `Cake\Datasource\RulesChecker` The domain rules to be applied to entities saved by this table
* [$\_schema](#%24_schema) protected `Cake\Database\Schema\TableSchemaInterface|null` The schema object containing a description of this table fields
* [$\_table](#%24_table) protected `string|null` Name of the table as it can be found in the database
* [$\_validatorClass](#%24_validatorClass) protected `string` Validator class.
* [$\_validators](#%24_validators) protected `arrayCake\Validation\Validator>` A list of validation objects indexed by name
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Handles behavior delegation + dynamic finders.
* ##### [\_\_construct()](#__construct()) public
Initializes a new instance
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Returns the association named after the passed value if exists, otherwise throws an exception.
* ##### [\_\_isset()](#__isset()) public
Returns whether an association named after the passed value exists for this table.
* ##### [\_deleteMany()](#_deleteMany()) protected
* ##### [\_dynamicFinder()](#_dynamicFinder()) protected
Provides the dynamic findBy and findAllBy methods.
* ##### [\_executeTransaction()](#_executeTransaction()) protected
Handles the logic executing of a worker inside a transaction.
* ##### [\_getFindOrCreateQuery()](#_getFindOrCreateQuery()) protected
Gets the query object for findOrCreate().
* ##### [\_initializeSchema()](#_initializeSchema()) protected
Override this function in order to alter the schema used by this table. This function is only called after fetching the schema out of the database. If you wish to provide your own schema to this table without touching the database, you can override schema() or inject the definitions though that method.
* ##### [\_insert()](#_insert()) protected
Auxiliary function to handle the insert of an entity's data in the table
* ##### [\_newId()](#_newId()) protected
Generate a primary key value for a new record.
* ##### [\_onSaveSuccess()](#_onSaveSuccess()) protected
Handles the saving of children associations and executing the afterSave logic once the entity for this table has been saved successfully.
* ##### [\_processDelete()](#_processDelete()) protected
Perform the delete operation.
* ##### [\_processFindOrCreate()](#_processFindOrCreate()) protected
Performs the actual find and/or create of an entity based on the passed options.
* ##### [\_processSave()](#_processSave()) protected
Performs the actual saving of an entity based on the passed options.
* ##### [\_saveMany()](#_saveMany()) protected
* ##### [\_setFieldMatchers()](#_setFieldMatchers()) protected
Out of an options array, check if the keys described in `$keys` are arrays and change the values for closures that will concatenate the each of the properties in the value array when passed a row.
* ##### [\_transactionCommitted()](#_transactionCommitted()) protected
Checks if the caller would have executed a commit on a transaction.
* ##### [\_update()](#_update()) protected
Auxiliary function to handle the update of an entity's data in the table
* ##### [addAssociations()](#addAssociations()) public
Setup multiple associations.
* ##### [addBehavior()](#addBehavior()) public
Add a behavior.
* ##### [addBehaviors()](#addBehaviors()) public
Adds an array of behaviors to the table's behavior collection.
* ##### [aliasField()](#aliasField()) public
Alias a field with the table's current alias.
* ##### [associations()](#associations()) public
Get the associations collection for this table.
* ##### [behaviors()](#behaviors()) public
Returns the behavior registry for this table.
* ##### [belongsTo()](#belongsTo()) public
Creates a new BelongsTo association between this table and a target table. A "belongs to" association is a N-1 relationship where this table is the N side, and where there is a single associated record in the target table for each one in this table.
* ##### [belongsToMany()](#belongsToMany()) public
Creates a new BelongsToMany association between this table and a target table. A "belongs to many" association is a M-N relationship.
* ##### [buildRules()](#buildRules()) public
Returns a RulesChecker object after modifying the one that was supplied.
* ##### [callFinder()](#callFinder()) public
Calls a finder method and applies it to the passed query.
* ##### [checkAliasLengths()](#checkAliasLengths()) protected
Checks if all table name + column name combinations used for queries fit into the max length allowed by database driver.
* ##### [checkRules()](#checkRules()) public
Returns whether the passed entity complies with all the rules stored in the rules checker.
* ##### [createValidator()](#createValidator()) protected
Creates a validator using a custom method inside your class.
* ##### [defaultConnectionName()](#defaultConnectionName()) public static
Get the default connection name.
* ##### [delete()](#delete()) public
Delete a single entity.
* ##### [deleteAll()](#deleteAll()) public
Deletes all records matching the provided conditions.
* ##### [deleteMany()](#deleteMany()) public
Deletes multiple entities of a table.
* ##### [deleteManyOrFail()](#deleteManyOrFail()) public
Deletes multiple entities of a table.
* ##### [deleteOrFail()](#deleteOrFail()) public
Try to delete an entity or throw a PersistenceFailedException if the entity is new, has no primary key value, application rules checks failed or the delete was aborted by a callback.
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [exists()](#exists()) public
Returns true if there is any record in this repository matching the specified conditions.
* ##### [find()](#find()) public
Creates a new Query for this repository and applies some defaults based on the type of search that was selected.
* ##### [findAll()](#findAll()) public
Returns the query as passed.
* ##### [findAssociation()](#findAssociation()) protected
Returns an association object configured for the specified alias if any.
* ##### [findList()](#findList()) public
Sets up a query object so results appear as an indexed array, useful for any place where you would want a list such as for populating input select boxes.
* ##### [findOrCreate()](#findOrCreate()) public
Finds an existing record or creates a new one.
* ##### [findThreaded()](#findThreaded()) public
Results for this finder will be a nested array, and is appropriate if you want to use the parent\_id field of your model data to build nested results.
* ##### [get()](#get()) public
Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
* ##### [getAlias()](#getAlias()) public
Returns the table alias.
* ##### [getAssociation()](#getAssociation()) public
Returns an association object configured for the specified alias.
* ##### [getBehavior()](#getBehavior()) public
Get a behavior from the registry.
* ##### [getConnection()](#getConnection()) public
Returns the connection instance.
* ##### [getDisplayField()](#getDisplayField()) public
Returns the display field.
* ##### [getEntityClass()](#getEntityClass()) public
Returns the class used to hydrate rows for this table.
* ##### [getEventManager()](#getEventManager()) public
Returns the Cake\Event\EventManager manager instance for this object.
* ##### [getPrimaryKey()](#getPrimaryKey()) public
Returns the primary key field name.
* ##### [getRegistryAlias()](#getRegistryAlias()) public
Returns the table registry key used to create this table instance.
* ##### [getSaveOptionsBuilder()](#getSaveOptionsBuilder()) public deprecated
Gets a SaveOptionsBuilder instance.
* ##### [getSchema()](#getSchema()) public
Returns the schema table object describing this table's properties.
* ##### [getTable()](#getTable()) public
Returns the database table name.
* ##### [getValidator()](#getValidator()) public
Returns the validation rules tagged with $name. It is possible to have multiple different named validation sets, this is useful when you need to use varying rules when saving from different routines in your system.
* ##### [hasAssociation()](#hasAssociation()) public
Checks whether a specific association exists on this Table instance.
* ##### [hasBehavior()](#hasBehavior()) public
Check if a behavior with the given alias has been loaded.
* ##### [hasField()](#hasField()) public
Test to see if a Table has a specific field/column.
* ##### [hasFinder()](#hasFinder()) public
Returns true if the finder exists for the table
* ##### [hasMany()](#hasMany()) public
Creates a new HasMany association between this table and a target table. A "has many" association is a 1-N relationship.
* ##### [hasOne()](#hasOne()) public
Creates a new HasOne association between this table and a target table. A "has one" association is a 1-1 relationship.
* ##### [hasValidator()](#hasValidator()) public
Checks whether a validator has been set.
* ##### [implementedEvents()](#implementedEvents()) public
Get the Model callbacks this table is interested in.
* ##### [initialize()](#initialize()) public
Initialize a table instance. Called after the constructor.
* ##### [loadInto()](#loadInto()) public
Loads the specified associations in the passed entity or list of entities by executing extra queries in the database and merging the results in the appropriate properties.
* ##### [marshaller()](#marshaller()) public
Get the object used to marshal/convert array data into objects.
* ##### [newEmptyEntity()](#newEmptyEntity()) public
This creates a new entity object.
* ##### [newEntities()](#newEntities()) public
Create a list of entities + associated entities from an array.
* ##### [newEntity()](#newEntity()) public
Create a new entity + associated entities from an array.
* ##### [patchEntities()](#patchEntities()) public
Merges each of the elements passed in `$data` into the entities found in `$entities` respecting the accessible fields configured on the entities. Merging is done by matching the primary key in each of the elements in `$data` and `$entities`.
* ##### [patchEntity()](#patchEntity()) public
Merges the passed `$data` into `$entity` respecting the accessible fields configured on the entity. Returns the same entity after being altered.
* ##### [query()](#query()) public
Creates a new Query instance for a table.
* ##### [removeBehavior()](#removeBehavior()) public
Removes a behavior from this table's behavior registry.
* ##### [rulesChecker()](#rulesChecker()) public
Returns the RulesChecker for this instance.
* ##### [save()](#save()) public
Persists an entity based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error.
* ##### [saveMany()](#saveMany()) public
Persists multiple entities of a table.
* ##### [saveManyOrFail()](#saveManyOrFail()) public
Persists multiple entities of a table.
* ##### [saveOrFail()](#saveOrFail()) public
Try to save an entity or throw a PersistenceFailedException if the application rules checks failed, the entity contains errors or the save was aborted by a callback.
* ##### [setAlias()](#setAlias()) public
Sets the table alias.
* ##### [setConnection()](#setConnection()) public
Sets the connection instance.
* ##### [setDisplayField()](#setDisplayField()) public
Sets the display field.
* ##### [setEntityClass()](#setEntityClass()) public
Sets the class used to hydrate rows for this table.
* ##### [setEventManager()](#setEventManager()) public
Returns the Cake\Event\EventManagerInterface instance for this object.
* ##### [setPrimaryKey()](#setPrimaryKey()) public
Sets the primary key field name.
* ##### [setRegistryAlias()](#setRegistryAlias()) public
Sets the table registry key used to create this table instance.
* ##### [setSchema()](#setSchema()) public
Sets the schema table object describing this table's properties.
* ##### [setTable()](#setTable()) public
Sets the database table name.
* ##### [setValidator()](#setValidator()) public
This method stores a custom validator under the given name.
* ##### [subquery()](#subquery()) public
Creates a new Query::subquery() instance for a table.
* ##### [updateAll()](#updateAll()) public
Update all matching records.
* ##### [validateUnique()](#validateUnique()) public
Validator method used to check the uniqueness of a value for a column. This is meant to be used with the validation API and not to be called directly.
* ##### [validationDefault()](#validationDefault()) public
Returns the default validator object. Subclasses can override this function to add a default validation set to the validator object.
* ##### [validationMethodExists()](#validationMethodExists()) protected
Checks if validation method exists.
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $args): mixed
```
Handles behavior delegation + dynamic finders.
If your Table uses any behaviors you can call them as if they were on the table object.
#### Parameters
`string` $method name of the method to be invoked
`array` $args List of arguments passed to the function
#### Returns
`mixed`
#### Throws
`BadMethodCallException`
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Initializes a new instance
The $config array understands the following keys:
* table: Name of the database table to represent
* alias: Alias to be assigned to this table (default to table name)
* connection: The connection instance to use
* entityClass: The fully namespaced class name of the entity class that will represent rows in this table.
* schema: A \Cake\Database\Schema\TableSchemaInterface object or an array that can be passed to it.
* eventManager: An instance of an event manager to use for internal events
* behaviors: A BehaviorRegistry. Generally not used outside of tests.
* associations: An AssociationCollection instance.
* validator: A Validator instance which is assigned as the "default" validation set, or an associative array, where key is the name of the validation set and value the Validator instance.
#### Parameters
`array<string, mixed>` $config optional List of options for this table
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $property): Cake\ORM\Association
```
Returns the association named after the passed value if exists, otherwise throws an exception.
#### Parameters
`string` $property the association name
#### Returns
`Cake\ORM\Association`
#### Throws
`RuntimeException`
if no association with such name exists ### \_\_isset() public
```
__isset(string $property): bool
```
Returns whether an association named after the passed value exists for this table.
#### Parameters
`string` $property the association name
#### Returns
`bool`
### \_deleteMany() protected
```
_deleteMany(iterableCake\Datasource\EntityInterface> $entities, ArrayAccess|array $options = []): Cake\Datasource\EntityInterface|null
```
#### Parameters
`iterableCake\Datasource\EntityInterface>` $entities Entities to delete.
`ArrayAccess|array` $options optional Options used.
#### Returns
`Cake\Datasource\EntityInterface|null`
### \_dynamicFinder() protected
```
_dynamicFinder(string $method, array $args): Cake\ORM\Query
```
Provides the dynamic findBy and findAllBy methods.
#### Parameters
`string` $method The method name that was fired.
`array` $args List of arguments passed to the function.
#### Returns
`Cake\ORM\Query`
#### Throws
`BadMethodCallException`
when there are missing arguments, or when and & or are combined. ### \_executeTransaction() protected
```
_executeTransaction(callable $worker, bool $atomic = true): mixed
```
Handles the logic executing of a worker inside a transaction.
#### Parameters
`callable` $worker The worker that will run inside the transaction.
`bool` $atomic optional Whether to execute the worker inside a database transaction.
#### Returns
`mixed`
### \_getFindOrCreateQuery() protected
```
_getFindOrCreateQuery(Cake\ORM\Query|callable|array $search): Cake\ORM\Query
```
Gets the query object for findOrCreate().
#### Parameters
`Cake\ORM\Query|callable|array` $search The criteria to find existing records by.
#### Returns
`Cake\ORM\Query`
### \_initializeSchema() protected
```
_initializeSchema(Cake\Database\Schema\TableSchemaInterface $schema): Cake\Database\Schema\TableSchemaInterface
```
Override this function in order to alter the schema used by this table. This function is only called after fetching the schema out of the database. If you wish to provide your own schema to this table without touching the database, you can override schema() or inject the definitions though that method.
### Example:
```
protected function _initializeSchema(\Cake\Database\Schema\TableSchemaInterface $schema) {
$schema->setColumnType('preferences', 'json');
return $schema;
}
```
#### Parameters
`Cake\Database\Schema\TableSchemaInterface` $schema The table definition fetched from database.
#### Returns
`Cake\Database\Schema\TableSchemaInterface`
### \_insert() protected
```
_insert(Cake\Datasource\EntityInterface $entity, array $data): Cake\Datasource\EntityInterface|false
```
Auxiliary function to handle the insert of an entity's data in the table
#### Parameters
`Cake\Datasource\EntityInterface` $entity the subject entity from were $data was extracted
`array` $data The actual data that needs to be saved
#### Returns
`Cake\Datasource\EntityInterface|false`
#### Throws
`RuntimeException`
if not all the primary keys where supplied or could be generated when the table has composite primary keys. Or when the table has no primary key. ### \_newId() protected
```
_newId(array<string> $primary): string|null
```
Generate a primary key value for a new record.
By default, this uses the type system to generate a new primary key value if possible. You can override this method if you have specific requirements for id generation.
Note: The ORM will not generate primary key values for composite primary keys. You can overwrite \_newId() in your table class.
#### Parameters
`array<string>` $primary The primary key columns to get a new ID for.
#### Returns
`string|null`
### \_onSaveSuccess() protected
```
_onSaveSuccess(Cake\Datasource\EntityInterface $entity, ArrayObject $options): bool
```
Handles the saving of children associations and executing the afterSave logic once the entity for this table has been saved successfully.
#### Parameters
`Cake\Datasource\EntityInterface` $entity the entity to be saved
`ArrayObject` $options the options to use for the save operation
#### Returns
`bool`
#### Throws
`Cake\ORM\Exception\RolledbackTransactionException`
If the transaction is aborted in the afterSave event. ### \_processDelete() protected
```
_processDelete(Cake\Datasource\EntityInterface $entity, ArrayObject $options): bool
```
Perform the delete operation.
Will delete the entity provided. Will remove rows from any dependent associations, and clear out join tables for BelongsToMany associations.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to delete.
`ArrayObject` $options The options for the delete.
#### Returns
`bool`
#### Throws
`InvalidArgumentException`
if there are no primary key values of the passed entity ### \_processFindOrCreate() protected
```
_processFindOrCreate(Cake\ORM\Query|callable|array $search, callable|null $callback = null, array<string, mixed> $options = []): Cake\Datasource\EntityInterface|array
```
Performs the actual find and/or create of an entity based on the passed options.
#### Parameters
`Cake\ORM\Query|callable|array` $search The criteria to find an existing record by, or a callable tha will customize the find query.
`callable|null` $callback optional A callback that will be invoked for newly created entities. This callback will be called *before* the entity is persisted.
`array<string, mixed>` $options optional The options to use when saving.
#### Returns
`Cake\Datasource\EntityInterface|array`
#### Throws
`Cake\ORM\Exception\PersistenceFailedException`
When the entity couldn't be saved
`InvalidArgumentException`
### \_processSave() protected
```
_processSave(Cake\Datasource\EntityInterface $entity, ArrayObject $options): Cake\Datasource\EntityInterface|false
```
Performs the actual saving of an entity based on the passed options.
#### Parameters
`Cake\Datasource\EntityInterface` $entity the entity to be saved
`ArrayObject` $options the options to use for the save operation
#### Returns
`Cake\Datasource\EntityInterface|false`
#### Throws
`RuntimeException`
When an entity is missing some of the primary keys.
`Cake\ORM\Exception\RolledbackTransactionException`
If the transaction is aborted in the afterSave event. ### \_saveMany() protected
```
_saveMany(iterableCake\Datasource\EntityInterface> $entities, Cake\ORM\SaveOptionsBuilderArrayAccess|array $options = []): iterableCake\Datasource\EntityInterface>
```
#### Parameters
`iterableCake\Datasource\EntityInterface>` $entities Entities to save.
`Cake\ORM\SaveOptionsBuilderArrayAccess|array` $options optional Options used when calling Table::save() for each entity.
#### Returns
`iterableCake\Datasource\EntityInterface>`
#### Throws
`Cake\ORM\Exception\PersistenceFailedException`
If an entity couldn't be saved.
`Exception`
If an entity couldn't be saved. ### \_setFieldMatchers() protected
```
_setFieldMatchers(array<string, mixed> $options, array<string> $keys): array<string, mixed>
```
Out of an options array, check if the keys described in `$keys` are arrays and change the values for closures that will concatenate the each of the properties in the value array when passed a row.
This is an auxiliary function used for result formatters that can accept composite keys when comparing values.
#### Parameters
`array<string, mixed>` $options the original options passed to a finder
`array<string>` $keys the keys to check in $options to build matchers from the associated value
#### Returns
`array<string, mixed>`
### \_transactionCommitted() protected
```
_transactionCommitted(bool $atomic, bool $primary): bool
```
Checks if the caller would have executed a commit on a transaction.
#### Parameters
`bool` $atomic True if an atomic transaction was used.
`bool` $primary True if a primary was used.
#### Returns
`bool`
### \_update() protected
```
_update(Cake\Datasource\EntityInterface $entity, array $data): Cake\Datasource\EntityInterface|false
```
Auxiliary function to handle the update of an entity's data in the table
#### Parameters
`Cake\Datasource\EntityInterface` $entity the subject entity from were $data was extracted
`array` $data The actual data that needs to be saved
#### Returns
`Cake\Datasource\EntityInterface|false`
#### Throws
`InvalidArgumentException`
When primary key data is missing. ### addAssociations() public
```
addAssociations(array $params): $this
```
Setup multiple associations.
It takes an array containing set of table names indexed by association type as argument:
```
$this->Posts->addAssociations([
'belongsTo' => [
'Users' => ['className' => 'App\Model\Table\UsersTable']
],
'hasMany' => ['Comments'],
'belongsToMany' => ['Tags']
]);
```
Each association type accepts multiple associations where the keys are the aliases, and the values are association config data. If numeric keys are used the values will be treated as association aliases.
#### Parameters
`array` $params Set of associations to bind (indexed by association type)
#### Returns
`$this`
#### See Also
\Cake\ORM\Table::belongsTo()
\Cake\ORM\Table::hasOne()
\Cake\ORM\Table::hasMany()
\Cake\ORM\Table::belongsToMany() ### addBehavior() public
```
addBehavior(string $name, array<string, mixed> $options = []): $this
```
Add a behavior.
Adds a behavior to this table's behavior collection. Behaviors provide an easy way to create horizontally re-usable features that can provide trait like functionality, and allow for events to be listened to.
Example:
Load a behavior, with some settings.
```
$this->addBehavior('Tree', ['parent' => 'parentId']);
```
Behaviors are generally loaded during Table::initialize().
#### Parameters
`string` $name The name of the behavior. Can be a short class reference.
`array<string, mixed>` $options optional The options for the behavior to use.
#### Returns
`$this`
#### Throws
`RuntimeException`
If a behavior is being reloaded. #### See Also
\Cake\ORM\Behavior ### addBehaviors() public
```
addBehaviors(array $behaviors): $this
```
Adds an array of behaviors to the table's behavior collection.
Example:
```
$this->addBehaviors([
'Timestamp',
'Tree' => ['level' => 'level'],
]);
```
#### Parameters
`array` $behaviors All the behaviors to load.
#### Returns
`$this`
#### Throws
`RuntimeException`
If a behavior is being reloaded. ### aliasField() public
```
aliasField(string $field): string
```
Alias a field with the table's current alias.
If field is already aliased it will result in no-op.
#### Parameters
`string` $field The field to alias.
#### Returns
`string`
### associations() public
```
associations(): Cake\ORM\AssociationCollection
```
Get the associations collection for this table.
#### Returns
`Cake\ORM\AssociationCollection`
### behaviors() public
```
behaviors(): Cake\ORM\BehaviorRegistry
```
Returns the behavior registry for this table.
#### Returns
`Cake\ORM\BehaviorRegistry`
### belongsTo() public
```
belongsTo(string $associated, array<string, mixed> $options = []): Cake\ORM\Association\BelongsTo
```
Creates a new BelongsTo association between this table and a target table. A "belongs to" association is a N-1 relationship where this table is the N side, and where there is a single associated record in the target table for each one in this table.
Target table can be inferred by its name, which is provided in the first argument, or you can either pass the to be instantiated or an instance of it directly.
The options array accept the following keys:
* className: The class name of the target table object
* targetTable: An instance of a table object to be used as the target table
* foreignKey: The name of the field to use as foreign key, if false none will be used
* conditions: array with a list of conditions to filter the join with
* joinType: The type of join to be used (e.g. INNER)
* strategy: The loading strategy to use. 'join' and 'select' are supported.
* finder: The finder method to use when loading records from this association. Defaults to 'all'. When the strategy is 'join', only the fields, containments, and where conditions will be used from the finder.
This method will return the association object that was built.
#### Parameters
`string` $associated the alias for the target table. This is used to uniquely identify the association
`array<string, mixed>` $options optional list of options to configure the association definition
#### Returns
`Cake\ORM\Association\BelongsTo`
### belongsToMany() public
```
belongsToMany(string $associated, array<string, mixed> $options = []): Cake\ORM\Association\BelongsToMany
```
Creates a new BelongsToMany association between this table and a target table. A "belongs to many" association is a M-N relationship.
Target table can be inferred by its name, which is provided in the first argument, or you can either pass the class name to be instantiated or an instance of it directly.
The options array accept the following keys:
* className: The class name of the target table object.
* targetTable: An instance of a table object to be used as the target table.
* foreignKey: The name of the field to use as foreign key.
* targetForeignKey: The name of the field to use as the target foreign key.
* joinTable: The name of the table representing the link between the two
* through: If you choose to use an already instantiated link table, set this key to a configured Table instance containing associations to both the source and target tables in this association.
* dependent: Set to false, if you do not want junction table records removed when an owning record is removed.
* cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on cascaded deletes. If false the ORM will use deleteAll() to remove data. When true join/junction table records will be loaded and then deleted.
* conditions: array with a list of conditions to filter the join with.
* sort: The order in which results for this association should be returned.
* strategy: The strategy to be used for selecting results Either 'select' or 'subquery'. If subquery is selected the query used to return results in the source table will be used as conditions for getting rows in the target table.
* saveStrategy: Either 'append' or 'replace'. Indicates the mode to be used for saving associated entities. The former will only create new links between both side of the relation and the latter will do a wipe and replace to create the links between the passed entities when saving.
* strategy: The loading strategy to use. 'select' and 'subquery' are supported.
* finder: The finder method to use when loading records from this association. Defaults to 'all'.
This method will return the association object that was built.
#### Parameters
`string` $associated the alias for the target table. This is used to uniquely identify the association
`array<string, mixed>` $options optional list of options to configure the association definition
#### Returns
`Cake\ORM\Association\BelongsToMany`
### buildRules() public
```
buildRules(Cake\Datasource\RulesChecker $rules): Cake\ORM\RulesChecker
```
Returns a RulesChecker object after modifying the one that was supplied.
Subclasses should override this method in order to initialize the rules to be applied to entities saved by this instance.
#### Parameters
`Cake\Datasource\RulesChecker` $rules The rules object to be modified.
#### Returns
`Cake\ORM\RulesChecker`
### callFinder() public
```
callFinder(string $type, Cake\ORM\Query $query, array<string, mixed> $options = []): Cake\ORM\Query
```
Calls a finder method and applies it to the passed query.
#### Parameters
`string` $type Name of the finder to be called.
`Cake\ORM\Query` $query The query object to apply the finder options to.
`array<string, mixed>` $options optional List of options to pass to the finder.
#### Returns
`Cake\ORM\Query`
#### Throws
`BadMethodCallException`
### checkAliasLengths() protected
```
checkAliasLengths(): void
```
Checks if all table name + column name combinations used for queries fit into the max length allowed by database driver.
#### Returns
`void`
#### Throws
`RuntimeException`
When an alias combination is too long ### checkRules() public
```
checkRules(Cake\Datasource\EntityInterface $entity, string $operation = RulesChecker::CREATE, ArrayObject|array|null $options = null): bool
```
Returns whether the passed entity complies with all the rules stored in the rules checker.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for validity.
`string` $operation optional The operation being run. Either 'create', 'update' or 'delete'.
`ArrayObject|array|null` $options optional The options To be passed to the rules.
#### Returns
`bool`
### createValidator() protected
```
createValidator(string $name): Cake\Validation\Validator
```
Creates a validator using a custom method inside your class.
This method is used only to build a new validator and it does not store it in your object. If you want to build and reuse validators, use getValidator() method instead.
#### Parameters
`string` $name The name of the validation set to create.
#### Returns
`Cake\Validation\Validator`
#### Throws
`RuntimeException`
### defaultConnectionName() public static
```
defaultConnectionName(): string
```
Get the default connection name.
This method is used to get the fallback connection name if an instance is created through the TableLocator without a connection.
#### Returns
`string`
#### See Also
\Cake\ORM\Locator\TableLocator::get() ### delete() public
```
delete(Cake\Datasource\EntityInterface $entity, ArrayAccess|array $options = []): bool
```
Delete a single entity.
For HasMany and HasOne associations records will be removed based on the dependent option. Join table records in BelongsToMany associations will always be removed. You can use the `cascadeCallbacks` option when defining associations to change how associated data is deleted.
### Options
* `atomic` Defaults to true. When true the deletion happens within a transaction.
* `checkRules` Defaults to true. Check deletion rules before deleting the record.
### Events
* `Model.beforeDelete` Fired before the delete occurs. If stopped the delete will be aborted. Receives the event, entity, and options.
* `Model.afterDelete` Fired after the delete has been successful. Receives the event, entity, and options.
* `Model.afterDeleteCommit` Fired after the transaction is committed for an atomic delete. Receives the event, entity, and options.
The options argument will be converted into an \ArrayObject instance for the duration of the callbacks, this allows listeners to modify the options used in the delete operation.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to remove.
`ArrayAccess|array` $options optional The options for the delete.
#### Returns
`bool`
### deleteAll() public
```
deleteAll(mixed $conditions): int
```
Deletes all records matching the provided conditions.
This method will *not* trigger beforeDelete/afterDelete events. If you need those first load a collection of records and delete them.
This method will *not* execute on associations' `cascade` attribute. You should use database foreign keys + ON CASCADE rules if you need cascading deletes combined with this method.
#### Parameters
`mixed` $conditions #### Returns
`int`
### deleteMany() public
```
deleteMany(iterableCake\Datasource\EntityInterface> $entities, ArrayAccess|array $options = []): iterableCake\Datasource\EntityInterface>|false
```
Deletes multiple entities of a table.
The records will be deleted in a transaction which will be rolled back if any one of the records fails to delete due to failed validation or database error.
#### Parameters
`iterableCake\Datasource\EntityInterface>` $entities Entities to delete.
`ArrayAccess|array` $options optional Options used when calling Table::save() for each entity.
#### Returns
`iterableCake\Datasource\EntityInterface>|false`
#### See Also
\Cake\ORM\Table::delete() for options and events related to this method. ### deleteManyOrFail() public
```
deleteManyOrFail(iterableCake\Datasource\EntityInterface> $entities, ArrayAccess|array $options = []): iterableCake\Datasource\EntityInterface>
```
Deletes multiple entities of a table.
The records will be deleted in a transaction which will be rolled back if any one of the records fails to delete due to failed validation or database error.
#### Parameters
`iterableCake\Datasource\EntityInterface>` $entities Entities to delete.
`ArrayAccess|array` $options optional Options used when calling Table::save() for each entity.
#### Returns
`iterableCake\Datasource\EntityInterface>`
#### Throws
`Cake\ORM\Exception\PersistenceFailedException`
#### See Also
\Cake\ORM\Table::delete() for options and events related to this method. ### deleteOrFail() public
```
deleteOrFail(Cake\Datasource\EntityInterface $entity, ArrayAccess|array $options = []): true
```
Try to delete an entity or throw a PersistenceFailedException if the entity is new, has no primary key value, application rules checks failed or the delete was aborted by a callback.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to remove.
`ArrayAccess|array` $options optional The options for the delete.
#### Returns
`true`
#### Throws
`Cake\ORM\Exception\PersistenceFailedException`
#### See Also
\Cake\ORM\Table::delete() ### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### exists() public
```
exists(array $conditions): bool
```
Returns true if there is any record in this repository matching the specified conditions.
#### Parameters
`array` $conditions #### Returns
`bool`
### find() public
```
find(string $type = 'all', array<string, mixed> $options = []): Cake\ORM\Query
```
Creates a new Query for this repository and applies some defaults based on the type of search that was selected.
### Model.beforeFind event
Each find() will trigger a `Model.beforeFind` event for all attached listeners. Any listener can set a valid result set using $query
By default, `$options` will recognize the following keys:
* fields
* conditions
* order
* limit
* offset
* page
* group
* having
* contain
* join
### Usage
Using the options array:
```
$query = $articles->find('all', [
'conditions' => ['published' => 1],
'limit' => 10,
'contain' => ['Users', 'Comments']
]);
```
Using the builder interface:
```
$query = $articles->find()
->where(['published' => 1])
->limit(10)
->contain(['Users', 'Comments']);
```
### Calling finders
The find() method is the entry point for custom finder methods. You can invoke a finder by specifying the type:
```
$query = $articles->find('published');
```
Would invoke the `findPublished` method.
#### Parameters
`string` $type optional the type of query to perform
`array<string, mixed>` $options optional An array that will be passed to Query::applyOptions()
#### Returns
`Cake\ORM\Query`
### findAll() public
```
findAll(Cake\ORM\Query $query, array<string, mixed> $options): Cake\ORM\Query
```
Returns the query as passed.
By default findAll() applies no conditions, you can override this method in subclasses to modify how `find('all')` works.
#### Parameters
`Cake\ORM\Query` $query The query to find with
`array<string, mixed>` $options The options to use for the find
#### Returns
`Cake\ORM\Query`
### findAssociation() protected
```
findAssociation(string $name): Cake\ORM\Association|null
```
Returns an association object configured for the specified alias if any.
The name argument also supports dot syntax to access deeper associations.
```
$users = $this->getAssociation('Articles.Comments.Users');
```
#### Parameters
`string` $name The alias used for the association.
#### Returns
`Cake\ORM\Association|null`
### findList() public
```
findList(Cake\ORM\Query $query, array<string, mixed> $options): Cake\ORM\Query
```
Sets up a query object so results appear as an indexed array, useful for any place where you would want a list such as for populating input select boxes.
When calling this finder, the fields passed are used to determine what should be used as the array key, value and optionally what to group the results by. By default, the primary key for the model is used for the key, and the display field as value.
The results of this finder will be in the following form:
```
[
1 => 'value for id 1',
2 => 'value for id 2',
4 => 'value for id 4'
]
```
You can specify which property will be used as the key and which as value by using the `$options` array, when not specified, it will use the results of calling `primaryKey` and `displayField` respectively in this table:
```
$table->find('list', [
'keyField' => 'name',
'valueField' => 'age'
]);
```
The `valueField` can also be an array, in which case you can also specify the `valueSeparator` option to control how the values will be concatenated:
```
$table->find('list', [
'valueField' => ['first_name', 'last_name'],
'valueSeparator' => ' | ',
]);
```
The results of this finder will be in the following form:
```
[
1 => 'John | Doe',
2 => 'Steve | Smith'
]
```
Results can be put together in bigger groups when they share a property, you can customize the property to use for grouping by setting `groupField`:
```
$table->find('list', [
'groupField' => 'category_id',
]);
```
When using a `groupField` results will be returned in this format:
```
[
'group_1' => [
1 => 'value for id 1',
2 => 'value for id 2',
]
'group_2' => [
4 => 'value for id 4'
]
]
```
#### Parameters
`Cake\ORM\Query` $query The query to find with
`array<string, mixed>` $options The options for the find
#### Returns
`Cake\ORM\Query`
### findOrCreate() public
```
findOrCreate(Cake\ORM\Query|callable|array $search, callable|null $callback = null, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
```
Finds an existing record or creates a new one.
A find() will be done to locate an existing record using the attributes defined in $search. If records matches the conditions, the first record will be returned.
If no record can be found, a new entity will be created with the $search properties. If a callback is provided, it will be called allowing you to define additional default values. The new entity will be saved and returned.
If your find conditions require custom order, associations or conditions, then the $search parameter can be a callable that takes the Query as the argument, or a \Cake\ORM\Query object passed as the $search parameter. Allowing you to customize the find results.
### Options
The options array is passed to the save method with exception to the following keys:
* atomic: Whether to execute the methods for find, save and callbacks inside a database transaction (default: true)
* defaults: Whether to use the search criteria as default values for the new entity (default: true)
#### Parameters
`Cake\ORM\Query|callable|array` $search The criteria to find existing records by. Note that when you pass a query object you'll have to use the 2nd arg of the method to modify the entity data before saving.
`callable|null` $callback optional A callback that will be invoked for newly created entities. This callback will be called *before* the entity is persisted.
`array<string, mixed>` $options optional The options to use when saving.
#### Returns
`Cake\Datasource\EntityInterface`
#### Throws
`Cake\ORM\Exception\PersistenceFailedException`
When the entity couldn't be saved ### findThreaded() public
```
findThreaded(Cake\ORM\Query $query, array<string, mixed> $options): Cake\ORM\Query
```
Results for this finder will be a nested array, and is appropriate if you want to use the parent\_id field of your model data to build nested results.
Values belonging to a parent row based on their parent\_id value will be recursively nested inside the parent row values using the `children` property
You can customize what fields are used for nesting results, by default the primary key and the `parent_id` fields are used. If you wish to change these defaults you need to provide the keys `keyField`, `parentField` or `nestingKey` in `$options`:
```
$table->find('threaded', [
'keyField' => 'id',
'parentField' => 'ancestor_id',
'nestingKey' => 'children'
]);
```
#### Parameters
`Cake\ORM\Query` $query The query to find with
`array<string, mixed>` $options The options to find with
#### Returns
`Cake\ORM\Query`
### get() public
```
get(mixed $primaryKey, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
```
Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
### Usage
Get an article and some relationships:
```
$article = $articles->get(1, ['contain' => ['Users', 'Comments']]);
```
#### Parameters
`mixed` $primaryKey primary key value to find
`array<string, mixed>` $options optional options accepted by `Table::find()`
#### Returns
`Cake\Datasource\EntityInterface`
#### Throws
`Cake\Datasource\Exception\RecordNotFoundException`
if the record with such id could not be found
`Cake\Datasource\Exception\InvalidPrimaryKeyException`
When $primaryKey has an incorrect number of elements. #### See Also
\Cake\Datasource\RepositoryInterface::find() ### getAlias() public
```
getAlias(): string
```
Returns the table alias.
#### Returns
`string`
### getAssociation() public
```
getAssociation(string $name): Cake\ORM\Association
```
Returns an association object configured for the specified alias.
The name argument also supports dot syntax to access deeper associations.
```
$users = $this->getAssociation('Articles.Comments.Users');
```
Note that this method requires the association to be present or otherwise throws an exception. If you are not sure, use hasAssociation() before calling this method.
#### Parameters
`string` $name The alias used for the association.
#### Returns
`Cake\ORM\Association`
#### Throws
`InvalidArgumentException`
### getBehavior() public
```
getBehavior(string $name): Cake\ORM\Behavior
```
Get a behavior from the registry.
#### Parameters
`string` $name The behavior alias to get from the registry.
#### Returns
`Cake\ORM\Behavior`
#### Throws
`InvalidArgumentException`
If the behavior does not exist. ### getConnection() public
```
getConnection(): Cake\Database\Connection
```
Returns the connection instance.
#### Returns
`Cake\Database\Connection`
### getDisplayField() public
```
getDisplayField(): array<string>|string|null
```
Returns the display field.
#### Returns
`array<string>|string|null`
### getEntityClass() public
```
getEntityClass(): string
```
Returns the class used to hydrate rows for this table.
#### Returns
`string`
### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Returns the Cake\Event\EventManager manager instance for this object.
You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.
#### Returns
`Cake\Event\EventManagerInterface`
### getPrimaryKey() public
```
getPrimaryKey(): array<string>|string
```
Returns the primary key field name.
#### Returns
`array<string>|string`
### getRegistryAlias() public
```
getRegistryAlias(): string
```
Returns the table registry key used to create this table instance.
#### Returns
`string`
### getSaveOptionsBuilder() public
```
getSaveOptionsBuilder(array<string, mixed> $options = []): Cake\ORM\SaveOptionsBuilder
```
Gets a SaveOptionsBuilder instance.
#### Parameters
`array<string, mixed>` $options optional Options to parse by the builder.
#### Returns
`Cake\ORM\SaveOptionsBuilder`
### getSchema() public
```
getSchema(): Cake\Database\Schema\TableSchemaInterface
```
Returns the schema table object describing this table's properties.
#### Returns
`Cake\Database\Schema\TableSchemaInterface`
### getTable() public
```
getTable(): string
```
Returns the database table name.
This can include the database schema name if set using `setTable()`.
#### Returns
`string`
### getValidator() public
```
getValidator(string|null $name = null): Cake\Validation\Validator
```
Returns the validation rules tagged with $name. It is possible to have multiple different named validation sets, this is useful when you need to use varying rules when saving from different routines in your system.
If a validator has not been set earlier, this method will build a valiator using a method inside your class.
For example, if you wish to create a validation set called 'forSubscription', you will need to create a method in your Table subclass as follows:
```
public function validationForSubscription($validator)
{
return $validator
->add('email', 'valid-email', ['rule' => 'email'])
->add('password', 'valid', ['rule' => 'notBlank'])
->requirePresence('username');
}
$validator = $this->getValidator('forSubscription');
```
You can implement the method in `validationDefault` in your Table subclass should you wish to have a validation set that applies in cases where no other set is specified.
If a $name argument has not been provided, the default validator will be returned. You can configure your default validator name in a `DEFAULT_VALIDATOR` class constant.
#### Parameters
`string|null` $name optional The name of the validation set to return.
#### Returns
`Cake\Validation\Validator`
### hasAssociation() public
```
hasAssociation(string $name): bool
```
Checks whether a specific association exists on this Table instance.
The name argument also supports dot syntax to access deeper associations.
```
$hasUsers = $this->hasAssociation('Articles.Comments.Users');
```
#### Parameters
`string` $name The alias used for the association.
#### Returns
`bool`
### hasBehavior() public
```
hasBehavior(string $name): bool
```
Check if a behavior with the given alias has been loaded.
#### Parameters
`string` $name The behavior alias to check.
#### Returns
`bool`
### hasField() public
```
hasField(string $field): bool
```
Test to see if a Table has a specific field/column.
Delegates to the schema object and checks for column presence using the Schema\Table instance.
#### Parameters
`string` $field The field to check for.
#### Returns
`bool`
### hasFinder() public
```
hasFinder(string $type): bool
```
Returns true if the finder exists for the table
#### Parameters
`string` $type name of finder to check
#### Returns
`bool`
### hasMany() public
```
hasMany(string $associated, array<string, mixed> $options = []): Cake\ORM\Association\HasMany
```
Creates a new HasMany association between this table and a target table. A "has many" association is a 1-N relationship.
Target table can be inferred by its name, which is provided in the first argument, or you can either pass the class name to be instantiated or an instance of it directly.
The options array accept the following keys:
* className: The class name of the target table object
* targetTable: An instance of a table object to be used as the target table
* foreignKey: The name of the field to use as foreign key, if false none will be used
* dependent: Set to true if you want CakePHP to cascade deletes to the associated table when an entity is removed on this table. The delete operation on the associated table will not cascade further. To get recursive cascades enable `cascadeCallbacks` as well. Set to false if you don't want CakePHP to remove associated data, or when you are using database constraints.
* cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on cascaded deletes. If false the ORM will use deleteAll() to remove data. When true records will be loaded and then deleted.
* conditions: array with a list of conditions to filter the join with
* sort: The order in which results for this association should be returned
* saveStrategy: Either 'append' or 'replace'. When 'append' the current records are appended to any records in the database. When 'replace' associated records not in the current set will be removed. If the foreign key is a null able column or if `dependent` is true records will be orphaned.
* strategy: The strategy to be used for selecting results Either 'select' or 'subquery'. If subquery is selected the query used to return results in the source table will be used as conditions for getting rows in the target table.
* finder: The finder method to use when loading records from this association. Defaults to 'all'.
This method will return the association object that was built.
#### Parameters
`string` $associated the alias for the target table. This is used to uniquely identify the association
`array<string, mixed>` $options optional list of options to configure the association definition
#### Returns
`Cake\ORM\Association\HasMany`
### hasOne() public
```
hasOne(string $associated, array<string, mixed> $options = []): Cake\ORM\Association\HasOne
```
Creates a new HasOne association between this table and a target table. A "has one" association is a 1-1 relationship.
Target table can be inferred by its name, which is provided in the first argument, or you can either pass the class name to be instantiated or an instance of it directly.
The options array accept the following keys:
* className: The class name of the target table object
* targetTable: An instance of a table object to be used as the target table
* foreignKey: The name of the field to use as foreign key, if false none will be used
* dependent: Set to true if you want CakePHP to cascade deletes to the associated table when an entity is removed on this table. The delete operation on the associated table will not cascade further. To get recursive cascades enable `cascadeCallbacks` as well. Set to false if you don't want CakePHP to remove associated data, or when you are using database constraints.
* cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on cascaded deletes. If false the ORM will use deleteAll() to remove data. When true records will be loaded and then deleted.
* conditions: array with a list of conditions to filter the join with
* joinType: The type of join to be used (e.g. LEFT)
* strategy: The loading strategy to use. 'join' and 'select' are supported.
* finder: The finder method to use when loading records from this association. Defaults to 'all'. When the strategy is 'join', only the fields, containments, and where conditions will be used from the finder.
This method will return the association object that was built.
#### Parameters
`string` $associated the alias for the target table. This is used to uniquely identify the association
`array<string, mixed>` $options optional list of options to configure the association definition
#### Returns
`Cake\ORM\Association\HasOne`
### hasValidator() public
```
hasValidator(string $name): bool
```
Checks whether a validator has been set.
#### Parameters
`string` $name The name of a validator.
#### Returns
`bool`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Get the Model callbacks this table is interested in.
By implementing the conventional methods a table class is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want you table to listen to non-standard events.
The conventional method map is:
* Model.beforeMarshal => beforeMarshal
* Model.afterMarshal => afterMarshal
* Model.buildValidator => buildValidator
* Model.beforeFind => beforeFind
* Model.beforeSave => beforeSave
* Model.afterSave => afterSave
* Model.afterSaveCommit => afterSaveCommit
* Model.beforeDelete => beforeDelete
* Model.afterDelete => afterDelete
* Model.afterDeleteCommit => afterDeleteCommit
* Model.beforeRules => beforeRules
* Model.afterRules => afterRules
#### Returns
`array<string, mixed>`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Initialize a table instance. Called after the constructor.
You can use this method to define associations, attach behaviors define validation and do any other initialization logic you need.
```
public function initialize(array $config)
{
$this->belongsTo('Users');
$this->belongsToMany('Tagging.Tags');
$this->setPrimaryKey('something_else');
}
```
#### Parameters
`array<string, mixed>` $config Configuration options passed to the constructor
#### Returns
`void`
### loadInto() public
```
loadInto(Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface> $entities, array $contain): Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>
```
Loads the specified associations in the passed entity or list of entities by executing extra queries in the database and merging the results in the appropriate properties.
### Example:
```
$user = $usersTable->get(1);
$user = $usersTable->loadInto($user, ['Articles.Tags', 'Articles.Comments']);
echo $user->articles[0]->title;
```
You can also load associations for multiple entities at once
### Example:
```
$users = $usersTable->find()->where([...])->toList();
$users = $usersTable->loadInto($users, ['Articles.Tags', 'Articles.Comments']);
echo $user[1]->articles[0]->title;
```
The properties for the associations to be loaded will be overwritten on each entity.
#### Parameters
`Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>` $entities a single entity or list of entities
`array` $contain A `contain()` compatible array.
#### Returns
`Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>`
#### See Also
\Cake\ORM\Query::contain() ### marshaller() public
```
marshaller(): Cake\ORM\Marshaller
```
Get the object used to marshal/convert array data into objects.
Override this method if you want a table object to use custom marshalling logic.
#### Returns
`Cake\ORM\Marshaller`
#### See Also
\Cake\ORM\Marshaller ### newEmptyEntity() public
```
newEmptyEntity(): Cake\Datasource\EntityInterface
```
This creates a new entity object.
Careful: This does not trigger any field validation. This entity can be persisted without validation error as empty record. Always patch in required fields before saving.
#### Returns
`Cake\Datasource\EntityInterface`
### newEntities() public
```
newEntities(array $data, array<string, mixed> $options = []): arrayCake\Datasource\EntityInterface>
```
Create a list of entities + associated entities from an array.
By default all the associations on this table will be hydrated. You can limit which associations are built, or include deeper associations using the options parameter:
```
$articles = $this->Articles->newEntities(
$this->request->getData(),
['associated' => ['Tags', 'Comments.Users']]
);
```
You can limit fields that will be present in the constructed entities by passing the `fields` option, which is also accepted for associations:
```
$articles = $this->Articles->newEntities($this->request->getData(), [
'fields' => ['title', 'body', 'tags', 'comments'],
'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']]
]
);
```
You can use the `Model.beforeMarshal` event to modify request data before it is converted into entities.
#### Parameters
`array` $data The data to build an entity with.
`array<string, mixed>` $options optional A list of options for the objects hydration.
#### Returns
`arrayCake\Datasource\EntityInterface>`
### newEntity() public
```
newEntity(array $data, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
```
Create a new entity + associated entities from an array.
By default all the associations on this table will be hydrated. You can limit which associations are built, or include deeper associations using the options parameter:
```
$article = $this->Articles->newEntity(
$this->request->getData(),
['associated' => ['Tags', 'Comments.Users']]
);
```
You can limit fields that will be present in the constructed entity by passing the `fields` option, which is also accepted for associations:
```
$article = $this->Articles->newEntity($this->request->getData(), [
'fields' => ['title', 'body', 'tags', 'comments'],
'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']]
]
);
```
The `fields` option lets remove or restrict input data from ending up in the entity. If you'd like to relax the entity's default accessible fields, you can use the `accessibleFields` option:
```
$article = $this->Articles->newEntity(
$this->request->getData(),
['accessibleFields' => ['protected_field' => true]]
);
```
By default, the data is validated before being passed to the new entity. In the case of invalid fields, those will not be present in the resulting object. The `validate` option can be used to disable validation on the passed data:
```
$article = $this->Articles->newEntity(
$this->request->getData(),
['validate' => false]
);
```
You can also pass the name of the validator to use in the `validate` option. If `null` is passed to the first param of this function, no validation will be performed.
You can use the `Model.beforeMarshal` event to modify request data before it is converted into entities.
#### Parameters
`array` $data The data to build an entity with.
`array<string, mixed>` $options optional A list of options for the object hydration.
#### Returns
`Cake\Datasource\EntityInterface`
#### See Also
\Cake\ORM\Marshaller::one() ### patchEntities() public
```
patchEntities(iterableCake\Datasource\EntityInterface> $entities, array $data, array<string, mixed> $options = []): arrayCake\Datasource\EntityInterface>
```
Merges each of the elements passed in `$data` into the entities found in `$entities` respecting the accessible fields configured on the entities. Merging is done by matching the primary key in each of the elements in `$data` and `$entities`.
Those entries in `$entities` that cannot be matched to any record in `$data` will be discarded. Records in `$data` that could not be matched will be marshalled as a new entity.
When merging HasMany or BelongsToMany associations, all the entities in the `$data` array will appear, those that can be matched by primary key will get the data merged, but those that cannot, will be discarded.
You can limit fields that will be present in the merged entities by passing the `fields` option, which is also accepted for associations:
```
$articles = $this->Articles->patchEntities($articles, $this->request->getData(), [
'fields' => ['title', 'body', 'tags', 'comments'],
'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']]
]
);
```
You can use the `Model.beforeMarshal` event to modify request data before it is converted into entities.
#### Parameters
`iterableCake\Datasource\EntityInterface>` $entities the entities that will get the data merged in
`array` $data list of arrays to be merged into the entities
`array<string, mixed>` $options optional A list of options for the objects hydration.
#### Returns
`arrayCake\Datasource\EntityInterface>`
### patchEntity() public
```
patchEntity(Cake\Datasource\EntityInterface $entity, array $data, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
```
Merges the passed `$data` into `$entity` respecting the accessible fields configured on the entity. Returns the same entity after being altered.
When merging HasMany or BelongsToMany associations, all the entities in the `$data` array will appear, those that can be matched by primary key will get the data merged, but those that cannot, will be discarded.
You can limit fields that will be present in the merged entity by passing the `fields` option, which is also accepted for associations:
```
$article = $this->Articles->patchEntity($article, $this->request->getData(), [
'fields' => ['title', 'body', 'tags', 'comments'],
'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']]
]
);
```
```
$article = $this->Articles->patchEntity($article, $this->request->getData(), [
'associated' => [
'Tags' => ['accessibleFields' => ['*' => true]]
]
]);
```
By default, the data is validated before being passed to the entity. In the case of invalid fields, those will not be assigned to the entity. The `validate` option can be used to disable validation on the passed data:
```
$article = $this->patchEntity($article, $this->request->getData(),[
'validate' => false
]);
```
You can use the `Model.beforeMarshal` event to modify request data before it is converted into entities.
When patching scalar values (null/booleans/string/integer/float), if the property presently has an identical value, the setter will not be called, and the property will not be marked as dirty. This is an optimization to prevent unnecessary field updates when persisting entities.
#### Parameters
`Cake\Datasource\EntityInterface` $entity the entity that will get the data merged in
`array` $data key value list of fields to be merged into the entity
`array<string, mixed>` $options optional A list of options for the object hydration.
#### Returns
`Cake\Datasource\EntityInterface`
#### See Also
\Cake\ORM\Marshaller::merge() ### query() public
```
query(): Cake\ORM\Query
```
Creates a new Query instance for a table.
#### Returns
`Cake\ORM\Query`
### removeBehavior() public
```
removeBehavior(string $name): $this
```
Removes a behavior from this table's behavior registry.
Example:
Remove a behavior from this table.
```
$this->removeBehavior('Tree');
```
#### Parameters
`string` $name The alias that the behavior was added with.
#### Returns
`$this`
#### See Also
\Cake\ORM\Behavior ### rulesChecker() public
```
rulesChecker(): Cake\Datasource\RulesChecker
```
Returns the RulesChecker for this instance.
A RulesChecker object is used to test an entity for validity on rules that may involve complex logic or data that needs to be fetched from relevant datasources.
#### Returns
`Cake\Datasource\RulesChecker`
#### See Also
\Cake\Datasource\RulesChecker ### save() public
```
save(Cake\Datasource\EntityInterface $entity, ArrayAccess|array $options = []): Cake\Datasource\EntityInterface|false
```
Persists an entity based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error.
### Options
The options array accepts the following keys:
* atomic: Whether to execute the save and callbacks inside a database transaction (default: true)
* checkRules: Whether to check the rules on entity before saving, if the checking fails, it will abort the save operation. (default:true)
* associated: If `true` it will save 1st level associated entities as they are found in the passed `$entity` whenever the property defined for the association is marked as dirty. If an array, it will be interpreted as the list of associations to be saved. It is possible to provide different options for saving on associated table objects using this key by making the custom options the array value. If `false` no associated records will be saved. (default: `true`)
* checkExisting: Whether to check if the entity already exists, assuming that the entity is marked as not new, and the primary key has been set.
### Events
When saving, this method will trigger four events:
* Model.beforeRules: Will be triggered right before any rule checking is done for the passed entity if the `checkRules` key in $options is not set to false. Listeners will receive as arguments the entity, options array and the operation type. If the event is stopped the rules check result will be set to the result of the event itself.
* Model.afterRules: Will be triggered right after the `checkRules()` method is called for the entity. Listeners will receive as arguments the entity, options array, the result of checking the rules and the operation type. If the event is stopped the checking result will be set to the result of the event itself.
* Model.beforeSave: Will be triggered just before the list of fields to be persisted is calculated. It receives both the entity and the options as arguments. The options array is passed as an ArrayObject, so any changes in it will be reflected in every listener and remembered at the end of the event so it can be used for the rest of the save operation. Returning false in any of the listeners will abort the saving process. If the event is stopped using the event API, the event object's `result` property will be returned. This can be useful when having your own saving strategy implemented inside a listener.
* Model.afterSave: Will be triggered after a successful insert or save, listeners will receive the entity and the options array as arguments. The type of operation performed (insert or update) can be determined by checking the entity's method `isNew`, true meaning an insert and false an update.
* Model.afterSaveCommit: Will be triggered after the transaction is committed for atomic save, listeners will receive the entity and the options array as arguments.
This method will determine whether the passed entity needs to be inserted or updated in the database. It does that by checking the `isNew` method on the entity. If the entity to be saved returns a non-empty value from its `errors()` method, it will not be saved.
### Saving on associated tables
This method will by default persist entities belonging to associated tables, whenever a dirty property matching the name of the property name set for an association in this table. It is possible to control what associations will be saved and to pass additional option for saving them.
```
// Only save the comments association
$articles->save($entity, ['associated' => ['Comments']]);
// Save the company, the employees and related addresses for each of them.
// For employees do not check the entity rules
$companies->save($entity, [
'associated' => [
'Employees' => [
'associated' => ['Addresses'],
'checkRules' => false
]
]
]);
// Save no associations
$articles->save($entity, ['associated' => false]);
```
#### Parameters
`Cake\Datasource\EntityInterface` $entity the entity to be saved
`ArrayAccess|array` $options optional The options to use when saving.
#### Returns
`Cake\Datasource\EntityInterface|false`
#### Throws
`Cake\ORM\Exception\RolledbackTransactionException`
If the transaction is aborted in the afterSave event. ### saveMany() public
```
saveMany(iterableCake\Datasource\EntityInterface> $entities, Cake\ORM\SaveOptionsBuilderArrayAccess|array $options = []): iterableCake\Datasource\EntityInterface>|false
```
Persists multiple entities of a table.
The records will be saved in a transaction which will be rolled back if any one of the records fails to save due to failed validation or database error.
#### Parameters
`iterableCake\Datasource\EntityInterface>` $entities Entities to save.
`Cake\ORM\SaveOptionsBuilderArrayAccess|array` $options optional Options used when calling Table::save() for each entity.
#### Returns
`iterableCake\Datasource\EntityInterface>|false`
#### Throws
`Exception`
### saveManyOrFail() public
```
saveManyOrFail(iterableCake\Datasource\EntityInterface> $entities, ArrayAccess|array $options = []): iterableCake\Datasource\EntityInterface>
```
Persists multiple entities of a table.
The records will be saved in a transaction which will be rolled back if any one of the records fails to save due to failed validation or database error.
#### Parameters
`iterableCake\Datasource\EntityInterface>` $entities Entities to save.
`ArrayAccess|array` $options optional Options used when calling Table::save() for each entity.
#### Returns
`iterableCake\Datasource\EntityInterface>`
#### Throws
`Exception`
`Cake\ORM\Exception\PersistenceFailedException`
If an entity couldn't be saved. ### saveOrFail() public
```
saveOrFail(Cake\Datasource\EntityInterface $entity, ArrayAccess|array $options = []): Cake\Datasource\EntityInterface
```
Try to save an entity or throw a PersistenceFailedException if the application rules checks failed, the entity contains errors or the save was aborted by a callback.
#### Parameters
`Cake\Datasource\EntityInterface` $entity the entity to be saved
`ArrayAccess|array` $options optional The options to use when saving.
#### Returns
`Cake\Datasource\EntityInterface`
#### Throws
`Cake\ORM\Exception\PersistenceFailedException`
When the entity couldn't be saved #### See Also
\Cake\ORM\Table::save() ### setAlias() public
```
setAlias(string $alias): $this
```
Sets the table alias.
#### Parameters
`string` $alias Table alias
#### Returns
`$this`
### setConnection() public
```
setConnection(Cake\Database\Connection $connection): $this
```
Sets the connection instance.
#### Parameters
`Cake\Database\Connection` $connection The connection instance
#### Returns
`$this`
### setDisplayField() public
```
setDisplayField(array<string>|string $field): $this
```
Sets the display field.
#### Parameters
`array<string>|string` $field Name to be used as display field.
#### Returns
`$this`
### setEntityClass() public
```
setEntityClass(string $name): $this
```
Sets the class used to hydrate rows for this table.
#### Parameters
`string` $name The name of the class to use
#### Returns
`$this`
#### Throws
`Cake\ORM\Exception\MissingEntityException`
when the entity class cannot be found ### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $this
```
Returns the Cake\Event\EventManagerInterface instance for this object.
You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager the eventManager to set
#### Returns
`$this`
### setPrimaryKey() public
```
setPrimaryKey(array<string>|string $key): $this
```
Sets the primary key field name.
#### Parameters
`array<string>|string` $key Sets a new name to be used as primary key
#### Returns
`$this`
### setRegistryAlias() public
```
setRegistryAlias(string $registryAlias): $this
```
Sets the table registry key used to create this table instance.
#### Parameters
`string` $registryAlias The key used to access this object.
#### Returns
`$this`
### setSchema() public
```
setSchema(Cake\Database\Schema\TableSchemaInterface|array $schema): $this
```
Sets the schema table object describing this table's properties.
If an array is passed, a new TableSchemaInterface will be constructed out of it and used as the schema for this table.
#### Parameters
`Cake\Database\Schema\TableSchemaInterface|array` $schema Schema to be used for this table
#### Returns
`$this`
### setTable() public
```
setTable(string $table): $this
```
Sets the database table name.
This can include the database schema name in the form 'schema.table'. If the name must be quoted, enable automatic identifier quoting.
#### Parameters
`string` $table Table name.
#### Returns
`$this`
### setValidator() public
```
setValidator(string $name, Cake\Validation\Validator $validator): $this
```
This method stores a custom validator under the given name.
You can build the object by yourself and store it in your object:
```
$validator = new \Cake\Validation\Validator();
$validator
->add('email', 'valid-email', ['rule' => 'email'])
->add('password', 'valid', ['rule' => 'notBlank'])
->allowEmpty('bio');
$this->setValidator('forSubscription', $validator);
```
#### Parameters
`string` $name The name of a validator to be set.
`Cake\Validation\Validator` $validator Validator object to be set.
#### Returns
`$this`
### subquery() public
```
subquery(): Cake\ORM\Query
```
Creates a new Query::subquery() instance for a table.
#### Returns
`Cake\ORM\Query`
#### See Also
\Cake\ORM\Query::subquery() ### updateAll() public
```
updateAll(Cake\Database\Expression\QueryExpressionClosure|array|string $fields, mixed $conditions): int
```
Update all matching records.
Sets the $fields to the provided values based on $conditions. This method will *not* trigger beforeSave/afterSave events. If you need those first load a collection of records and update them.
#### Parameters
`Cake\Database\Expression\QueryExpressionClosure|array|string` $fields `mixed` $conditions #### Returns
`int`
### validateUnique() public
```
validateUnique(mixed $value, array<string, mixed> $options, array|null $context = null): bool
```
Validator method used to check the uniqueness of a value for a column. This is meant to be used with the validation API and not to be called directly.
### Example:
```
$validator->add('email', [
'unique' => ['rule' => 'validateUnique', 'provider' => 'table']
])
```
Unique validation can be scoped to the value of another column:
```
$validator->add('email', [
'unique' => [
'rule' => ['validateUnique', ['scope' => 'site_id']],
'provider' => 'table'
]
]);
```
In the above example, the email uniqueness will be scoped to only rows having the same site\_id. Scoping will only be used if the scoping field is present in the data to be validated.
#### Parameters
`mixed` $value The value of column to be checked for uniqueness.
`array<string, mixed>` $options The options array, optionally containing the 'scope' key. May also be the validation context, if there are no options.
`array|null` $context optional Either the validation context or null.
#### Returns
`bool`
### validationDefault() public
```
validationDefault(Cake\Validation\Validator $validator): Cake\Validation\Validator
```
Returns the default validator object. Subclasses can override this function to add a default validation set to the validator object.
#### Parameters
`Cake\Validation\Validator` $validator The validator that can be modified to add some rules to it.
#### Returns
`Cake\Validation\Validator`
### validationMethodExists() protected
```
validationMethodExists(string $name): bool
```
Checks if validation method exists.
#### Parameters
`string` $name #### Returns
`bool`
Property Detail
---------------
### $\_alias protected
Human name giving to this particular instance. Multiple objects representing the same database table can exist by using different aliases.
#### Type
`string|null`
### $\_associations protected
The associations container for this Table.
#### Type
`Cake\ORM\AssociationCollection`
### $\_behaviors protected
BehaviorRegistry for this table
#### Type
`Cake\ORM\BehaviorRegistry`
### $\_connection protected
Connection instance
#### Type
`Cake\Database\Connection|null`
### $\_displayField protected
The name of the field that represents a human-readable representation of a row
#### Type
`array<string>|string|null`
### $\_entityClass protected
The name of the class that represent a single row for this table
#### Type
`string`
### $\_eventClass protected
Default class name for new event objects.
#### Type
`string`
### $\_eventManager protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
#### Type
`Cake\Event\EventManagerInterface|null`
### $\_primaryKey protected
The name of the field that represents the primary key in the table
#### Type
`array<string>|string|null`
### $\_registryAlias protected
Registry key used to create this table object
#### Type
`string|null`
### $\_rulesChecker protected
The domain rules to be applied to entities saved by this table
#### Type
`Cake\Datasource\RulesChecker`
### $\_schema protected
The schema object containing a description of this table fields
#### Type
`Cake\Database\Schema\TableSchemaInterface|null`
### $\_table protected
Name of the table as it can be found in the database
#### Type
`string|null`
### $\_validatorClass protected
Validator class.
#### Type
`string`
### $\_validators protected
A list of validation objects indexed by name
#### Type
`arrayCake\Validation\Validator>`
| programming_docs |
cakephp Class HelpCommand Class HelpCommand
==================
Print out command list
**Namespace:** [Cake\Console\Command](namespace-cake.console.command)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$commands](#%24commands) protected `Cake\Console\CommandCollection` The command collection to get help on.
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [asText()](#asText()) protected
Output text.
* ##### [asXml()](#asXml()) protected
Output as XML
* ##### [buildOptionParser()](#buildOptionParser()) protected
Gets the option parser instance and configures it.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) public
Main function Prints out the list of commands.
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [getShortestName()](#getShortestName()) protected
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [outputPaths()](#outputPaths()) protected
Output relevant paths if defined
* ##### [run()](#run()) public
Run the command.
* ##### [setCommandCollection()](#setCommandCollection()) public
Set the command collection being used.
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
Method Detail
-------------
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### asText() protected
```
asText(Cake\Console\ConsoleIo $io, iterable $commands): void
```
Output text.
#### Parameters
`Cake\Console\ConsoleIo` $io The console io
`iterable` $commands The command collection to output.
#### Returns
`void`
### asXml() protected
```
asXml(Cake\Console\ConsoleIo $io, iterable $commands): void
```
Output as XML
#### Parameters
`Cake\Console\ConsoleIo` $io The console io
`iterable` $commands The command collection to output
#### Returns
`void`
### buildOptionParser() protected
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Gets the option parser instance and configures it.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The parser to build
#### Returns
`Cake\Console\ConsoleOptionParser`
### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int
```
Main function Prints out the list of commands.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### getShortestName() protected
```
getShortestName(array<string> $names): string
```
#### Parameters
`array<string>` $names Names
#### Returns
`string`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### outputPaths() protected
```
outputPaths(Cake\Console\ConsoleIo $io): void
```
Output relevant paths if defined
#### Parameters
`Cake\Console\ConsoleIo` $io IO object.
#### Returns
`void`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setCommandCollection() public
```
setCommandCollection(Cake\Console\CommandCollection $commands): void
```
Set the command collection being used.
#### Parameters
`Cake\Console\CommandCollection` $commands #### Returns
`void`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
Property Detail
---------------
### $commands protected
The command collection to get help on.
#### Type
`Cake\Console\CommandCollection`
### $name protected
The name of this command.
#### Type
`string`
cakephp Class SecurityComponent Class SecurityComponent
========================
The Security Component creates an easy way to integrate tighter security in your application. It provides methods for these tasks:
* Form tampering protection.
* Requiring that SSL be used.
**Namespace:** [Cake\Controller\Component](namespace-cake.controller.component)
**Deprecated:** 4.0.0 Use {@link FormProtectionComponent} instead, for form tampering protection or {@link HttpsEnforcerMiddleware} to enforce use of HTTPS (SSL) for requests.
**Link:** https://book.cakephp.org/4/en/controllers/components/security.html
Constants
---------
* `string` **DEFAULT\_EXCEPTION\_MESSAGE**
```
'The request has been black-holed'
```
Default message used for exceptions thrown
Property Summary
----------------
* [$\_action](#%24_action) protected `string` Holds the current action of the controller
* [$\_componentMap](#%24_componentMap) protected `array<string, array>` A component lookup table used to lazy load component objects.
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config
* [$\_registry](#%24_registry) protected `Cake\Controller\ComponentRegistry` Component registry class used to lazy load components.
* [$components](#%24components) protected `array` Other Components this component uses.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Magic method for lazy loading $components.
* ##### [\_callback()](#_callback()) protected
Calls a controller callback method
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_debugCheckFields()](#_debugCheckFields()) protected
Iterates data array to check against expected
* ##### [\_debugExpectedFields()](#_debugExpectedFields()) protected
Generate debug message for the expected fields
* ##### [\_debugPostTokenNotMatching()](#_debugPostTokenNotMatching()) protected
Create a message for humans to understand why Security token is not matching
* ##### [\_fieldsList()](#_fieldsList()) protected
Return the fields list for the hash calculation
* ##### [\_hashParts()](#_hashParts()) protected
Return hash parts for the Token generation
* ##### [\_matchExistingFields()](#_matchExistingFields()) protected
Generate array of messages for the existing fields in POST data, matching dataFields in $expectedFields will be unset
* ##### [\_secureRequired()](#_secureRequired()) protected
Check if access requires secure connection
* ##### [\_sortedUnlocked()](#_sortedUnlocked()) protected
Get the sorted unlocked string
* ##### [\_throwException()](#_throwException()) protected
Check debug status and throw an Exception based on the existing one
* ##### [\_unlocked()](#_unlocked()) protected
Get the unlocked string
* ##### [\_validToken()](#_validToken()) protected
Check if token is valid
* ##### [\_validatePost()](#_validatePost()) protected
Validate submitted form
* ##### [blackHole()](#blackHole()) public
Black-hole an invalid request with a 400 error or custom callback. If SecurityComponent::$blackHoleCallback is specified, it will use this callback by executing the method indicated in $error
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [generateToken()](#generateToken()) public
Manually add form tampering prevention token information into the provided request object.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getController()](#getController()) public
Get the controller this component is bound to.
* ##### [implementedEvents()](#implementedEvents()) public
Events supported by this component.
* ##### [initialize()](#initialize()) public
Constructor hook method.
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [requireSecure()](#requireSecure()) public
Sets the actions that require a request that is SSL-secured, or empty for all actions
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [startup()](#startup()) public
Component startup. All security checking happens here.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Controller\ComponentRegistry $registry, array<string, mixed> $config = [])
```
Constructor
#### Parameters
`Cake\Controller\ComponentRegistry` $registry A component registry this component can use to lazy load its components.
`array<string, mixed>` $config optional Array of configuration settings.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\Controller\Component|null
```
Magic method for lazy loading $components.
#### Parameters
`string` $name Name of component to get.
#### Returns
`Cake\Controller\Component|null`
### \_callback() protected
```
_callback(Cake\Controller\Controller $controller, string $method, array $params = []): mixed
```
Calls a controller callback method
#### Parameters
`Cake\Controller\Controller` $controller Instantiating controller
`string` $method Method to execute
`array` $params optional Parameters to send to method
#### Returns
`mixed`
#### Throws
`Cake\Http\Exception\BadRequestException`
When a the blackholeCallback is not callable. ### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_debugCheckFields() protected
```
_debugCheckFields(array $dataFields, array $expectedFields = [], string $intKeyMessage = '', string $stringKeyMessage = '', string $missingMessage = ''): array<string>
```
Iterates data array to check against expected
#### Parameters
`array` $dataFields Fields array, containing the POST data fields
`array` $expectedFields optional Fields array, containing the expected fields we should have in POST
`string` $intKeyMessage optional Message string if unexpected found in data fields indexed by int (not protected)
`string` $stringKeyMessage optional Message string if tampered found in data fields indexed by string (protected).
`string` $missingMessage optional Message string if missing field
#### Returns
`array<string>`
### \_debugExpectedFields() protected
```
_debugExpectedFields(array $expectedFields = [], string $missingMessage = ''): string|null
```
Generate debug message for the expected fields
#### Parameters
`array` $expectedFields optional Expected fields
`string` $missingMessage optional Message template
#### Returns
`string|null`
### \_debugPostTokenNotMatching() protected
```
_debugPostTokenNotMatching(Cake\Controller\Controller $controller, array<string> $hashParts): string
```
Create a message for humans to understand why Security token is not matching
#### Parameters
`Cake\Controller\Controller` $controller Instantiating controller
`array<string>` $hashParts Elements used to generate the Token hash
#### Returns
`string`
### \_fieldsList() protected
```
_fieldsList(array $check): array
```
Return the fields list for the hash calculation
#### Parameters
`array` $check Data array
#### Returns
`array`
### \_hashParts() protected
```
_hashParts(Cake\Controller\Controller $controller): array<string>
```
Return hash parts for the Token generation
#### Parameters
`Cake\Controller\Controller` $controller Instantiating controller
#### Returns
`array<string>`
### \_matchExistingFields() protected
```
_matchExistingFields(array $dataFields, array $expectedFields, string $intKeyMessage, string $stringKeyMessage): array<string>
```
Generate array of messages for the existing fields in POST data, matching dataFields in $expectedFields will be unset
#### Parameters
`array` $dataFields Fields array, containing the POST data fields
`array` $expectedFields Fields array, containing the expected fields we should have in POST
`string` $intKeyMessage Message string if unexpected found in data fields indexed by int (not protected)
`string` $stringKeyMessage Message string if tampered found in data fields indexed by string (protected)
#### Returns
`array<string>`
### \_secureRequired() protected
```
_secureRequired(Cake\Controller\Controller $controller): void
```
Check if access requires secure connection
#### Parameters
`Cake\Controller\Controller` $controller Instantiating controller
#### Returns
`void`
#### Throws
`Cake\Controller\Exception\SecurityException`
### \_sortedUnlocked() protected
```
_sortedUnlocked(array $data): string
```
Get the sorted unlocked string
#### Parameters
`array` $data Data array
#### Returns
`string`
### \_throwException() protected
```
_throwException(Cake\Controller\Exception\SecurityException|null $exception = null): void
```
Check debug status and throw an Exception based on the existing one
#### Parameters
`Cake\Controller\Exception\SecurityException|null` $exception optional Additional debug info describing the cause
#### Returns
`void`
#### Throws
`Cake\Http\Exception\BadRequestException`
### \_unlocked() protected
```
_unlocked(array $data): string
```
Get the unlocked string
#### Parameters
`array` $data Data array
#### Returns
`string`
### \_validToken() protected
```
_validToken(Cake\Controller\Controller $controller): string
```
Check if token is valid
#### Parameters
`Cake\Controller\Controller` $controller Instantiating controller
#### Returns
`string`
#### Throws
`Cake\Controller\Exception\SecurityException`
### \_validatePost() protected
```
_validatePost(Cake\Controller\Controller $controller): void
```
Validate submitted form
#### Parameters
`Cake\Controller\Controller` $controller Instantiating controller
#### Returns
`void`
#### Throws
`Cake\Controller\Exception\AuthSecurityException`
### blackHole() public
```
blackHole(Cake\Controller\Controller $controller, string $error = '', Cake\Controller\Exception\SecurityException|null $exception = null): mixed
```
Black-hole an invalid request with a 400 error or custom callback. If SecurityComponent::$blackHoleCallback is specified, it will use this callback by executing the method indicated in $error
#### Parameters
`Cake\Controller\Controller` $controller Instantiating controller
`string` $error optional Error method
`Cake\Controller\Exception\SecurityException|null` $exception optional Additional debug info describing the cause
#### Returns
`mixed`
#### Throws
`Cake\Http\Exception\BadRequestException`
#### See Also
\Cake\Controller\Component\SecurityComponent::$blackHoleCallback #### Links
https://book.cakephp.org/4/en/controllers/components/security.html#handling-blackhole-callbacks
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
```
$this->configShallow('key', $value);
```
Setting a nested value:
```
$this->configShallow('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->configShallow(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### generateToken() public
```
generateToken(Cake\Http\ServerRequest $request): Cake\Http\ServerRequest
```
Manually add form tampering prevention token information into the provided request object.
#### Parameters
`Cake\Http\ServerRequest` $request The request object to add into.
#### Returns
`Cake\Http\ServerRequest`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### Usage
Reading the whole config:
```
$this->getConfig();
```
Reading a specific value:
```
$this->getConfig('key');
```
Reading a nested value:
```
$this->getConfig('some.nested.key');
```
Reading with default value:
```
$this->getConfig('some-key', 'default-value');
```
#### Parameters
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getController() public
```
getController(): Cake\Controller\Controller
```
Get the controller this component is bound to.
#### Returns
`Cake\Controller\Controller`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Events supported by this component.
Uses Conventions to map controller events to standard component callback method names. By defining one of the callback methods a component is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want components to listen to non-standard events.
#### Returns
`array<string, mixed>`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Constructor hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The configuration settings provided to this component.
#### Returns
`void`
### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### requireSecure() public
```
requireSecure(array<string>|string|null $actions = null): void
```
Sets the actions that require a request that is SSL-secured, or empty for all actions
#### Parameters
`array<string>|string|null` $actions optional Actions list
#### Returns
`void`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### Usage
Setting a specific value:
```
$this->setConfig('key', $value);
```
Setting a nested value:
```
$this->setConfig('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->setConfig(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### startup() public
```
startup(Cake\Event\EventInterface $event): Cake\Http\Response|null
```
Component startup. All security checking happens here.
#### Parameters
`Cake\Event\EventInterface` $event An Event instance
#### Returns
`Cake\Http\Response|null`
Property Detail
---------------
### $\_action protected
Holds the current action of the controller
#### Type
`string`
### $\_componentMap protected
A component lookup table used to lazy load component objects.
#### Type
`array<string, array>`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config
* `blackHoleCallback` - The controller method that will be called if this request is black-hole'd.
* `requireSecure` - List of actions that require an SSL-secured connection.
* `unlockedFields` - Form fields to exclude from POST validation. Fields can be unlocked either in the Component, or with FormHelper::unlockField(). Fields that have been unlocked are not required to be part of the POST and hidden unlocked fields do not have their values checked.
* `unlockedActions` - Actions to exclude from POST validation checks. Other checks like requireSecure() etc. will still be applied.
* `validatePost` - Whether to validate POST data. Set to false to disable for data coming from 3rd party services, etc.
#### Type
`array<string, mixed>`
### $\_registry protected
Component registry class used to lazy load components.
#### Type
`Cake\Controller\ComponentRegistry`
### $components protected
Other Components this component uses.
#### Type
`array`
| programming_docs |
cakephp Interface I18nDateTimeInterface Interface I18nDateTimeInterface
================================
Interface for date formatting methods shared by both Time & Date.
**Namespace:** [Cake\I18n](namespace-cake.i18n)
Constants
---------
* `int` **DAYS\_PER\_WEEK**
```
7
```
* `string` **DEFAULT\_TO\_STRING\_FORMAT**
```
'Y-m-d H:i:s'
```
Default format to use for \_\_toString method when type juggling occurs.
* `int` **FRIDAY**
```
5
```
* `int` **HOURS\_PER\_DAY**
```
24
```
* `int` **MINUTES\_PER\_HOUR**
```
60
```
* `int` **MONDAY**
```
1
```
* `int` **MONTHS\_PER\_QUARTER**
```
3
```
* `int` **MONTHS\_PER\_YEAR**
```
12
```
* `int` **SATURDAY**
```
6
```
* `int` **SECONDS\_PER\_MINUTE**
```
60
```
* `int` **SUNDAY**
```
7
```
* `int` **THURSDAY**
```
4
```
* `int` **TUESDAY**
```
2
```
* `int` **WEDNESDAY**
```
3
```
* `int` **WEEKS\_PER\_YEAR**
```
52
```
* `int` **YEARS\_PER\_CENTURY**
```
100
```
* `int` **YEARS\_PER\_DECADE**
```
10
```
Method Summary
--------------
* ##### [addDay()](#addDay()) public
Add a day to the instance
* ##### [addDays()](#addDays()) public
Add days to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addHour()](#addHour()) public
Add an hour to the instance
* ##### [addHours()](#addHours()) public
Add hours to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addMinute()](#addMinute()) public
Add a minute to the instance
* ##### [addMinutes()](#addMinutes()) public
Add minutes to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addMonth()](#addMonth()) public
Add a month to the instance.
* ##### [addMonthWithOverflow()](#addMonthWithOverflow()) public
Add a month with overflow to the instance.
* ##### [addMonths()](#addMonths()) public
Add months to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addMonthsWithOverflow()](#addMonthsWithOverflow()) public
Add months with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addSecond()](#addSecond()) public
Add a second to the instance
* ##### [addSeconds()](#addSeconds()) public
Add seconds to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addWeek()](#addWeek()) public
Add a week to the instance
* ##### [addWeekday()](#addWeekday()) public
Add a weekday to the instance
* ##### [addWeekdays()](#addWeekdays()) public
Add weekdays to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addWeeks()](#addWeeks()) public
Add weeks to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addYear()](#addYear()) public
Add a year to the instance
* ##### [addYearWithOverflow()](#addYearWithOverflow()) public
Add a year with overflow to the instance
* ##### [addYears()](#addYears()) public
Add years to the instance. Positive $value travel forward while negative $value travel into the past.
* ##### [addYearsWithOverflow()](#addYearsWithOverflow()) public
Add years with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [average()](#average()) public
Modify the current instance to the average of a given instance (default now) and the current instance.
* ##### [between()](#between()) public
Determines if the instance is between two others
* ##### [closest()](#closest()) public
Get the closest date from the instance.
* ##### [copy()](#copy()) public
Get a copy of the instance
* ##### [day()](#day()) public
Set the instance's day
* ##### [diffFiltered()](#diffFiltered()) public
Get the difference by the given interval using a filter callable
* ##### [diffForHumans()](#diffForHumans()) public
Get the difference in a human readable format in the current locale.
* ##### [diffInDays()](#diffInDays()) public
Get the difference in days
* ##### [diffInDaysFiltered()](#diffInDaysFiltered()) public
Get the difference in days using a filter callable
* ##### [diffInHours()](#diffInHours()) public
Get the difference in hours
* ##### [diffInHoursFiltered()](#diffInHoursFiltered()) public
Get the difference in hours using a filter callable
* ##### [diffInMinutes()](#diffInMinutes()) public
Get the difference in minutes
* ##### [diffInMonths()](#diffInMonths()) public
Get the difference in months
* ##### [diffInSeconds()](#diffInSeconds()) public
Get the difference in seconds
* ##### [diffInWeekdays()](#diffInWeekdays()) public
Get the difference in weekdays
* ##### [diffInWeekendDays()](#diffInWeekendDays()) public
Get the difference in weekend days using a filter
* ##### [diffInWeeks()](#diffInWeeks()) public
Get the difference in weeks
* ##### [diffInYears()](#diffInYears()) public
Get the difference in years
* ##### [endOfCentury()](#endOfCentury()) public
Resets the date to end of the century and time to 23:59:59
* ##### [endOfDay()](#endOfDay()) public
Resets the time to 23:59:59
* ##### [endOfDecade()](#endOfDecade()) public
Resets the date to end of the decade and time to 23:59:59
* ##### [endOfMonth()](#endOfMonth()) public
Resets the date to end of the month and time to 23:59:59
* ##### [endOfWeek()](#endOfWeek()) public
Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59
* ##### [endOfYear()](#endOfYear()) public
Resets the date to end of the year and time to 23:59:59
* ##### [eq()](#eq()) public
Determines if the instance is equal to another
* ##### [equals()](#equals()) public
Determines if the instance is equal to another
* ##### [farthest()](#farthest()) public
Get the farthest date from the instance.
* ##### [firstOfMonth()](#firstOfMonth()) public
Modify to the first occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the first day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [firstOfQuarter()](#firstOfQuarter()) public
Modify to the first occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the first day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [firstOfYear()](#firstOfYear()) public
Modify to the first occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the first day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [getDefaultLocale()](#getDefaultLocale()) public static
Gets the default locale.
* ##### [getDiffFormatter()](#getDiffFormatter()) public static
Get the difference formatter instance.
* ##### [greaterThan()](#greaterThan()) public
Determines if the instance is greater (after) than another
* ##### [greaterThanOrEquals()](#greaterThanOrEquals()) public
Determines if the instance is greater (after) than or equal to another
* ##### [gt()](#gt()) public
Determines if the instance is greater (after) than another
* ##### [gte()](#gte()) public
Determines if the instance is greater (after) than or equal to another
* ##### [hour()](#hour()) public
Set the instance's hour
* ##### [i18nFormat()](#i18nFormat()) public
Returns a formatted string for this time object using the preferred format and language for the specified locale.
* ##### [isBirthday()](#isBirthday()) public
Check if its the birthday. Compares the date/month values of the two dates.
* ##### [isFriday()](#isFriday()) public
Checks if this day is a Friday.
* ##### [isFuture()](#isFuture()) public
Determines if the instance is in the future, ie. greater (after) than now
* ##### [isLeapYear()](#isLeapYear()) public
Determines if the instance is a leap year
* ##### [isMonday()](#isMonday()) public
Checks if this day is a Monday.
* ##### [isMutable()](#isMutable()) public
Check if instance of ChronosInterface is mutable.
* ##### [isPast()](#isPast()) public
Determines if the instance is in the past, ie. less (before) than now
* ##### [isSameDay()](#isSameDay()) public
Checks if the passed in date is the same day as the instance current day.
* ##### [isSaturday()](#isSaturday()) public
Checks if this day is a Saturday.
* ##### [isSunday()](#isSunday()) public
Checks if this day is a Sunday.
* ##### [isThisMonth()](#isThisMonth()) public
Returns true if this object represents a date within the current month
* ##### [isThisWeek()](#isThisWeek()) public
Returns true if this object represents a date within the current week
* ##### [isThisYear()](#isThisYear()) public
Returns true if this object represents a date within the current year
* ##### [isThursday()](#isThursday()) public
Checks if this day is a Thursday.
* ##### [isToday()](#isToday()) public
Determines if the instance is today
* ##### [isTomorrow()](#isTomorrow()) public
Determines if the instance is tomorrow
* ##### [isTuesday()](#isTuesday()) public
Checks if this day is a Tuesday.
* ##### [isWednesday()](#isWednesday()) public
Checks if this day is a Wednesday.
* ##### [isWeekday()](#isWeekday()) public
Determines if the instance is a weekday
* ##### [isWeekend()](#isWeekend()) public
Determines if the instance is a weekend day
* ##### [isWithinNext()](#isWithinNext()) public
Returns true this instance will happen within the specified interval
* ##### [isYesterday()](#isYesterday()) public
Determines if the instance is yesterday
* ##### [lastOfMonth()](#lastOfMonth()) public
Modify to the last occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the last day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [lastOfQuarter()](#lastOfQuarter()) public
Modify to the last occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the last day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [lastOfYear()](#lastOfYear()) public
Modify to the last occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the last day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [lessThan()](#lessThan()) public
Determines if the instance is less (before) than another
* ##### [lessThanOrEquals()](#lessThanOrEquals()) public
Determines if the instance is less (before) or equal to another
* ##### [lt()](#lt()) public
Determines if the instance is less (before) than another
* ##### [lte()](#lte()) public
Determines if the instance is less (before) or equal to another
* ##### [max()](#max()) public
Get the maximum instance between a given instance (default now) and the current instance.
* ##### [min()](#min()) public
Get the minimum instance between a given instance (default now) and the current instance.
* ##### [minute()](#minute()) public
Set the instance's minute
* ##### [modify()](#modify()) public @method
* ##### [month()](#month()) public
Set the instance's month
* ##### [ne()](#ne()) public
Determines if the instance is not equal to another
* ##### [next()](#next()) public
Modify to the next occurrence of a given day of the week. If no dayOfWeek is provided, modify to the next occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [nice()](#nice()) public
Returns a nicely formatted date string for this object.
* ##### [notEquals()](#notEquals()) public
Determines if the instance is not equal to another
* ##### [now()](#now()) public static
Get a ChronosInterface instance for the current date and time
* ##### [nthOfMonth()](#nthOfMonth()) public
Modify to the given occurrence of a given day of the week in the current month. If the calculated occurrence is outside the scope of the current month, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [nthOfQuarter()](#nthOfQuarter()) public
Modify to the given occurrence of a given day of the week in the current quarter. If the calculated occurrence is outside the scope of the current quarter, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [nthOfYear()](#nthOfYear()) public
Modify to the given occurrence of a given day of the week in the current year. If the calculated occurrence is outside the scope of the current year, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [parseDate()](#parseDate()) public static
Returns a new Time object after parsing the provided $date string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
* ##### [parseDateTime()](#parseDateTime()) public static
Returns a new Time object after parsing the provided time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
* ##### [parseTime()](#parseTime()) public static
Returns a new Time object after parsing the provided $time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
* ##### [previous()](#previous()) public
Modify to the previous occurrence of a given day of the week. If no dayOfWeek is provided, modify to the previous occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [resetToStringFormat()](#resetToStringFormat()) public static
Resets the format used to the default when converting an instance of this type to a string
* ##### [second()](#second()) public
Set the instance's second
* ##### [secondsSinceMidnight()](#secondsSinceMidnight()) public
The number of seconds since midnight.
* ##### [secondsUntilEndOfDay()](#secondsUntilEndOfDay()) public
The number of seconds until 23:59:59.
* ##### [setDateTime()](#setDateTime()) public
Set the date and time all together
* ##### [setDefaultLocale()](#setDefaultLocale()) public static
Sets the default locale.
* ##### [setDiffFormatter()](#setDiffFormatter()) public static
Set the difference formatter instance.
* ##### [setJsonEncodeFormat()](#setJsonEncodeFormat()) public static
Sets the default format used when converting this object to JSON
* ##### [setTimeFromTimeString()](#setTimeFromTimeString()) public
Set the time by time string
* ##### [setTimezone()](#setTimezone()) public
Set the instance's timezone from a string or object
* ##### [setToStringFormat()](#setToStringFormat()) public static
Sets the default format used when type converting instances of this type to string
* ##### [startOfCentury()](#startOfCentury()) public
Resets the date to the first day of the century and the time to 00:00:00
* ##### [startOfDay()](#startOfDay()) public
Resets the time to 00:00:00
* ##### [startOfDecade()](#startOfDecade()) public
Resets the date to the first day of the decade and the time to 00:00:00
* ##### [startOfMonth()](#startOfMonth()) public
Resets the date to the first day of the month and the time to 00:00:00
* ##### [startOfWeek()](#startOfWeek()) public
Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00
* ##### [startOfYear()](#startOfYear()) public
Resets the date to the first day of the year and the time to 00:00:00
* ##### [subDay()](#subDay()) public
Remove a day from the instance
* ##### [subDays()](#subDays()) public
Remove days from the instance
* ##### [subHour()](#subHour()) public
Remove an hour from the instance
* ##### [subHours()](#subHours()) public
Remove hours from the instance
* ##### [subMinute()](#subMinute()) public
Remove a minute from the instance
* ##### [subMinutes()](#subMinutes()) public
Remove minutes from the instance
* ##### [subMonth()](#subMonth()) public
Remove a month from the instance
* ##### [subMonthWithOverflow()](#subMonthWithOverflow()) public
Remove a month with overflow from the instance.
* ##### [subMonths()](#subMonths()) public
Remove months from the instance.
* ##### [subMonthsWithOverflow()](#subMonthsWithOverflow()) public
Remove months with overflow from the instance.
* ##### [subSecond()](#subSecond()) public
Remove a second from the instance
* ##### [subSeconds()](#subSeconds()) public
Remove seconds from the instance
* ##### [subWeek()](#subWeek()) public
Remove a week from the instance
* ##### [subWeekday()](#subWeekday()) public
Remove a weekday from the instance
* ##### [subWeekdays()](#subWeekdays()) public
Remove weekdays from the instance
* ##### [subWeeks()](#subWeeks()) public
Remove weeks to the instance
* ##### [subYear()](#subYear()) public
Remove a year from the instance.
* ##### [subYearWithOverflow()](#subYearWithOverflow()) public
Remove a year with overflow from the instance
* ##### [subYears()](#subYears()) public
Remove years from the instance.
* ##### [subYearsWithOverflow()](#subYearsWithOverflow()) public
Remove years with overflow from the instance
* ##### [timestamp()](#timestamp()) public
Set the instance's timestamp
* ##### [timezone()](#timezone()) public
Alias for setTimezone()
* ##### [toAtomString()](#toAtomString()) public
Format the instance as ATOM
* ##### [toCookieString()](#toCookieString()) public
Format the instance as COOKIE
* ##### [toDateString()](#toDateString()) public
Format the instance as date
* ##### [toDateTimeString()](#toDateTimeString()) public
Format the instance as date and time
* ##### [toDayDateTimeString()](#toDayDateTimeString()) public
Format the instance with day, date and time
* ##### [toFormattedDateString()](#toFormattedDateString()) public
Format the instance as a readable date
* ##### [toIso8601String()](#toIso8601String()) public
Format the instance as ISO8601
* ##### [toRfc1036String()](#toRfc1036String()) public
Format the instance as RFC1036
* ##### [toRfc1123String()](#toRfc1123String()) public
Format the instance as RFC1123
* ##### [toRfc2822String()](#toRfc2822String()) public
Format the instance as RFC2822
* ##### [toRfc3339String()](#toRfc3339String()) public
Format the instance as RFC3339
* ##### [toRfc822String()](#toRfc822String()) public
Format the instance as RFC822
* ##### [toRfc850String()](#toRfc850String()) public
Format the instance as RFC850
* ##### [toRssString()](#toRssString()) public
Format the instance as RSS
* ##### [toTimeString()](#toTimeString()) public
Format the instance as time
* ##### [toW3cString()](#toW3cString()) public
Format the instance as W3C
* ##### [tz()](#tz()) public
Alias for setTimezone()
* ##### [wasWithinLast()](#wasWithinLast()) public
Returns true this instance happened within the specified interval
* ##### [year()](#year()) public
Set the instance's year
Method Detail
-------------
### addDay() public
```
addDay(int $value = 1): static
```
Add a day to the instance
#### Parameters
`int` $value optional The number of days to add.
#### Returns
`static`
### addDays() public
```
addDays(int $value): static
```
Add days to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of days to add.
#### Returns
`static`
### addHour() public
```
addHour(int $value = 1): static
```
Add an hour to the instance
#### Parameters
`int` $value optional The number of hours to add.
#### Returns
`static`
### addHours() public
```
addHours(int $value): static
```
Add hours to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of hours to add.
#### Returns
`static`
### addMinute() public
```
addMinute(int $value = 1): static
```
Add a minute to the instance
#### Parameters
`int` $value optional The number of minutes to add.
#### Returns
`static`
### addMinutes() public
```
addMinutes(int $value): static
```
Add minutes to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of minutes to add.
#### Returns
`static`
### addMonth() public
```
addMonth(int $value = 1): static
```
Add a month to the instance.
Has the same behavior as `addMonths()`.
#### Parameters
`int` $value optional The number of months to add.
#### Returns
`static`
### addMonthWithOverflow() public
```
addMonthWithOverflow(int $value = 1): static
```
Add a month with overflow to the instance.
Has the same behavior as `addMonthsWithOverflow()`.
#### Parameters
`int` $value optional The number of months to add.
#### Returns
`static`
### addMonths() public
```
addMonths(int $value): static
```
Add months to the instance. Positive $value travels forward while negative $value travels into the past.
If the new date does not exist, the last day of the month is used instead instead of overflowing into the next month.
### Example:
```
(new Chronos('2015-01-03'))->addMonths(1); // Results in 2015-02-03
(new Chronos('2015-01-31'))->addMonths(1); // Results in 2015-02-28
```
#### Parameters
`int` $value The number of months to add.
#### Returns
`static`
### addMonthsWithOverflow() public
```
addMonthsWithOverflow(int $value): static
```
Add months with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
If the new date does not exist, the days overflow into the next month.
### Example:
```
(new Chronos('2012-01-30'))->addMonthsWithOverflow(1); // Results in 2013-03-01
```
#### Parameters
`int` $value The number of months to add.
#### Returns
`static`
### addSecond() public
```
addSecond(int $value = 1): static
```
Add a second to the instance
#### Parameters
`int` $value optional The number of seconds to add.
#### Returns
`static`
### addSeconds() public
```
addSeconds(int $value): static
```
Add seconds to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of seconds to add.
#### Returns
`static`
### addWeek() public
```
addWeek(int $value = 1): static
```
Add a week to the instance
#### Parameters
`int` $value optional The number of weeks to add.
#### Returns
`static`
### addWeekday() public
```
addWeekday(int $value = 1): static
```
Add a weekday to the instance
#### Parameters
`int` $value optional The number of weekdays to add.
#### Returns
`static`
### addWeekdays() public
```
addWeekdays(int $value): static
```
Add weekdays to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of weekdays to add.
#### Returns
`static`
### addWeeks() public
```
addWeeks(int $value): static
```
Add weeks to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of weeks to add.
#### Returns
`static`
### addYear() public
```
addYear(int $value = 1): static
```
Add a year to the instance
Has the same behavior as `addYears()`.
#### Parameters
`int` $value optional The number of years to add.
#### Returns
`static`
### addYearWithOverflow() public
```
addYearWithOverflow(int $value = 1): static
```
Add a year with overflow to the instance
Has the same behavior as `addYearsWithOverflow()`.
#### Parameters
`int` $value optional The number of years to add.
#### Returns
`static`
### addYears() public
```
addYears(int $value): static
```
Add years to the instance. Positive $value travel forward while negative $value travel into the past.
If the new date does not exist, the last day of the month is used instead instead of overflowing into the next month.
### Example:
```
(new Chronos('2015-01-03'))->addYears(1); // Results in 2016-01-03
(new Chronos('2012-02-29'))->addYears(1); // Results in 2013-02-28
```
#### Parameters
`int` $value The number of years to add.
#### Returns
`static`
### addYearsWithOverflow() public
```
addYearsWithOverflow(int $value): static
```
Add years with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
If the new date does not exist, the days overflow into the next month.
### Example:
```
(new Chronos('2012-02-29'))->addYearsWithOverflow(1); // Results in 2013-03-01
```
#### Parameters
`int` $value The number of years to add.
#### Returns
`static`
### average() public
```
average(Cake\Chronos\ChronosInterface $dt = null): static
```
Modify the current instance to the average of a given instance (default now) and the current instance.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt optional The instance to compare with.
#### Returns
`static`
### between() public
```
between(Cake\Chronos\ChronosInterface $dt1, Cake\Chronos\ChronosInterface $dt2, bool $equal = true): bool
```
Determines if the instance is between two others
#### Parameters
`Cake\Chronos\ChronosInterface` $dt1 The instance to compare with.
`Cake\Chronos\ChronosInterface` $dt2 The instance to compare with.
`bool` $equal optional Indicates if a > and < comparison should be used or <= or >=
#### Returns
`bool`
### closest() public
```
closest(Cake\Chronos\ChronosInterface $dt1, Cake\Chronos\ChronosInterface $dt2): static
```
Get the closest date from the instance.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt1 The instance to compare with.
`Cake\Chronos\ChronosInterface` $dt2 The instance to compare with.
#### Returns
`static`
### copy() public
```
copy(): static
```
Get a copy of the instance
#### Returns
`static`
### day() public
```
day(int $value): static
```
Set the instance's day
#### Parameters
`int` $value The day value.
#### Returns
`static`
### diffFiltered() public
```
diffFiltered(Cake\Chronos\ChronosInterval $ci, callable $callback, Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference by the given interval using a filter callable
#### Parameters
`Cake\Chronos\ChronosInterval` $ci An interval to traverse by
`callable` $callback The callback to use for filtering.
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffForHumans() public
```
diffForHumans(Cake\Chronos\ChronosInterface|null $other = null, bool $absolute = false): string
```
Get the difference in a human readable format in the current locale.
When comparing a value in the past to default now: 1 hour ago 5 months ago
When comparing a value in the future to default now: 1 hour from now 5 months from now
When comparing a value in the past to another value: 1 hour before 5 months before
When comparing a value in the future to another value: 1 hour after 5 months after
#### Parameters
`Cake\Chronos\ChronosInterface|null` $other optional The datetime to compare with.
`bool` $absolute optional Removes time difference modifiers ago, after, etc
#### Returns
`string`
### diffInDays() public
```
diffInDays(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in days
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInDaysFiltered() public
```
diffInDaysFiltered(callable $callback, Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in days using a filter callable
#### Parameters
`callable` $callback The callback to use for filtering.
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInHours() public
```
diffInHours(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in hours
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInHoursFiltered() public
```
diffInHoursFiltered(callable $callback, Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in hours using a filter callable
#### Parameters
`callable` $callback The callback to use for filtering.
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInMinutes() public
```
diffInMinutes(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in minutes
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInMonths() public
```
diffInMonths(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in months
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInSeconds() public
```
diffInSeconds(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in seconds
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInWeekdays() public
```
diffInWeekdays(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in weekdays
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInWeekendDays() public
```
diffInWeekendDays(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in weekend days using a filter
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInWeeks() public
```
diffInWeeks(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in weeks
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInYears() public
```
diffInYears(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in years
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### endOfCentury() public
```
endOfCentury(): static
```
Resets the date to end of the century and time to 23:59:59
#### Returns
`static`
### endOfDay() public
```
endOfDay(): static
```
Resets the time to 23:59:59
#### Returns
`static`
### endOfDecade() public
```
endOfDecade(): static
```
Resets the date to end of the decade and time to 23:59:59
#### Returns
`static`
### endOfMonth() public
```
endOfMonth(): static
```
Resets the date to end of the month and time to 23:59:59
#### Returns
`static`
### endOfWeek() public
```
endOfWeek(): static
```
Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59
#### Returns
`static`
### endOfYear() public
```
endOfYear(): static
```
Resets the date to end of the year and time to 23:59:59
#### Returns
`static`
### eq() public
```
eq(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
equals ### equals() public
```
equals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### farthest() public
```
farthest(Cake\Chronos\ChronosInterface $dt1, Cake\Chronos\ChronosInterface $dt2): static
```
Get the farthest date from the instance.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt1 The instance to compare with.
`Cake\Chronos\ChronosInterface` $dt2 The instance to compare with.
#### Returns
`static`
### firstOfMonth() public
```
firstOfMonth(int|null $dayOfWeek = null): mixed
```
Modify to the first occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the first day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### firstOfQuarter() public
```
firstOfQuarter(int|null $dayOfWeek = null): mixed
```
Modify to the first occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the first day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### firstOfYear() public
```
firstOfYear(int|null $dayOfWeek = null): mixed
```
Modify to the first occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the first day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### getDefaultLocale() public static
```
getDefaultLocale(): string|null
```
Gets the default locale.
#### Returns
`string|null`
### getDiffFormatter() public static
```
getDiffFormatter(): Cake\Chronos\DifferenceFormatterInterface
```
Get the difference formatter instance.
#### Returns
`Cake\Chronos\DifferenceFormatterInterface`
### greaterThan() public
```
greaterThan(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### greaterThanOrEquals() public
```
greaterThanOrEquals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### gt() public
```
gt(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
greaterThan ### gte() public
```
gte(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
greaterThanOrEquals ### hour() public
```
hour(int $value): static
```
Set the instance's hour
#### Parameters
`int` $value The hour value.
#### Returns
`static`
### i18nFormat() public
```
i18nFormat(string|int|null $format = null, DateTimeZone|string|null $timezone = null, string|null $locale = null): string|int
```
Returns a formatted string for this time object using the preferred format and language for the specified locale.
It is possible to specify the desired format for the string to be displayed. You can either pass `IntlDateFormatter` constants as the first argument of this function, or pass a full ICU date formatting string as specified in the following resource: <https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>.
Additional to `IntlDateFormatter` constants and date formatting string you can use Time::UNIX\_TIMESTAMP\_FORMAT to get a unix timestamp
### Examples
```
$time = new Time('2014-04-20 22:10');
$time->i18nFormat(); // outputs '4/20/14, 10:10 PM' for the en-US locale
$time->i18nFormat(\IntlDateFormatter::FULL); // Use the full date and time format
$time->i18nFormat([\IntlDateFormatter::FULL, \IntlDateFormatter::SHORT]); // Use full date but short time format
$time->i18nFormat('yyyy-MM-dd HH:mm:ss'); // outputs '2014-04-20 22:10'
$time->i18nFormat(Time::UNIX_TIMESTAMP_FORMAT); // outputs '1398031800'
```
If you wish to control the default format to be used for this method, you can alter the value of the static `Time::$defaultLocale` variable and set it to one of the possible formats accepted by this function.
You can read about the available IntlDateFormatter constants at <https://secure.php.net/manual/en/class.intldateformatter.php>
If you need to display the date in a different timezone than the one being used for this Time object without altering its internal state, you can pass a timezone string or object as the second parameter.
Finally, should you need to use a different locale for displaying this time object, pass a locale string as the third parameter to this function.
### Examples
```
$time = new Time('2014-04-20 22:10');
$time->i18nFormat(null, null, 'de-DE');
$time->i18nFormat(\IntlDateFormatter::FULL, 'Europe/Berlin', 'de-DE');
```
You can control the default locale to be used by setting the static variable `Time::$defaultLocale` to a valid locale string. If empty, the default will be taken from the `intl.default_locale` ini config.
#### Parameters
`string|int|null` $format optional Format string.
`DateTimeZone|string|null` $timezone optional Timezone string or DateTimeZone object in which the date will be displayed. The timezone stored for this object will not be changed.
`string|null` $locale optional The locale name in which the date should be displayed (e.g. pt-BR)
#### Returns
`string|int`
### isBirthday() public
```
isBirthday(Cake\Chronos\ChronosInterface $dt): bool
```
Check if its the birthday. Compares the date/month values of the two dates.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### isFriday() public
```
isFriday(): bool
```
Checks if this day is a Friday.
#### Returns
`bool`
### isFuture() public
```
isFuture(): bool
```
Determines if the instance is in the future, ie. greater (after) than now
#### Returns
`bool`
### isLeapYear() public
```
isLeapYear(): bool
```
Determines if the instance is a leap year
#### Returns
`bool`
### isMonday() public
```
isMonday(): bool
```
Checks if this day is a Monday.
#### Returns
`bool`
### isMutable() public
```
isMutable(): bool
```
Check if instance of ChronosInterface is mutable.
#### Returns
`bool`
### isPast() public
```
isPast(): bool
```
Determines if the instance is in the past, ie. less (before) than now
#### Returns
`bool`
### isSameDay() public
```
isSameDay(Cake\Chronos\ChronosInterface $dt): bool
```
Checks if the passed in date is the same day as the instance current day.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to check against.
#### Returns
`bool`
### isSaturday() public
```
isSaturday(): bool
```
Checks if this day is a Saturday.
#### Returns
`bool`
### isSunday() public
```
isSunday(): bool
```
Checks if this day is a Sunday.
#### Returns
`bool`
### isThisMonth() public
```
isThisMonth(): bool
```
Returns true if this object represents a date within the current month
#### Returns
`bool`
### isThisWeek() public
```
isThisWeek(): bool
```
Returns true if this object represents a date within the current week
#### Returns
`bool`
### isThisYear() public
```
isThisYear(): bool
```
Returns true if this object represents a date within the current year
#### Returns
`bool`
### isThursday() public
```
isThursday(): bool
```
Checks if this day is a Thursday.
#### Returns
`bool`
### isToday() public
```
isToday(): bool
```
Determines if the instance is today
#### Returns
`bool`
### isTomorrow() public
```
isTomorrow(): bool
```
Determines if the instance is tomorrow
#### Returns
`bool`
### isTuesday() public
```
isTuesday(): bool
```
Checks if this day is a Tuesday.
#### Returns
`bool`
### isWednesday() public
```
isWednesday(): bool
```
Checks if this day is a Wednesday.
#### Returns
`bool`
### isWeekday() public
```
isWeekday(): bool
```
Determines if the instance is a weekday
#### Returns
`bool`
### isWeekend() public
```
isWeekend(): bool
```
Determines if the instance is a weekend day
#### Returns
`bool`
### isWithinNext() public
```
isWithinNext(string|int $timeInterval): bool
```
Returns true this instance will happen within the specified interval
#### Parameters
`string|int` $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
#### Returns
`bool`
### isYesterday() public
```
isYesterday(): bool
```
Determines if the instance is yesterday
#### Returns
`bool`
### lastOfMonth() public
```
lastOfMonth(int|null $dayOfWeek = null): mixed
```
Modify to the last occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the last day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### lastOfQuarter() public
```
lastOfQuarter(int|null $dayOfWeek = null): mixed
```
Modify to the last occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the last day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### lastOfYear() public
```
lastOfYear(int|null $dayOfWeek = null): mixed
```
Modify to the last occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the last day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### lessThan() public
```
lessThan(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### lessThanOrEquals() public
```
lessThanOrEquals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### lt() public
```
lt(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
lessThan ### lte() public
```
lte(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
lessThanOrEquals ### max() public
```
max(Cake\Chronos\ChronosInterface|null $dt = null): static
```
Get the maximum instance between a given instance (default now) and the current instance.
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to compare with.
#### Returns
`static`
### min() public
```
min(Cake\Chronos\ChronosInterface|null $dt = null): static
```
Get the minimum instance between a given instance (default now) and the current instance.
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to compare with.
#### Returns
`static`
### minute() public
```
minute(int $value): static
```
Set the instance's minute
#### Parameters
`int` $value The minute value.
#### Returns
`static`
### modify() public @method
```
modify(string $relative): Cake\Chronos\ChronosInterface
```
#### Parameters
`string` $relative #### Returns
`Cake\Chronos\ChronosInterface`
### month() public
```
month(int $value): static
```
Set the instance's month
#### Parameters
`int` $value The month value.
#### Returns
`static`
### ne() public
```
ne(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is not equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
notEquals ### next() public
```
next(int|null $dayOfWeek = null): mixed
```
Modify to the next occurrence of a given day of the week. If no dayOfWeek is provided, modify to the next occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### nice() public
```
nice(DateTimeZone|string|null $timezone = null, string|null $locale = null): string
```
Returns a nicely formatted date string for this object.
The format to be used is stored in the static property `Time::niceFormat`.
#### Parameters
`DateTimeZone|string|null` $timezone optional Timezone string or DateTimeZone object in which the date will be displayed. The timezone stored for this object will not be changed.
`string|null` $locale optional The locale name in which the date should be displayed (e.g. pt-BR)
#### Returns
`string`
### notEquals() public
```
notEquals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is not equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### now() public static
```
now(DateTimeZone|string|null $tz): static
```
Get a ChronosInterface instance for the current date and time
#### Parameters
`DateTimeZone|string|null` $tz The DateTimeZone object or timezone name.
#### Returns
`static`
### nthOfMonth() public
```
nthOfMonth(int $nth, int $dayOfWeek): mixed
```
Modify to the given occurrence of a given day of the week in the current month. If the calculated occurrence is outside the scope of the current month, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int` $nth The offset to use.
`int` $dayOfWeek The day of the week to move to.
#### Returns
`mixed`
### nthOfQuarter() public
```
nthOfQuarter(int $nth, int $dayOfWeek): mixed
```
Modify to the given occurrence of a given day of the week in the current quarter. If the calculated occurrence is outside the scope of the current quarter, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int` $nth The offset to use.
`int` $dayOfWeek The day of the week to move to.
#### Returns
`mixed`
### nthOfYear() public
```
nthOfYear(int $nth, int $dayOfWeek): mixed
```
Modify to the given occurrence of a given day of the week in the current year. If the calculated occurrence is outside the scope of the current year, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int` $nth The offset to use.
`int` $dayOfWeek The day of the week to move to.
#### Returns
`mixed`
### parseDate() public static
```
parseDate(string $date, array|string|int|null $format = null): static|null
```
Returns a new Time object after parsing the provided $date string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
When no $format is provided, the `wordFormat` format will be used.
If it was impossible to parse the provided time, null will be returned.
Example:
```
$time = Time::parseDate('10/13/2013');
$time = Time::parseDate('13 Oct, 2013', 'dd MMM, y');
$time = Time::parseDate('13 Oct, 2013', IntlDateFormatter::SHORT);
```
#### Parameters
`string` $date The date string to parse.
`array|string|int|null` $format optional Any format accepted by IntlDateFormatter.
#### Returns
`static|null`
### parseDateTime() public static
```
parseDateTime(string $time, array<int>|string|null $format = null, DateTimeZone|string|null $tz = null): static|null
```
Returns a new Time object after parsing the provided time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
When no $format is provided, the `toString` format will be used.
If it was impossible to parse the provided time, null will be returned.
Example:
```
$time = Time::parseDateTime('10/13/2013 12:54am');
$time = Time::parseDateTime('13 Oct, 2013 13:54', 'dd MMM, y H:mm');
$time = Time::parseDateTime('10/10/2015', [IntlDateFormatter::SHORT, -1]);
```
#### Parameters
`string` $time The time string to parse.
`array<int>|string|null` $format optional Any format accepted by IntlDateFormatter.
`DateTimeZone|string|null` $tz optional The timezone for the instance
#### Returns
`static|null`
#### Throws
`InvalidArgumentException`
If $format is a single int instead of array of constants ### parseTime() public static
```
parseTime(string $time, string|int|null $format = null): static|null
```
Returns a new Time object after parsing the provided $time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
When no $format is provided, the IntlDateFormatter::SHORT format will be used.
If it was impossible to parse the provided time, null will be returned.
Example:
```
$time = Time::parseTime('11:23pm');
```
#### Parameters
`string` $time The time string to parse.
`string|int|null` $format optional Any format accepted by IntlDateFormatter.
#### Returns
`static|null`
### previous() public
```
previous(int|null $dayOfWeek = null): mixed
```
Modify to the previous occurrence of a given day of the week. If no dayOfWeek is provided, modify to the previous occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### resetToStringFormat() public static
```
resetToStringFormat(): void
```
Resets the format used to the default when converting an instance of this type to a string
#### Returns
`void`
### second() public
```
second(int $value): static
```
Set the instance's second
#### Parameters
`int` $value The seconds value.
#### Returns
`static`
### secondsSinceMidnight() public
```
secondsSinceMidnight(): int
```
The number of seconds since midnight.
#### Returns
`int`
### secondsUntilEndOfDay() public
```
secondsUntilEndOfDay(): int
```
The number of seconds until 23:59:59.
#### Returns
`int`
### setDateTime() public
```
setDateTime(int $year, int $month, int $day, int $hour, int $minute, int $second = 0): static
```
Set the date and time all together
#### Parameters
`int` $year The year to set.
`int` $month The month to set.
`int` $day The day to set.
`int` $hour The hour to set.
`int` $minute The minute to set.
`int` $second optional The second to set.
#### Returns
`static`
### setDefaultLocale() public static
```
setDefaultLocale(string|null $locale = null): void
```
Sets the default locale.
#### Parameters
`string|null` $locale optional The default locale string to be used or null.
#### Returns
`void`
### setDiffFormatter() public static
```
setDiffFormatter(Cake\Chronos\DifferenceFormatterInterface $formatter): void
```
Set the difference formatter instance.
#### Parameters
`Cake\Chronos\DifferenceFormatterInterface` $formatter The formatter instance when setting.
#### Returns
`void`
### setJsonEncodeFormat() public static
```
setJsonEncodeFormat(Closure|array|string|int $format): void
```
Sets the default format used when converting this object to JSON
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
Alternatively, the format can provide a callback. In this case, the callback can receive this datetime object and return a formatted string.
#### Parameters
`Closure|array|string|int` $format Format.
#### Returns
`void`
#### See Also
\Cake\I18n\Time::i18nFormat() ### setTimeFromTimeString() public
```
setTimeFromTimeString(string $time): static
```
Set the time by time string
#### Parameters
`string` $time Time as string.
#### Returns
`static`
### setTimezone() public
```
setTimezone(DateTimeZone|string $value): static
```
Set the instance's timezone from a string or object
#### Parameters
`DateTimeZone|string` $value The DateTimeZone object or timezone name to use.
#### Returns
`static`
### setToStringFormat() public static
```
setToStringFormat(array<int>|string|int $format): void
```
Sets the default format used when type converting instances of this type to string
#### Parameters
`array<int>|string|int` $format Format.
#### Returns
`void`
### startOfCentury() public
```
startOfCentury(): static
```
Resets the date to the first day of the century and the time to 00:00:00
#### Returns
`static`
### startOfDay() public
```
startOfDay(): static
```
Resets the time to 00:00:00
#### Returns
`static`
### startOfDecade() public
```
startOfDecade(): static
```
Resets the date to the first day of the decade and the time to 00:00:00
#### Returns
`static`
### startOfMonth() public
```
startOfMonth(): static
```
Resets the date to the first day of the month and the time to 00:00:00
#### Returns
`static`
### startOfWeek() public
```
startOfWeek(): static
```
Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00
#### Returns
`static`
### startOfYear() public
```
startOfYear(): static
```
Resets the date to the first day of the year and the time to 00:00:00
#### Returns
`static`
### subDay() public
```
subDay(int $value = 1): static
```
Remove a day from the instance
#### Parameters
`int` $value optional The number of days to remove.
#### Returns
`static`
### subDays() public
```
subDays(int $value): static
```
Remove days from the instance
#### Parameters
`int` $value The number of days to remove.
#### Returns
`static`
### subHour() public
```
subHour(int $value = 1): static
```
Remove an hour from the instance
#### Parameters
`int` $value optional The number of hours to remove.
#### Returns
`static`
### subHours() public
```
subHours(int $value): static
```
Remove hours from the instance
#### Parameters
`int` $value The number of hours to remove.
#### Returns
`static`
### subMinute() public
```
subMinute(int $value = 1): static
```
Remove a minute from the instance
#### Parameters
`int` $value optional The number of minutes to remove.
#### Returns
`static`
### subMinutes() public
```
subMinutes(int $value): static
```
Remove minutes from the instance
#### Parameters
`int` $value The number of minutes to remove.
#### Returns
`static`
### subMonth() public
```
subMonth(int $value = 1): static
```
Remove a month from the instance
Has the same behavior as `addMonths()`.
#### Parameters
`int` $value optional The number of months to remove.
#### Returns
`static`
### subMonthWithOverflow() public
```
subMonthWithOverflow(int $value = 1): static
```
Remove a month with overflow from the instance.
Has the same behavior as `addMonthsWithOverflow()`.
#### Parameters
`int` $value optional The number of months to remove.
#### Returns
`static`
### subMonths() public
```
subMonths(int $value): static
```
Remove months from the instance.
Has the same behavior as `addMonths()`.
#### Parameters
`int` $value The number of months to remove.
#### Returns
`static`
### subMonthsWithOverflow() public
```
subMonthsWithOverflow(int $value): static
```
Remove months with overflow from the instance.
Has the same behavior as `addMonthsWithOverflow()`.
#### Parameters
`int` $value The number of months to remove.
#### Returns
`static`
### subSecond() public
```
subSecond(int $value = 1): static
```
Remove a second from the instance
#### Parameters
`int` $value optional The number of seconds to remove.
#### Returns
`static`
### subSeconds() public
```
subSeconds(int $value): static
```
Remove seconds from the instance
#### Parameters
`int` $value The number of seconds to remove.
#### Returns
`static`
### subWeek() public
```
subWeek(int $value = 1): static
```
Remove a week from the instance
#### Parameters
`int` $value optional The number of weeks to remove.
#### Returns
`static`
### subWeekday() public
```
subWeekday(int $value = 1): static
```
Remove a weekday from the instance
#### Parameters
`int` $value optional The number of weekdays to remove.
#### Returns
`static`
### subWeekdays() public
```
subWeekdays(int $value): static
```
Remove weekdays from the instance
#### Parameters
`int` $value The number of weekdays to remove.
#### Returns
`static`
### subWeeks() public
```
subWeeks(int $value): static
```
Remove weeks to the instance
#### Parameters
`int` $value The number of weeks to remove.
#### Returns
`static`
### subYear() public
```
subYear(int $value = 1): static
```
Remove a year from the instance.
Has the same behavior as `addYears()`.
#### Parameters
`int` $value optional The number of years to remove.
#### Returns
`static`
### subYearWithOverflow() public
```
subYearWithOverflow(int $value = 1): static
```
Remove a year with overflow from the instance
Has the same behavior as `addYearsWithOverflow()`.
#### Parameters
`int` $value optional The number of years to remove.
#### Returns
`static`
### subYears() public
```
subYears(int $value): static
```
Remove years from the instance.
Has the same behavior as `addYears()`.
#### Parameters
`int` $value The number of years to remove.
#### Returns
`static`
### subYearsWithOverflow() public
```
subYearsWithOverflow(int $value): static
```
Remove years with overflow from the instance
Has the same behavior as `addYearsWithOverflow()`.
#### Parameters
`int` $value The number of years to remove.
#### Returns
`static`
### timestamp() public
```
timestamp(int $value): static
```
Set the instance's timestamp
#### Parameters
`int` $value The timestamp value to set.
#### Returns
`static`
### timezone() public
```
timezone(DateTimeZone|string $value): static
```
Alias for setTimezone()
#### Parameters
`DateTimeZone|string` $value The DateTimeZone object or timezone name to use.
#### Returns
`static`
### toAtomString() public
```
toAtomString(): string
```
Format the instance as ATOM
#### Returns
`string`
### toCookieString() public
```
toCookieString(): string
```
Format the instance as COOKIE
#### Returns
`string`
### toDateString() public
```
toDateString(): string
```
Format the instance as date
#### Returns
`string`
### toDateTimeString() public
```
toDateTimeString(): string
```
Format the instance as date and time
#### Returns
`string`
### toDayDateTimeString() public
```
toDayDateTimeString(): string
```
Format the instance with day, date and time
#### Returns
`string`
### toFormattedDateString() public
```
toFormattedDateString(): string
```
Format the instance as a readable date
#### Returns
`string`
### toIso8601String() public
```
toIso8601String(): string
```
Format the instance as ISO8601
#### Returns
`string`
### toRfc1036String() public
```
toRfc1036String(): string
```
Format the instance as RFC1036
#### Returns
`string`
### toRfc1123String() public
```
toRfc1123String(): string
```
Format the instance as RFC1123
#### Returns
`string`
### toRfc2822String() public
```
toRfc2822String(): string
```
Format the instance as RFC2822
#### Returns
`string`
### toRfc3339String() public
```
toRfc3339String(): string
```
Format the instance as RFC3339
#### Returns
`string`
### toRfc822String() public
```
toRfc822String(): string
```
Format the instance as RFC822
#### Returns
`string`
### toRfc850String() public
```
toRfc850String(): string
```
Format the instance as RFC850
#### Returns
`string`
### toRssString() public
```
toRssString(): string
```
Format the instance as RSS
#### Returns
`string`
### toTimeString() public
```
toTimeString(): string
```
Format the instance as time
#### Returns
`string`
### toW3cString() public
```
toW3cString(): string
```
Format the instance as W3C
#### Returns
`string`
### tz() public
```
tz(DateTimeZone|string $value): static
```
Alias for setTimezone()
#### Parameters
`DateTimeZone|string` $value The DateTimeZone object or timezone name to use.
#### Returns
`static`
### wasWithinLast() public
```
wasWithinLast(string|int $timeInterval): bool
```
Returns true this instance happened within the specified interval
#### Parameters
`string|int` $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
#### Returns
`bool`
### year() public
```
year(int $value): static
```
Set the instance's year
#### Parameters
`int` $value The year value.
#### Returns
`static`
| programming_docs |
cakephp Interface EventListenerInterface Interface EventListenerInterface
=================================
Objects implementing this interface should declare the `implementedEvents()` method to notify the event manager what methods should be called when an event is triggered.
**Namespace:** [Cake\Event](namespace-cake.event)
Method Summary
--------------
* ##### [implementedEvents()](#implementedEvents()) public
Returns a list of events this object is implementing. When the class is registered in an event manager, each individual method will be associated with the respective event.
Method Detail
-------------
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Returns a list of events this object is implementing. When the class is registered in an event manager, each individual method will be associated with the respective event.
### Example:
```
public function implementedEvents()
{
return [
'Order.complete' => 'sendEmail',
'Article.afterBuy' => 'decrementInventory',
'User.onRegister' => ['callable' => 'logRegistration', 'priority' => 20, 'passParams' => true]
];
}
```
#### Returns
`array<string, mixed>`
cakephp Class BadRequestException Class BadRequestException
==========================
Represents an HTTP 400 error.
**Namespace:** [Cake\Http\Exception](namespace-cake.http.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$headers](#%24headers) protected `array<string, mixed>`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getHeaders()](#getHeaders()) public
Returns array of response headers.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
* ##### [setHeader()](#setHeader()) public
Set a single HTTP response header.
* ##### [setHeaders()](#setHeaders()) public
Sets HTTP response headers.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $message = null, int|null $code = null, Throwable|null $previous = null)
```
Constructor
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`string|null` $message optional If no message is given 'Bad Request' will be the message
`int|null` $code optional Status code, defaults to 400
`Throwable|null` $previous optional The previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getHeaders() public
```
getHeaders(): array<string, mixed>
```
Returns array of response headers.
#### Returns
`array<string, mixed>`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
### setHeader() public
```
setHeader(string $header, array<string>|string|null $value = null): void
```
Set a single HTTP response header.
#### Parameters
`string` $header Header name
`array<string>|string|null` $value optional Header value
#### Returns
`void`
### setHeaders() public
```
setHeaders(array<string, mixed> $headers): void
```
Sets HTTP response headers.
#### Parameters
`array<string, mixed>` $headers Array of header name and value pairs.
#### Returns
`void`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $headers protected
#### Type
`array<string, mixed>`
cakephp Class Message Class Message
==============
Base class for other HTTP requests/responses
Defines some common helper methods, constants and properties.
**Namespace:** [Cake\Http\Client](namespace-cake.http.client)
Constants
---------
* `string` **METHOD\_DELETE**
```
'DELETE'
```
HTTP DELETE method
* `string` **METHOD\_GET**
```
'GET'
```
HTTP GET method
* `string` **METHOD\_HEAD**
```
'HEAD'
```
HTTP HEAD method
* `string` **METHOD\_OPTIONS**
```
'OPTIONS'
```
HTTP OPTIONS method
* `string` **METHOD\_PATCH**
```
'PATCH'
```
HTTP PATCH method
* `string` **METHOD\_POST**
```
'POST'
```
HTTP POST method
* `string` **METHOD\_PUT**
```
'PUT'
```
HTTP PUT method
* `string` **METHOD\_TRACE**
```
'TRACE'
```
HTTP TRACE method
* `int` **STATUS\_ACCEPTED**
```
202
```
HTTP 202 code
* `int` **STATUS\_CREATED**
```
201
```
HTTP 201 code
* `int` **STATUS\_FOUND**
```
302
```
HTTP 302 code
* `int` **STATUS\_MOVED\_PERMANENTLY**
```
301
```
HTTP 301 code
* `int` **STATUS\_NON\_AUTHORITATIVE\_INFORMATION**
```
203
```
HTTP 203 code
* `int` **STATUS\_NO\_CONTENT**
```
204
```
HTTP 204 code
* `int` **STATUS\_OK**
```
200
```
HTTP 200 code
* `int` **STATUS\_PERMANENT\_REDIRECT**
```
308
```
HTTP 308 code
* `int` **STATUS\_SEE\_OTHER**
```
303
```
HTTP 303 code
* `int` **STATUS\_TEMPORARY\_REDIRECT**
```
307
```
HTTP 307 code
Property Summary
----------------
* [$\_cookies](#%24_cookies) protected `array` The array of cookies in the response.
Method Summary
--------------
* ##### [cookies()](#cookies()) public
Get all cookies
Method Detail
-------------
### cookies() public
```
cookies(): array
```
Get all cookies
#### Returns
`array`
Property Detail
---------------
### $\_cookies protected
The array of cookies in the response.
#### Type
`array`
cakephp Interface CommandCollectionAwareInterface Interface CommandCollectionAwareInterface
==========================================
An interface for shells that take a CommandCollection during initialization.
**Namespace:** [Cake\Console](namespace-cake.console)
Method Summary
--------------
* ##### [setCommandCollection()](#setCommandCollection()) public
Set the command collection being used.
Method Detail
-------------
### setCommandCollection() public
```
setCommandCollection(Cake\Console\CommandCollection $commands): void
```
Set the command collection being used.
#### Parameters
`Cake\Console\CommandCollection` $commands The commands to use.
#### Returns
`void`
cakephp Class StoppableIterator Class StoppableIterator
========================
Creates an iterator from another iterator that will verify a condition on each step. If the condition evaluates to false, the iterator will not yield more results.
**Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator)
**See:** \Cake\Collection\Collection::stopWhen()
Property Summary
----------------
* [$\_condition](#%24_condition) protected `callable` The condition to evaluate for each item of the collection
* [$\_innerIterator](#%24_innerIterator) protected `Traversable` A reference to the internal iterator this object is wrapping.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Creates an iterator that can be stopped based on a condition provided by a callback.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_serialize()](#__serialize()) public
Returns an array for serializing this of this object.
* ##### [\_\_unserialize()](#__unserialize()) public
Rebuilds the Collection instance.
* ##### [\_createMatcherFilter()](#_createMatcherFilter()) protected
Returns a callable that receives a value and will return whether it matches certain condition.
* ##### [\_extract()](#_extract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
* ##### [\_propertyExtractor()](#_propertyExtractor()) protected
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
* ##### [\_simpleExtract()](#_simpleExtract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path
* ##### [append()](#append()) public
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
* ##### [appendItem()](#appendItem()) public
Append a single item creating a new collection.
* ##### [avg()](#avg()) public
Returns the average of all the values extracted with $path or of this collection.
* ##### [buffered()](#buffered()) public
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
* ##### [cartesianProduct()](#cartesianProduct()) public
Create a new collection that is the cartesian product of the current collection
* ##### [chunk()](#chunk()) public
Breaks the collection into smaller arrays of the given size.
* ##### [chunkWithKeys()](#chunkWithKeys()) public
Breaks the collection into smaller arrays of the given size.
* ##### [combine()](#combine()) public
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
* ##### [compile()](#compile()) public
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
* ##### [contains()](#contains()) public
Returns true if $value is present in this collection. Comparisons are made both by value and type.
* ##### [count()](#count()) public
Returns the amount of elements in the collection.
* ##### [countBy()](#countBy()) public
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
* ##### [countKeys()](#countKeys()) public
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
* ##### [each()](#each()) public
Applies a callback to the elements in this collection.
* ##### [every()](#every()) public
Returns true if all values in this collection pass the truth test provided in the callback.
* ##### [extract()](#extract()) public
Returns a new collection containing the column or property value found in each of the elements.
* ##### [filter()](#filter()) public
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
* ##### [first()](#first()) public
Returns the first result in this collection
* ##### [firstMatch()](#firstMatch()) public
Returns the first result matching all the key-value pairs listed in conditions.
* ##### [groupBy()](#groupBy()) public
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
* ##### [indexBy()](#indexBy()) public
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
* ##### [insert()](#insert()) public
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
* ##### [isEmpty()](#isEmpty()) public
Returns whether there are elements in this collection
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
* ##### [last()](#last()) public
Returns the last result in this collection
* ##### [lazy()](#lazy()) public
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
* ##### [listNested()](#listNested()) public
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
* ##### [map()](#map()) public
Returns another collection after modifying each of the values in this one using the provided callable.
* ##### [match()](#match()) public
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
* ##### [max()](#max()) public
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [median()](#median()) public
Returns the median of all the values extracted with $path or of this collection.
* ##### [min()](#min()) public
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [nest()](#nest()) public
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
* ##### [newCollection()](#newCollection()) protected
Returns a new collection.
* ##### [optimizeUnwrap()](#optimizeUnwrap()) protected
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
* ##### [prepend()](#prepend()) public
Prepend a set of items to a collection creating a new collection
* ##### [prependItem()](#prependItem()) public
Prepend a single item creating a new collection.
* ##### [reduce()](#reduce()) public
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
* ##### [reject()](#reject()) public
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
* ##### [sample()](#sample()) public
Returns a new collection with maximum $size random elements from this collection
* ##### [serialize()](#serialize()) public
Returns a string representation of this object that can be used to reconstruct it
* ##### [shuffle()](#shuffle()) public
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
* ##### [skip()](#skip()) public
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
* ##### [some()](#some()) public
Returns true if any of the values in this collection pass the truth test provided in the callback.
* ##### [sortBy()](#sortBy()) public
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
* ##### [stopWhen()](#stopWhen()) public
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
* ##### [sumOf()](#sumOf()) public
Returns the total sum of all the values extracted with $matcher or of this collection.
* ##### [take()](#take()) public
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
* ##### [takeLast()](#takeLast()) public
Returns the last N elements of a collection
* ##### [through()](#through()) public
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
* ##### [toArray()](#toArray()) public
Returns an array representation of the results
* ##### [toList()](#toList()) public
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
* ##### [transpose()](#transpose()) public
Transpose rows and columns into columns and rows
* ##### [unfold()](#unfold()) public
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
* ##### [unserialize()](#unserialize()) public
Unserializes the passed string and rebuilds the Collection instance
* ##### [unwrap()](#unwrap()) public
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
* ##### [valid()](#valid()) public
Evaluates the condition and returns its result, this controls whether more results will be yielded.
* ##### [zip()](#zip()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
* ##### [zipWith()](#zipWith()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Method Detail
-------------
### \_\_construct() public
```
__construct(iterable $items, callable $condition)
```
Creates an iterator that can be stopped based on a condition provided by a callback.
Each time the condition callback is executed it will receive the value of the element in the current iteration, the key of the element and the passed $items iterator as arguments, in that order.
#### Parameters
`iterable` $items The list of values to iterate
`callable` $condition A function that will be called for each item in the collection, if the result evaluates to false, no more items will be yielded from this iterator.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_serialize() public
```
__serialize(): array
```
Returns an array for serializing this of this object.
#### Returns
`array`
### \_\_unserialize() public
```
__unserialize(array $data): void
```
Rebuilds the Collection instance.
#### Parameters
`array` $data Data array.
#### Returns
`void`
### \_createMatcherFilter() protected
```
_createMatcherFilter(array $conditions): Closure
```
Returns a callable that receives a value and will return whether it matches certain condition.
#### Parameters
`array` $conditions A key-value list of conditions to match where the key is the property path to get from the current item and the value is the value to be compared the item with.
#### Returns
`Closure`
### \_extract() protected
```
_extract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### \_propertyExtractor() protected
```
_propertyExtractor(callable|string $path): callable
```
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
#### Parameters
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
#### Returns
`callable`
### \_simpleExtract() protected
```
_simpleExtract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### append() public
```
append(iterable $items): self
```
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
#### Parameters
`iterable` $items #### Returns
`self`
### appendItem() public
```
appendItem(mixed $item, mixed $key = null): self
```
Append a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### avg() public
```
avg(callable|string|null $path = null): float|int|null
```
Returns the average of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
```
The average of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### buffered() public
```
buffered(): self
```
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
#### Returns
`self`
### cartesianProduct() public
```
cartesianProduct(callable|null $operation = null, callable|null $filter = null): Cake\Collection\CollectionInterface
```
Create a new collection that is the cartesian product of the current collection
In order to create a carteisan product a collection must contain a single dimension of data.
### Example
```
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
```
#### Parameters
`callable|null` $operation optional A callable that allows you to customize the product result.
`callable|null` $filter optional A filtering callback that must return true for a result to be part of the final results.
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### chunk() public
```
chunk(int $chunkSize): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
```
#### Parameters
`int` $chunkSize #### Returns
`self`
### chunkWithKeys() public
```
chunkWithKeys(int $chunkSize, bool $keepKeys = true): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
```
#### Parameters
`int` $chunkSize `bool` $keepKeys optional #### Returns
`self`
### combine() public
```
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): self
```
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
### Examples:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar']
];
```
#### Parameters
`callable|string` $keyPath `callable|string` $valuePath `callable|string|null` $groupPath optional #### Returns
`self`
### compile() public
```
compile(bool $keepKeys = true): self
```
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
### Example:
```
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
```
In the above example, had the collection not been compiled before, the iterations for `map`, `sortBy` and `extract` would've been executed twice: once for getting `$isJohnHere` and once for `$allButJohn`
You can think of this method as a way to create save points for complex calculations in a collection.
#### Parameters
`bool` $keepKeys optional #### Returns
`self`
### contains() public
```
contains(mixed $value): bool
```
Returns true if $value is present in this collection. Comparisons are made both by value and type.
#### Parameters
`mixed` $value #### Returns
`bool`
### count() public
```
count(): int
```
Returns the amount of elements in the collection.
WARNINGS:
---------
### Will change the current position of the iterator:
Calling this method at the same time that you are iterating this collections, for example in a foreach, will result in undefined behavior. Avoid doing this.
### Consumes all elements for NoRewindIterator collections:
On certain type of collections, calling this method may render unusable afterwards. That is, you may not be able to get elements out of it, or to iterate on it anymore.
Specifically any collection wrapping a Generator (a function with a yield statement) or a unbuffered database cursor will not accept any other function calls after calling `count()` on it.
Create a new collection with `buffered()` method to overcome this problem.
### Can report more elements than unique keys:
Any collection constructed by appending collections together, or by having internal iterators returning duplicate keys, will report a larger amount of elements using this functions than the final amount of elements when converting the collections to a keyed array. This is because duplicate keys will be collapsed into a single one in the final array, whereas this count method is only concerned by the amount of elements after converting it to a plain list.
If you need the count of elements after taking the keys in consideration (the count of unique keys), you can call `countKeys()`
#### Returns
`int`
### countBy() public
```
countBy(callable|string $path): self
```
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### countKeys() public
```
countKeys(): int
```
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
This method comes with a number of caveats. Please refer to `CollectionInterface::count()` for details.
#### Returns
`int`
### each() public
```
each(callable $callback): $this
```
Applies a callback to the elements in this collection.
### Example:
```
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
```
#### Parameters
`callable` $callback #### Returns
`$this`
### every() public
```
every(callable $callback): bool
```
Returns true if all values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
```
Empty collections always return true.
#### Parameters
`callable` $callback #### Returns
`bool`
### extract() public
```
extract(callable|string $path): self
```
Returns a new collection containing the column or property value found in each of the elements.
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
### Example:
Extract the user name for all comments in the array:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
```
It is also possible to extract a flattened collection out of nested properties
```
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
```
#### Parameters
`callable|string` $path #### Returns
`self`
### filter() public
```
filter(callable|null $callback = null): self
```
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### first() public
```
first(): mixed
```
Returns the first result in this collection
#### Returns
`mixed`
### firstMatch() public
```
firstMatch(array $conditions): mixed
```
Returns the first result matching all the key-value pairs listed in conditions.
#### Parameters
`array` $conditions #### Returns
`mixed`
### groupBy() public
```
groupBy(callable|string $path): self
```
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### indexBy() public
```
indexBy(callable|string $path): self
```
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### insert() public
```
insert(string $path, mixed $values): self
```
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
### Example:
Insert ages into a collection containing users:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
```
#### Parameters
`string` $path `mixed` $values #### Returns
`self`
### isEmpty() public
```
isEmpty(): bool
```
Returns whether there are elements in this collection
### Example:
```
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
```
```
(new Collection([]))->isEmpty(); // true
```
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): array
```
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
Part of JsonSerializable interface.
#### Returns
`array`
### last() public
```
last(): mixed
```
Returns the last result in this collection
#### Returns
`mixed`
### lazy() public
```
lazy(): self
```
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
A lazy collection can only be iterated once. A second attempt results in an error.
#### Returns
`self`
### listNested() public
```
listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): self
```
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
* desc: RecursiveIteratorIterator::SELF\_FIRST
* asc: RecursiveIteratorIterator::CHILD\_FIRST
* leaves: RecursiveIteratorIterator::LEAVES\_ONLY
### Example:
```
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
```
#### Parameters
`string|int` $order optional `callable|string` $nestingKey optional #### Returns
`self`
### map() public
```
map(callable $callback): self
```
Returns another collection after modifying each of the values in this one using the provided callable.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Getting a collection of booleans where true indicates if a person is female:
```
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### match() public
```
match(array $conditions): self
```
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
### Example:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
]
```
#### Parameters
`array` $conditions #### Returns
`self`
### max() public
```
max(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### median() public
```
median(callable|string|null $path = null): float|int|null
```
Returns the median of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
```
The median of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### min() public
```
min(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### nest() public
```
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self
```
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
#### Parameters
`callable|string` $idPath `callable|string` $parentPath `string` $nestingKey optional #### Returns
`self`
### newCollection() protected
```
newCollection(mixed ...$args): Cake\Collection\CollectionInterface
```
Returns a new collection.
Allows classes which use this trait to determine their own type of returned collection interface
#### Parameters
`mixed` ...$args Constructor arguments.
#### Returns
`Cake\Collection\CollectionInterface`
### optimizeUnwrap() protected
```
optimizeUnwrap(): iterable
```
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
#### Returns
`iterable`
### prepend() public
```
prepend(mixed $items): self
```
Prepend a set of items to a collection creating a new collection
#### Parameters
`mixed` $items #### Returns
`self`
### prependItem() public
```
prependItem(mixed $item, mixed $key = null): self
```
Prepend a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### reduce() public
```
reduce(callable $callback, mixed $initial = null): mixed
```
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
#### Parameters
`callable` $callback `mixed` $initial optional #### Returns
`mixed`
### reject() public
```
reject(callable $callback): self
```
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### sample() public
```
sample(int $length = 10): self
```
Returns a new collection with maximum $size random elements from this collection
#### Parameters
`int` $length optional #### Returns
`self`
### serialize() public
```
serialize(): string
```
Returns a string representation of this object that can be used to reconstruct it
#### Returns
`string`
### shuffle() public
```
shuffle(): self
```
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
#### Returns
`self`
### skip() public
```
skip(int $length): self
```
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
#### Parameters
`int` $length #### Returns
`self`
### some() public
```
some(callable $callback): bool
```
Returns true if any of the values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
```
#### Parameters
`callable` $callback #### Returns
`bool`
### sortBy() public
```
sortBy(callable|string $path, int $order = \SORT_DESC, int $sort = \SORT_NUMERIC): self
```
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
### Example:
```
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
```
#### Parameters
`callable|string` $path `int` $order optional `int` $sort optional #### Returns
`self`
### stopWhen() public
```
stopWhen(callable|array $condition): self
```
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
### Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
```
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
```
Get elements until the first unapproved message is found:
```
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
```
#### Parameters
`callable|array` $condition #### Returns
`self`
### sumOf() public
```
sumOf(callable|string|null $path = null): float|int
```
Returns the total sum of all the values extracted with $matcher or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
```
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int`
### take() public
```
take(int $length = 1, int $offset = 0): self
```
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
#### Parameters
`int` $length optional `int` $offset optional #### Returns
`self`
### takeLast() public
```
takeLast(int $length): self
```
Returns the last N elements of a collection
### Example:
```
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
```
#### Parameters
`int` $length #### Returns
`self`
### through() public
```
through(callable $callback): self
```
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
### Example:
```
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### toArray() public
```
toArray(bool $keepKeys = true): array
```
Returns an array representation of the results
#### Parameters
`bool` $keepKeys optional #### Returns
`array`
### toList() public
```
toList(): array
```
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
#### Returns
`array`
### transpose() public
```
transpose(): Cake\Collection\CollectionInterface
```
Transpose rows and columns into columns and rows
### Example:
```
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
```
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### unfold() public
```
unfold(callable|null $callback = null): self
```
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
### Example:
```
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
```
Using a transformer
```
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### unserialize() public
```
unserialize(string $collection): void
```
Unserializes the passed string and rebuilds the Collection instance
#### Parameters
`string` $collection The serialized collection
#### Returns
`void`
### unwrap() public
```
unwrap(): Traversable
```
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
#### Returns
`Traversable`
### valid() public
```
valid(): bool
```
Evaluates the condition and returns its result, this controls whether more results will be yielded.
#### Returns
`bool`
### zip() public
```
zip(iterable $items): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
### Example:
```
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
```
#### Parameters
`iterable` $items #### Returns
`self`
### zipWith() public
```
zipWith(iterable $items, callable $callback): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
The resulting element will be the return value of the $callable function.
### Example:
```
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
```
#### Parameters
`iterable` $items `callable` $callback #### Returns
`self`
Property Detail
---------------
### $\_condition protected
The condition to evaluate for each item of the collection
#### Type
`callable`
### $\_innerIterator protected
A reference to the internal iterator this object is wrapping.
#### Type
`Traversable`
| programming_docs |
cakephp Class EntityRoute Class EntityRoute
==================
Matches entities to routes
This route will match by entity and map its fields to the URL pattern by comparing the field names with the template vars. This makes it easy and convenient to change routes globally.
**Namespace:** [Cake\Routing\Route](namespace-cake.routing.route)
Constants
---------
* `string` **PLACEHOLDER\_REGEX**
```
'#\\{([a-z][a-z0-9-_]*)\\}#i'
```
Regex for matching braced placholders in route template.
* `array<string>` **VALID\_METHODS**
```
['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD']
```
Valid HTTP methods.
Property Summary
----------------
* [$\_compiledRoute](#%24_compiledRoute) protected `string|null` The compiled route regular expression
* [$\_extensions](#%24_extensions) protected `array<string>` List of connected extensions for this route.
* [$\_greedy](#%24_greedy) protected `bool` Is this route a greedy route? Greedy routes have a `/*` in their template
* [$\_name](#%24_name) protected `string|null` The name for a route. Fetch with Route::getName();
* [$braceKeys](#%24braceKeys) protected `bool` Track whether brace keys `{var}` were used.
* [$defaults](#%24defaults) public `array` Default parameters for a Route
* [$keys](#%24keys) public `array` An array of named segments in a Route. `/{controller}/{action}/{id}` has 3 key elements
* [$middleware](#%24middleware) protected `array` List of middleware that should be applied.
* [$options](#%24options) public `array` An array of additional parameters for the Route.
* [$template](#%24template) public `string` The routes template string.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor for a Route
* ##### [\_\_set\_state()](#__set_state()) public static
Set state magic method to support var\_export
* ##### [\_checkEntity()](#_checkEntity()) protected
Checks that we really deal with an entity object
* ##### [\_matchMethod()](#_matchMethod()) protected
Check whether the URL's HTTP method matches.
* ##### [\_parseArgs()](#_parseArgs()) protected
Parse passed parameters into a list of passed args.
* ##### [\_parseExtension()](#_parseExtension()) protected
Removes the extension from $url if it contains a registered extension. If no registered extension is found, no extension is returned and the URL is returned unmodified.
* ##### [\_persistParams()](#_persistParams()) protected
Apply persistent parameters to a URL array. Persistent parameters are a special key used during route creation to force route parameters to persist when omitted from a URL array.
* ##### [\_writeRoute()](#_writeRoute()) protected
Builds a route regular expression.
* ##### [\_writeUrl()](#_writeUrl()) protected
Converts a matching route array into a URL string.
* ##### [compile()](#compile()) public
Compiles the route's regular expression.
* ##### [compiled()](#compiled()) public
Check if a Route has been compiled into a regular expression.
* ##### [getExtensions()](#getExtensions()) public
Get the supported extensions for this route.
* ##### [getMiddleware()](#getMiddleware()) public
Get the names of the middleware that should be applied to this route.
* ##### [getName()](#getName()) public
Get the standardized plugin.controller:action name for a route.
* ##### [hostMatches()](#hostMatches()) public
Check to see if the host matches the route requirements
* ##### [match()](#match()) public
Match by entity and map its fields to the URL pattern by comparing the field names with the template vars.
* ##### [normalizeAndValidateMethods()](#normalizeAndValidateMethods()) protected
Normalize method names to upper case and validate that they are valid HTTP methods.
* ##### [parse()](#parse()) public
Checks to see if the given URL can be parsed by this route.
* ##### [parseRequest()](#parseRequest()) public
Checks to see if the given URL can be parsed by this route.
* ##### [setExtensions()](#setExtensions()) public
Set the supported extensions for this route.
* ##### [setHost()](#setHost()) public
Set host requirement
* ##### [setMethods()](#setMethods()) public
Set the accepted HTTP methods for this route.
* ##### [setMiddleware()](#setMiddleware()) public
Set the names of the middleware that should be applied to this route.
* ##### [setPass()](#setPass()) public
Set the names of parameters that will be converted into passed parameters
* ##### [setPatterns()](#setPatterns()) public
Set regexp patterns for routing parameters
* ##### [setPersist()](#setPersist()) public
Set the names of parameters that will persisted automatically
* ##### [staticPath()](#staticPath()) public
Get the static path portion for this route.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $template, array $defaults = [], array<string, mixed> $options = [])
```
Constructor for a Route
### Options
* `_ext` - Defines the extensions used for this route.
* `_middleware` - Define the middleware names for this route.
* `pass` - Copies the listed parameters into params['pass'].
* `_method` - Defines the HTTP method(s) the route applies to. It can be a string or array of valid HTTP method name.
* `_host` - Define the host name pattern if you want this route to only match specific host names. You can use `.*` and to create wildcard subdomains/hosts e.g. `*.example.com` matches all subdomains on `example.com`.
* '\_port` - Define the port if you want this route to only match specific port number.
* '\_urldecode' - Set to `false` to disable URL decoding before route parsing.
#### Parameters
`string` $template Template string with parameter placeholders
`array` $defaults optional Defaults for the route.
`array<string, mixed>` $options optional Array of additional options for the Route
#### Throws
`InvalidArgumentException`
When `$options['\_method']` are not in `VALID\_METHODS` list. ### \_\_set\_state() public static
```
__set_state(array<string, mixed> $fields): static
```
Set state magic method to support var\_export
This method helps for applications that want to implement router caching.
#### Parameters
`array<string, mixed>` $fields Key/Value of object attributes
#### Returns
`static`
### \_checkEntity() protected
```
_checkEntity(ArrayAccess|array $entity): void
```
Checks that we really deal with an entity object
#### Parameters
`ArrayAccess|array` $entity Entity value from the URL options
#### Returns
`void`
#### Throws
`RuntimeException`
### \_matchMethod() protected
```
_matchMethod(array $url): bool
```
Check whether the URL's HTTP method matches.
#### Parameters
`array` $url The array for the URL being generated.
#### Returns
`bool`
### \_parseArgs() protected
```
_parseArgs(string $args, array $context): array<string>
```
Parse passed parameters into a list of passed args.
Return true if a given named $param's $val matches a given $rule depending on $context. Currently implemented rule types are controller, action and match that can be combined with each other.
#### Parameters
`string` $args A string with the passed params. eg. /1/foo
`array` $context The current route context, which should contain controller/action keys.
#### Returns
`array<string>`
### \_parseExtension() protected
```
_parseExtension(string $url): array
```
Removes the extension from $url if it contains a registered extension. If no registered extension is found, no extension is returned and the URL is returned unmodified.
#### Parameters
`string` $url The url to parse.
#### Returns
`array`
### \_persistParams() protected
```
_persistParams(array $url, array $params): array
```
Apply persistent parameters to a URL array. Persistent parameters are a special key used during route creation to force route parameters to persist when omitted from a URL array.
#### Parameters
`array` $url The array to apply persistent parameters to.
`array` $params An array of persistent values to replace persistent ones.
#### Returns
`array`
### \_writeRoute() protected
```
_writeRoute(): void
```
Builds a route regular expression.
Uses the template, defaults and options properties to compile a regular expression that can be used to parse request strings.
#### Returns
`void`
### \_writeUrl() protected
```
_writeUrl(array $params, array $pass = [], array $query = []): string
```
Converts a matching route array into a URL string.
Composes the string URL using the template used to create the route.
#### Parameters
`array` $params The params to convert to a string url
`array` $pass optional The additional passed arguments
`array` $query optional An array of parameters
#### Returns
`string`
### compile() public
```
compile(): string
```
Compiles the route's regular expression.
Modifies defaults property so all necessary keys are set and populates $this->names with the named routing elements.
#### Returns
`string`
### compiled() public
```
compiled(): bool
```
Check if a Route has been compiled into a regular expression.
#### Returns
`bool`
### getExtensions() public
```
getExtensions(): array<string>
```
Get the supported extensions for this route.
#### Returns
`array<string>`
### getMiddleware() public
```
getMiddleware(): array
```
Get the names of the middleware that should be applied to this route.
#### Returns
`array`
### getName() public
```
getName(): string
```
Get the standardized plugin.controller:action name for a route.
#### Returns
`string`
### hostMatches() public
```
hostMatches(string $host): bool
```
Check to see if the host matches the route requirements
#### Parameters
`string` $host The request's host name
#### Returns
`bool`
### match() public
```
match(array $url, array $context = []): string|null
```
Match by entity and map its fields to the URL pattern by comparing the field names with the template vars.
If a routing key is defined in both `$url` and the entity, the value defined in `$url` will be preferred.
#### Parameters
`array` $url Array of parameters to convert to a string.
`array` $context optional An array of the current request context. Contains information such as the current host, scheme, port, and base directory.
#### Returns
`string|null`
### normalizeAndValidateMethods() protected
```
normalizeAndValidateMethods(array<string>|string $methods): array<string>|string
```
Normalize method names to upper case and validate that they are valid HTTP methods.
#### Parameters
`array<string>|string` $methods Methods.
#### Returns
`array<string>|string`
#### Throws
`InvalidArgumentException`
When methods are not in `VALID\_METHODS` list. ### parse() public
```
parse(string $url, string $method): array|null
```
Checks to see if the given URL can be parsed by this route.
If the route can be parsed an array of parameters will be returned; if not `null` will be returned. String URLs are parsed if they match a routes regular expression.
#### Parameters
`string` $url The URL to attempt to parse.
`string` $method The HTTP method of the request being parsed.
#### Returns
`array|null`
#### Throws
`Cake\Http\Exception\BadRequestException`
When method is not an empty string and not in `VALID\_METHODS` list. ### parseRequest() public
```
parseRequest(Psr\Http\Message\ServerRequestInterface $request): array|null
```
Checks to see if the given URL can be parsed by this route.
If the route can be parsed an array of parameters will be returned; if not `null` will be returned.
#### Parameters
`Psr\Http\Message\ServerRequestInterface` $request The URL to attempt to parse.
#### Returns
`array|null`
### setExtensions() public
```
setExtensions(array<string> $extensions): $this
```
Set the supported extensions for this route.
#### Parameters
`array<string>` $extensions The extensions to set.
#### Returns
`$this`
### setHost() public
```
setHost(string $host): $this
```
Set host requirement
#### Parameters
`string` $host The host name this route is bound to
#### Returns
`$this`
### setMethods() public
```
setMethods(array<string> $methods): $this
```
Set the accepted HTTP methods for this route.
#### Parameters
`array<string>` $methods The HTTP methods to accept.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
When methods are not in `VALID\_METHODS` list. ### setMiddleware() public
```
setMiddleware(array $middleware): $this
```
Set the names of the middleware that should be applied to this route.
#### Parameters
`array` $middleware The list of middleware names to apply to this route. Middleware names will not be checked until the route is matched.
#### Returns
`$this`
### setPass() public
```
setPass(array<string> $names): $this
```
Set the names of parameters that will be converted into passed parameters
#### Parameters
`array<string>` $names The names of the parameters that should be passed.
#### Returns
`$this`
### setPatterns() public
```
setPatterns(array<string> $patterns): $this
```
Set regexp patterns for routing parameters
If any of your patterns contain multibyte values, the `multibytePattern` mode will be enabled.
#### Parameters
`array<string>` $patterns The patterns to apply to routing elements
#### Returns
`$this`
### setPersist() public
```
setPersist(array $names): $this
```
Set the names of parameters that will persisted automatically
Persistent parameters allow you to define which route parameters should be automatically included when generating new URLs. You can override persistent parameters by redefining them in a URL or remove them by setting the persistent parameter to `false`.
```
// remove a persistent 'date' parameter
Router::url(['date' => false', ...]);
```
#### Parameters
`array` $names The names of the parameters that should be passed.
#### Returns
`$this`
### staticPath() public
```
staticPath(): string
```
Get the static path portion for this route.
#### Returns
`string`
Property Detail
---------------
### $\_compiledRoute protected
The compiled route regular expression
#### Type
`string|null`
### $\_extensions protected
List of connected extensions for this route.
#### Type
`array<string>`
### $\_greedy protected
Is this route a greedy route? Greedy routes have a `/*` in their template
#### Type
`bool`
### $\_name protected
The name for a route. Fetch with Route::getName();
#### Type
`string|null`
### $braceKeys protected
Track whether brace keys `{var}` were used.
#### Type
`bool`
### $defaults public
Default parameters for a Route
#### Type
`array`
### $keys public
An array of named segments in a Route. `/{controller}/{action}/{id}` has 3 key elements
#### Type
`array`
### $middleware protected
List of middleware that should be applied.
#### Type
`array`
### $options public
An array of additional parameters for the Route.
#### Type
`array`
### $template public
The routes template string.
#### Type
`string`
cakephp Class RedisEngine Class RedisEngine
==================
Redis storage engine for cache.
**Namespace:** [Cake\Cache\Engine](namespace-cake.cache.engine)
Constants
---------
* `string` **CHECK\_KEY**
```
'key'
```
* `string` **CHECK\_VALUE**
```
'value'
```
Property Summary
----------------
* [$\_Redis](#%24_Redis) protected `Redis` Redis wrapper.
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` The default config used unless overridden by runtime configuration
* [$\_groupPrefix](#%24_groupPrefix) protected `string` Contains the compiled string with all group prefixes to be prepended to every key in this cache engine
Method Summary
--------------
* ##### [\_\_destruct()](#__destruct()) public
Disconnects from the redis server
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_connect()](#_connect()) protected
Connects to a Redis server
* ##### [\_key()](#_key()) protected
Generates a key for cache backend usage.
* ##### [add()](#add()) public
Write data for key into cache if it doesn't exist already. If it already exists, it fails and returns false.
* ##### [clear()](#clear()) public
Delete all keys from the cache
* ##### [clearBlocking()](#clearBlocking()) public
Delete all keys from the cache by a blocking operation
* ##### [clearGroup()](#clearGroup()) public
Increments the group value to simulate deletion of all keys under a group old values will remain in storage until they expire.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [decrement()](#decrement()) public
Decrements the value of an integer cached key & update the expiry time
* ##### [delete()](#delete()) public
Delete a key from the cache
* ##### [deleteAsync()](#deleteAsync()) public
Delete a key from the cache asynchronously
* ##### [deleteMultiple()](#deleteMultiple()) public
Deletes multiple cache items as a list
* ##### [duration()](#duration()) protected
Convert the various expressions of a TTL value into duration in seconds
* ##### [ensureValidKey()](#ensureValidKey()) protected
Ensure the validity of the given cache key.
* ##### [ensureValidType()](#ensureValidType()) protected
Ensure the validity of the argument type and cache keys.
* ##### [get()](#get()) public
Read a key from the cache
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getMultiple()](#getMultiple()) public
Obtains multiple cache items by their unique keys.
* ##### [groups()](#groups()) public
Returns the `group value` for each of the configured groups If the group initial value was not found, then it initializes the group accordingly.
* ##### [has()](#has()) public
Determines whether an item is present in the cache.
* ##### [increment()](#increment()) public
Increments the value of an integer cached key & update the expiry time
* ##### [init()](#init()) public
Initialize the Cache Engine
* ##### [serialize()](#serialize()) protected
Serialize value for saving to Redis.
* ##### [set()](#set()) public
Write data for key into cache.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setMultiple()](#setMultiple()) public
Persists a set of key => value pairs in the cache, with an optional TTL.
* ##### [unserialize()](#unserialize()) protected
Unserialize string value fetched from Redis.
* ##### [warning()](#warning()) protected
Cache Engines may trigger warnings if they encounter failures during operation, if option warnOnWriteFailures is set to true.
Method Detail
-------------
### \_\_destruct() public
```
__destruct()
```
Disconnects from the redis server
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_connect() protected
```
_connect(): bool
```
Connects to a Redis server
#### Returns
`bool`
### \_key() protected
```
_key(string $key): string
```
Generates a key for cache backend usage.
If the requested key is valid, the group prefix value and engine prefix are applied. Whitespace in keys will be replaced.
#### Parameters
`string` $key the key passed over
#### Returns
`string`
#### Throws
`Cake\Cache\InvalidArgumentException`
If key's value is invalid. ### add() public
```
add(string $key, mixed $value): bool
```
Write data for key into cache if it doesn't exist already. If it already exists, it fails and returns false.
Defaults to a non-atomic implementation. Subclasses should prefer atomic implementations.
#### Parameters
`string` $key Identifier for the data.
`mixed` $value Data to be cached.
#### Returns
`bool`
#### Links
https://github.com/phpredis/phpredis#set
### clear() public
```
clear(): bool
```
Delete all keys from the cache
#### Returns
`bool`
### clearBlocking() public
```
clearBlocking(): bool
```
Delete all keys from the cache by a blocking operation
Faster than clear() using unlink method.
#### Returns
`bool`
### clearGroup() public
```
clearGroup(string $group): bool
```
Increments the group value to simulate deletion of all keys under a group old values will remain in storage until they expire.
Each implementation needs to decide whether actually delete the keys or just augment a group generation value to achieve the same result.
#### Parameters
`string` $group name of the group to be cleared
#### Returns
`bool`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
```
$this->configShallow('key', $value);
```
Setting a nested value:
```
$this->configShallow('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->configShallow(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### decrement() public
```
decrement(string $key, int $offset = 1): int|false
```
Decrements the value of an integer cached key & update the expiry time
#### Parameters
`string` $key Identifier for the data
`int` $offset optional How much to subtract
#### Returns
`int|false`
### delete() public
```
delete(string $key): bool
```
Delete a key from the cache
#### Parameters
`string` $key Identifier for the data
#### Returns
`bool`
### deleteAsync() public
```
deleteAsync(string $key): bool
```
Delete a key from the cache asynchronously
Just unlink a key from the cache. The actual removal will happen later asynchronously.
#### Parameters
`string` $key Identifier for the data
#### Returns
`bool`
### deleteMultiple() public
```
deleteMultiple(iterable $keys): bool
```
Deletes multiple cache items as a list
This is a best effort attempt. If deleting an item would create an error it will be ignored, and all items will be attempted.
#### Parameters
`iterable` $keys A list of string-based keys to be deleted.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value. ### duration() protected
```
duration(DateInterval|int|null $ttl): int
```
Convert the various expressions of a TTL value into duration in seconds
#### Parameters
`DateInterval|int|null` $ttl The TTL value of this item. If null is sent, the driver's default duration will be used.
#### Returns
`int`
### ensureValidKey() protected
```
ensureValidKey(string $key): void
```
Ensure the validity of the given cache key.
#### Parameters
`string` $key Key to check.
#### Returns
`void`
#### Throws
`Cake\Cache\InvalidArgumentException`
When the key is not valid. ### ensureValidType() protected
```
ensureValidType(iterable $iterable, string $check = self::CHECK_VALUE): void
```
Ensure the validity of the argument type and cache keys.
#### Parameters
`iterable` $iterable The iterable to check.
`string` $check optional Whether to check keys or values.
#### Returns
`void`
#### Throws
`Cake\Cache\InvalidArgumentException`
### get() public
```
get(string $key, mixed $default = null): mixed
```
Read a key from the cache
#### Parameters
`string` $key Identifier for the data
`mixed` $default optional Default value to return if the key does not exist.
#### Returns
`mixed`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### Usage
Reading the whole config:
```
$this->getConfig();
```
Reading a specific value:
```
$this->getConfig('key');
```
Reading a nested value:
```
$this->getConfig('some.nested.key');
```
Reading with default value:
```
$this->getConfig('some-key', 'default-value');
```
#### Parameters
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getMultiple() public
```
getMultiple(iterable $keys, mixed $default = null): iterable
```
Obtains multiple cache items by their unique keys.
#### Parameters
`iterable` $keys A list of keys that can obtained in a single operation.
`mixed` $default optional Default value to return for keys that do not exist.
#### Returns
`iterable`
#### Throws
`Cake\Cache\InvalidArgumentException`
If $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value. ### groups() public
```
groups(): array<string>
```
Returns the `group value` for each of the configured groups If the group initial value was not found, then it initializes the group accordingly.
#### Returns
`array<string>`
### has() public
```
has(string $key): bool
```
Determines whether an item is present in the cache.
NOTE: It is recommended that has() is only to be used for cache warming type purposes and not to be used within your live applications operations for get/set, as this method is subject to a race condition where your has() will return true and immediately after, another script can remove it making the state of your app out of date.
#### Parameters
`string` $key The cache item key.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If the $key string is not a legal value. ### increment() public
```
increment(string $key, int $offset = 1): int|false
```
Increments the value of an integer cached key & update the expiry time
#### Parameters
`string` $key Identifier for the data
`int` $offset optional How much to increment
#### Returns
`int|false`
### init() public
```
init(array<string, mixed> $config = []): bool
```
Initialize the Cache Engine
Called automatically by the cache frontend
#### Parameters
`array<string, mixed>` $config optional array of setting for the engine
#### Returns
`bool`
### serialize() protected
```
serialize(mixed $value): string
```
Serialize value for saving to Redis.
This is needed instead of using Redis' in built serialization feature as it creates problems incrementing/decrementing intially set integer value.
#### Parameters
`mixed` $value Value to serialize.
#### Returns
`string`
#### Links
https://github.com/phpredis/phpredis/issues/81
### set() public
```
set(string $key, mixed $value, null|intDateInterval $ttl = null): bool
```
Write data for key into cache.
#### Parameters
`string` $key Identifier for the data
`mixed` $value Data to be cached
`null|intDateInterval` $ttl optional Optional. The TTL value of this item. If no value is sent and the driver supports TTL then the library may set a default value for it or let the driver take care of that.
#### Returns
`bool`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### Usage
Setting a specific value:
```
$this->setConfig('key', $value);
```
Setting a nested value:
```
$this->setConfig('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->setConfig(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setMultiple() public
```
setMultiple(iterable $values, null|intDateInterval $ttl = null): bool
```
Persists a set of key => value pairs in the cache, with an optional TTL.
#### Parameters
`iterable` $values A list of key => value pairs for a multiple-set operation.
`null|intDateInterval` $ttl optional Optional. The TTL value of this item. If no value is sent and the driver supports TTL then the library may set a default value for it or let the driver take care of that.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If $values is neither an array nor a Traversable, or if any of the $values are not a legal value. ### unserialize() protected
```
unserialize(string $value): mixed
```
Unserialize string value fetched from Redis.
#### Parameters
`string` $value Value to unserialize.
#### Returns
`mixed`
### warning() protected
```
warning(string $message): void
```
Cache Engines may trigger warnings if they encounter failures during operation, if option warnOnWriteFailures is set to true.
#### Parameters
`string` $message The warning message.
#### Returns
`void`
Property Detail
---------------
### $\_Redis protected
Redis wrapper.
#### Type
`Redis`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
The default config used unless overridden by runtime configuration
* `database` database number to use for connection.
* `duration` Specify how long items in this cache configuration last.
* `groups` List of groups or 'tags' associated to every key stored in this config. handy for deleting a complete group from cache.
* `password` Redis server password.
* `persistent` Connect to the Redis server with a persistent connection
* `port` port number to the Redis server.
* `prefix` Prefix appended to all entries. Good for when you need to share a keyspace with either another cache config or another application.
* `scanCount` Number of keys to ask for each scan (default: 10)
* `server` URL or IP to the Redis server host.
* `timeout` timeout in seconds (float).
* `unix_socket` Path to the unix socket file (default: false)
#### Type
`array<string, mixed>`
### $\_groupPrefix protected
Contains the compiled string with all group prefixes to be prepended to every key in this cache engine
#### Type
`string`
| programming_docs |
cakephp Namespace Mailer Namespace Mailer
================
### Namespaces
* [Cake\Mailer\Exception](namespace-cake.mailer.exception)
* [Cake\Mailer\Transport](namespace-cake.mailer.transport)
### Classes
* ##### [AbstractTransport](class-cake.mailer.abstracttransport)
Abstract transport for sending email
* ##### [Email](class-cake.mailer.email)
CakePHP Email class.
* ##### [Mailer](class-cake.mailer.mailer)
Mailer base class.
* ##### [Message](class-cake.mailer.message)
Email message class.
* ##### [Renderer](class-cake.mailer.renderer)
Class for rendering email message.
* ##### [TransportFactory](class-cake.mailer.transportfactory)
Factory class for generating email transport instances.
* ##### [TransportRegistry](class-cake.mailer.transportregistry)
An object registry for mailer transports.
### Traits
* ##### [MailerAwareTrait](trait-cake.mailer.mailerawaretrait)
Provides functionality for loading mailer classes onto properties of the host object.
cakephp Class OrderClauseExpression Class OrderClauseExpression
============================
An expression object for complex ORDER BY clauses
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
Property Summary
----------------
* [$\_direction](#%24_direction) protected `string` The direction of sorting.
* [$\_field](#%24_field) protected `Cake\Database\ExpressionInterface|array|string` The field name or expression to be used in the left hand side of the operator
Method Summary
--------------
* ##### [\_\_clone()](#__clone()) public
Create a deep clone of the order clause.
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getField()](#getField()) public
Returns the field name
* ##### [setField()](#setField()) public
Sets the field name
* ##### [sql()](#sql()) public
Converts the Node into a SQL string fragment.
* ##### [traverse()](#traverse()) public
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
Method Detail
-------------
### \_\_clone() public
```
__clone(): void
```
Create a deep clone of the order clause.
#### Returns
`void`
### \_\_construct() public
```
__construct(Cake\Database\ExpressionInterface|string $field, string $direction)
```
Constructor
#### Parameters
`Cake\Database\ExpressionInterface|string` $field The field to order on.
`string` $direction The direction to sort on.
### getField() public
```
getField(): Cake\Database\ExpressionInterface|array|string
```
Returns the field name
#### Returns
`Cake\Database\ExpressionInterface|array|string`
### setField() public
```
setField(Cake\Database\ExpressionInterface|array|string $field): void
```
Sets the field name
#### Parameters
`Cake\Database\ExpressionInterface|array|string` $field The field to compare with.
#### Returns
`void`
### sql() public
```
sql(Cake\Database\ValueBinder $binder): string
```
Converts the Node into a SQL string fragment.
#### Parameters
`Cake\Database\ValueBinder` $binder #### Returns
`string`
### traverse() public
```
traverse(Closure $callback): $this
```
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
#### Parameters
`Closure` $callback #### Returns
`$this`
Property Detail
---------------
### $\_direction protected
The direction of sorting.
#### Type
`string`
### $\_field protected
The field name or expression to be used in the left hand side of the operator
#### Type
`Cake\Database\ExpressionInterface|array|string`
cakephp Class SchemaLoader Class SchemaLoader
===================
Create test database schema from one or more SQL dump files.
This class can be useful to create test database schema when your schema is managed by tools external to your CakePHP application.
It is not well suited for applications/plugins that need to support multiple database platforms. You should use migrations for that instead.
**Namespace:** [Cake\TestSuite\Fixture](namespace-cake.testsuite.fixture)
Property Summary
----------------
* [$helper](#%24helper) protected `Cake\TestSuite\ConnectionHelper`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [loadInternalFile()](#loadInternalFile()) public
Load and apply CakePHP-specific schema file.
* ##### [loadSqlFiles()](#loadSqlFiles()) public
Load and apply schema sql file, or an array of files.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor.
### loadInternalFile() public
```
loadInternalFile(string $file, string $connectionName = 'test'): void
```
Load and apply CakePHP-specific schema file.
#### Parameters
`string` $file Schema file
`string` $connectionName optional Connection name
#### Returns
`void`
### loadSqlFiles() public
```
loadSqlFiles(array<string>|string $paths, string $connectionName = 'test', bool $dropTables = true, bool $truncateTables = false): void
```
Load and apply schema sql file, or an array of files.
#### Parameters
`array<string>|string` $paths Schema files to load
`string` $connectionName optional Connection name
`bool` $dropTables optional Drop all tables prior to loading schema files
`bool` $truncateTables optional Truncate all tables after loading schema files
#### Returns
`void`
Property Detail
---------------
### $helper protected
#### Type
`Cake\TestSuite\ConnectionHelper`
cakephp Class BaseCommand Class BaseCommand
==================
Base class for console commands.
Provides hooks for common command features:
* `initialize` Acts as a post-construct hook.
* `buildOptionParser` Build/Configure the option parser for your command.
* `execute` Execute your command with parsed Arguments and ConsoleIo
**Abstract**
**Namespace:** [Cake\Console](namespace-cake.console)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [buildOptionParser()](#buildOptionParser()) protected
Hook method for defining this command's option parser.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) abstract public
Implement this method with your command's logic.
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [run()](#run()) public
Run the command.
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
Method Detail
-------------
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### buildOptionParser() protected
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Hook method for defining this command's option parser.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The parser to be defined
#### Returns
`Cake\Console\ConsoleOptionParser`
### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() abstract public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int|null|void
```
Implement this method with your command's logic.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null|void`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
Property Detail
---------------
### $name protected
The name of this command.
#### Type
`string`
cakephp Class PluginLoadCommand Class PluginLoadCommand
========================
Command for loading plugins.
**Namespace:** [Cake\Command](namespace-cake.command)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$args](#%24args) protected `Cake\Console\Arguments` Arguments
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$io](#%24io) protected `Cake\Console\ConsoleIo` Console IO
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [buildOptionParser()](#buildOptionParser()) public
Get the option parser.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) public
Execute the command
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [modifyApplication()](#modifyApplication()) protected
Modify the application class
* ##### [run()](#run()) public
Run the command.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor
By default CakePHP will construct command objects when building the CommandCollection for your application.
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### buildOptionParser() public
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Get the option parser.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser to update
#### Returns
`Cake\Console\ConsoleOptionParser`
### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int|null
```
Execute the command
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### modifyApplication() protected
```
modifyApplication(string $app, string $plugin): void
```
Modify the application class
#### Parameters
`string` $app The Application file to modify.
`string` $plugin The plugin name to add.
#### Returns
`void`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
Property Detail
---------------
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $args protected
Arguments
#### Type
`Cake\Console\Arguments`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $io protected
Console IO
#### Type
`Cake\Console\ConsoleIo`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name protected
The name of this command.
#### Type
`string`
| programming_docs |
cakephp Class StatusSuccess Class StatusSuccess
====================
StatusSuccess
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$code](#%24code) protected `array<int, int>|int`
* [$response](#%24response) protected `Psr\Http\Message\ResponseInterface`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Overwrites the descriptions so we can remove the automatic "expected" message
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Check assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [statusCodeBetween()](#statusCodeBetween()) protected
Helper for checking status codes
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface|null $response)
```
Constructor
#### Parameters
`Psr\Http\Message\ResponseInterface|null` $response Response
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Overwrites the descriptions so we can remove the automatic "expected" message
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other Value
#### Returns
`string`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Check assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Array of min/max status codes, or a single code
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### statusCodeBetween() protected
```
statusCodeBetween(int $min, int $max): bool
```
Helper for checking status codes
#### Parameters
`int` $min Min status code (inclusive)
`int` $max Max status code (inclusive)
#### Returns
`bool`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $code protected
#### Type
`array<int, int>|int`
### $response protected
#### Type
`Psr\Http\Message\ResponseInterface`
cakephp Class FieldTypeConverter Class FieldTypeConverter
=========================
A callable class to be used for processing each of the rows in a statement result, so that the values are converted to the right PHP types.
**Namespace:** [Cake\Database](namespace-cake.database)
Property Summary
----------------
* [$\_driver](#%24_driver) protected `Cake\Database\DriverInterface` The driver object to be used in the type conversion
* [$\_typeMap](#%24_typeMap) protected `arrayCake\Database\TypeInterface>` An array containing the name of the fields and the Type objects each should use when converting them.
* [$batchingTypeMap](#%24batchingTypeMap) protected `array<string, array>` An array containing the name of the fields and the Type objects each should use when converting them using batching.
* [$types](#%24types) protected `arrayCake\Database\TypeInterfaceCake\Database\Type\BatchCastingInterface>` An array containing all the types registered in the Type system at the moment this object is created. Used so that the types list is not fetched on each single row of the results.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Builds the type map
* ##### [\_\_invoke()](#__invoke()) public
Converts each of the fields in the array that are present in the type map using the corresponding Type class.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Database\TypeMap $typeMap, Cake\Database\DriverInterface $driver)
```
Builds the type map
#### Parameters
`Cake\Database\TypeMap` $typeMap Contains the types to use for converting results
`Cake\Database\DriverInterface` $driver The driver to use for the type conversion
### \_\_invoke() public
```
__invoke(array $row): array<string, mixed>
```
Converts each of the fields in the array that are present in the type map using the corresponding Type class.
#### Parameters
`array` $row The array with the fields to be casted
#### Returns
`array<string, mixed>`
Property Detail
---------------
### $\_driver protected
The driver object to be used in the type conversion
#### Type
`Cake\Database\DriverInterface`
### $\_typeMap protected
An array containing the name of the fields and the Type objects each should use when converting them.
#### Type
`arrayCake\Database\TypeInterface>`
### $batchingTypeMap protected
An array containing the name of the fields and the Type objects each should use when converting them using batching.
#### Type
`array<string, array>`
### $types protected
An array containing all the types registered in the Type system at the moment this object is created. Used so that the types list is not fetched on each single row of the results.
#### Type
`arrayCake\Database\TypeInterfaceCake\Database\Type\BatchCastingInterface>`
cakephp Class FatalErrorException Class FatalErrorException
==========================
Represents a fatal error
**Namespace:** [Cake\Error](namespace-cake.error)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(string $message, int|null $code = null, string|null $file = null, int|null $line = null, Throwable|null $previous = null)
```
Constructor
#### Parameters
`string` $message Message string.
`int|null` $code optional Code.
`string|null` $file optional File name.
`int|null` $line optional Line number.
`Throwable|null` $previous optional The previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class AbstractDecorator Class AbstractDecorator
========================
Common base class for event decorator subclasses.
**Abstract**
**Namespace:** [Cake\Event\Decorator](namespace-cake.event.decorator)
Property Summary
----------------
* [$\_callable](#%24_callable) protected `callable` Callable
* [$\_options](#%24_options) protected `array` Decorator options
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_\_invoke()](#__invoke()) public
Invoke
* ##### [\_call()](#_call()) protected
Calls the decorated callable with the passed arguments.
Method Detail
-------------
### \_\_construct() public
```
__construct(callable $callable, array<string, mixed> $options = [])
```
Constructor.
#### Parameters
`callable` $callable Callable.
`array<string, mixed>` $options optional Decorator options.
### \_\_invoke() public
```
__invoke(): mixed
```
Invoke
#### Returns
`mixed`
#### Links
https://secure.php.net/manual/en/language.oop5.magic.php#object.invoke
### \_call() protected
```
_call(array $args): mixed
```
Calls the decorated callable with the passed arguments.
#### Parameters
`array` $args Arguments for the callable.
#### Returns
`mixed`
Property Detail
---------------
### $\_callable protected
Callable
#### Type
`callable`
### $\_options protected
Decorator options
#### Type
`array`
cakephp Class Event Class Event
============
Class Event
**Namespace:** [Cake\Event](namespace-cake.event)
Property Summary
----------------
* [$\_data](#%24_data) protected `array` Custom data for the method that receives the event
* [$\_name](#%24_name) protected `string` Name of the event
* [$\_stopped](#%24_stopped) protected `bool` Flags an event as stopped or not, default is false
* [$\_subject](#%24_subject) protected `object|null` The object this event applies to (usually the same object that generates the event)
* [$result](#%24result) protected `mixed` Property used to retain the result value of the event listeners
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getData()](#getData()) public
Access the event data/payload.
* ##### [getName()](#getName()) public
Returns the name of this event. This is usually used as the event identifier
* ##### [getResult()](#getResult()) public
The result value of the event listeners
* ##### [getSubject()](#getSubject()) public
Returns the subject of this event
* ##### [isStopped()](#isStopped()) public
Check if the event is stopped
* ##### [setData()](#setData()) public
Assigns a value to the data/payload of this event.
* ##### [setResult()](#setResult()) public
Listeners can attach a result value to the event.
* ##### [stopPropagation()](#stopPropagation()) public
Stops the event from being used anymore
Method Detail
-------------
### \_\_construct() public
```
__construct(string $name, object|null $subject = null, ArrayAccess|array|null $data = null)
```
Constructor
### Examples of usage:
```
$event = new Event('Order.afterBuy', $this, ['buyer' => $userData]);
$event = new Event('User.afterRegister', $userModel);
```
#### Parameters
`string` $name Name of the event
`object|null` $subject optional the object that this event applies to (usually the object that is generating the event).
`ArrayAccess|array|null` $data optional any value you wish to be transported with this event to it can be read by listeners.
### getData() public
```
getData(string|null $key = null): mixed|array|null
```
Access the event data/payload.
#### Parameters
`string|null` $key optional The data payload element to return, or null to return all data.
#### Returns
`mixed|array|null`
### getName() public
```
getName(): string
```
Returns the name of this event. This is usually used as the event identifier
#### Returns
`string`
### getResult() public
```
getResult(): mixed
```
The result value of the event listeners
#### Returns
`mixed`
### getSubject() public
```
getSubject(): object
```
Returns the subject of this event
If the event has no subject an exception will be raised.
#### Returns
`object`
#### Throws
`Cake\Core\Exception\CakeException`
### isStopped() public
```
isStopped(): bool
```
Check if the event is stopped
#### Returns
`bool`
### setData() public
```
setData(array|string $key, mixed $value = null): $this
```
Assigns a value to the data/payload of this event.
#### Parameters
`array|string` $key An array will replace all payload data, and a key will set just that array item.
`mixed` $value optional The value to set.
#### Returns
`$this`
### setResult() public
```
setResult(mixed $value = null): $this
```
Listeners can attach a result value to the event.
#### Parameters
`mixed` $value optional The value to set.
#### Returns
`$this`
### stopPropagation() public
```
stopPropagation(): void
```
Stops the event from being used anymore
#### Returns
`void`
Property Detail
---------------
### $\_data protected
Custom data for the method that receives the event
#### Type
`array`
### $\_name protected
Name of the event
#### Type
`string`
### $\_stopped protected
Flags an event as stopped or not, default is false
#### Type
`bool`
### $\_subject protected
The object this event applies to (usually the same object that generates the event)
#### Type
`object|null`
### $result protected
Property used to retain the result value of the event listeners
Use setResult() and getResult() to set and get the result.
#### Type
`mixed`
| programming_docs |
cakephp Class SqliteStatement Class SqliteStatement
======================
Statement class meant to be used by an Sqlite driver
**Namespace:** [Cake\Database\Statement](namespace-cake.database.statement)
Constants
---------
* `string` **FETCH\_TYPE\_ASSOC**
```
'assoc'
```
Used to designate that an associated array be returned in a result when calling fetch methods
* `string` **FETCH\_TYPE\_NUM**
```
'num'
```
Used to designate that numeric indexes be returned in a result when calling fetch methods
* `string` **FETCH\_TYPE\_OBJ**
```
'obj'
```
Used to designate that a stdClass object be returned in a result when calling fetch methods
Property Summary
----------------
* [$\_bufferResults](#%24_bufferResults) protected `bool` Whether to buffer results in php
* [$\_driver](#%24_driver) protected `Cake\Database\DriverInterface` Reference to the driver object associated to this statement.
* [$\_hasExecuted](#%24_hasExecuted) protected `bool` Whether this statement has already been executed
* [$\_statement](#%24_statement) protected `Cake\Database\StatementInterface` Statement instance implementation, such as PDOStatement or any other custom implementation.
* [$queryString](#%24queryString) public @property-read `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_get()](#__get()) public
Magic getter to return $queryString as read-only.
* ##### [bind()](#bind()) public
Binds a set of values to statement object with corresponding type.
* ##### [bindValue()](#bindValue()) public
Assign a value to a positional or named variable in prepared query. If using positional variables you need to start with index one, if using named params then just use the name in any order.
* ##### [bufferResults()](#bufferResults()) public
Whether to buffer results in php
* ##### [cast()](#cast()) public
Converts a give value to a suitable database value based on type and return relevant internal statement type
* ##### [closeCursor()](#closeCursor()) public
Closes a cursor in the database, freeing up any resources and memory allocated to it. In most cases you don't need to call this method, as it is automatically called after fetching all results from the result set.
* ##### [columnCount()](#columnCount()) public
Returns the number of columns this statement's results will contain.
* ##### [count()](#count()) public
Statements can be passed as argument for count() to return the number for affected rows from last execution.
* ##### [errorCode()](#errorCode()) public
Returns the error code for the last error that occurred when executing this statement.
* ##### [errorInfo()](#errorInfo()) public
Returns the error information for the last error that occurred when executing this statement.
* ##### [execute()](#execute()) public
Executes the statement by sending the SQL query to the database. It can optionally take an array or arguments to be bound to the query variables. Please note that binding parameters from this method will not perform any custom type conversion as it would normally happen when calling `bindValue`.
* ##### [fetch()](#fetch()) public
Returns the next row for the result set after executing this statement. Rows can be fetched to contain columns as names or positions. If no rows are left in result set, this method will return false.
* ##### [fetchAll()](#fetchAll()) public
Returns an array with all rows resulting from executing this statement.
* ##### [fetchAssoc()](#fetchAssoc()) public
Returns the next row in a result set as an associative array. Calling this function is the same as calling $statement->fetch(StatementDecorator::FETCH\_TYPE\_ASSOC). If no results are found an empty array is returned.
* ##### [fetchColumn()](#fetchColumn()) public
Returns the value of the result at position.
* ##### [getInnerStatement()](#getInnerStatement()) public
Returns the statement object that was decorated by this class.
* ##### [getIterator()](#getIterator()) public
Statements are iterable as arrays, this method will return the iterator object for traversing all items in the result.
* ##### [lastInsertId()](#lastInsertId()) public
Returns the latest primary inserted using this statement.
* ##### [matchTypes()](#matchTypes()) public
Matches columns to corresponding types
* ##### [rowCount()](#rowCount()) public
Returns the number of rows returned of affected by last execution
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Database\StatementInterface $statement, Cake\Database\DriverInterface $driver)
```
Constructor
#### Parameters
`Cake\Database\StatementInterface` $statement Statement implementation such as PDOStatement.
`Cake\Database\DriverInterface` $driver Driver instance
### \_\_get() public
```
__get(string $property): string|null
```
Magic getter to return $queryString as read-only.
#### Parameters
`string` $property internal property to get
#### Returns
`string|null`
### bind() public
```
bind(array $params, array $types): void
```
Binds a set of values to statement object with corresponding type.
#### Parameters
`array` $params list of values to be bound
`array` $types list of types to be used, keys should match those in $params
#### Returns
`void`
### bindValue() public
```
bindValue(string|int $column, mixed $value, string|int|null $type = 'string'): void
```
Assign a value to a positional or named variable in prepared query. If using positional variables you need to start with index one, if using named params then just use the name in any order.
It is not allowed to combine positional and named variables in the same statement.
### Examples:
```
$statement->bindValue(1, 'a title');
$statement->bindValue('active', true, 'boolean');
$statement->bindValue(5, new \DateTime(), 'date');
```
#### Parameters
`string|int` $column name or param position to be bound
`mixed` $value The value to bind to variable in query
`string|int|null` $type optional name of configured Type class
#### Returns
`void`
### bufferResults() public
```
bufferResults(bool $buffer): $this
```
Whether to buffer results in php
#### Parameters
`bool` $buffer Toggle buffering
#### Returns
`$this`
### cast() public
```
cast(mixed $value, Cake\Database\TypeInterface|string|int $type = 'string'): array
```
Converts a give value to a suitable database value based on type and return relevant internal statement type
#### Parameters
`mixed` $value The value to cast
`Cake\Database\TypeInterface|string|int` $type optional The type name or type instance to use.
#### Returns
`array`
### closeCursor() public
```
closeCursor(): void
```
Closes a cursor in the database, freeing up any resources and memory allocated to it. In most cases you don't need to call this method, as it is automatically called after fetching all results from the result set.
#### Returns
`void`
### columnCount() public
```
columnCount(): int
```
Returns the number of columns this statement's results will contain.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
echo $statement->columnCount(); // outputs 2
```
#### Returns
`int`
### count() public
```
count(): int
```
Statements can be passed as argument for count() to return the number for affected rows from last execution.
#### Returns
`int`
### errorCode() public
```
errorCode(): string|int
```
Returns the error code for the last error that occurred when executing this statement.
#### Returns
`string|int`
### errorInfo() public
```
errorInfo(): array
```
Returns the error information for the last error that occurred when executing this statement.
#### Returns
`array`
### execute() public
```
execute(array|null $params = null): bool
```
Executes the statement by sending the SQL query to the database. It can optionally take an array or arguments to be bound to the query variables. Please note that binding parameters from this method will not perform any custom type conversion as it would normally happen when calling `bindValue`.
#### Parameters
`array|null` $params optional #### Returns
`bool`
### fetch() public
```
fetch(string|int $type = self::FETCH_TYPE_NUM): mixed
```
Returns the next row for the result set after executing this statement. Rows can be fetched to contain columns as names or positions. If no rows are left in result set, this method will return false.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->fetch('assoc')); // will show ['id' => 1, 'title' => 'a title']
```
#### Parameters
`string|int` $type optional 'num' for positional columns, assoc for named columns
#### Returns
`mixed`
### fetchAll() public
```
fetchAll(string|int $type = self::FETCH_TYPE_NUM): array|false
```
Returns an array with all rows resulting from executing this statement.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->fetchAll('assoc')); // will show [0 => ['id' => 1, 'title' => 'a title']]
```
#### Parameters
`string|int` $type optional num for fetching columns as positional keys or assoc for column names as keys
#### Returns
`array|false`
### fetchAssoc() public
```
fetchAssoc(): array
```
Returns the next row in a result set as an associative array. Calling this function is the same as calling $statement->fetch(StatementDecorator::FETCH\_TYPE\_ASSOC). If no results are found an empty array is returned.
#### Returns
`array`
### fetchColumn() public
```
fetchColumn(int $position): mixed
```
Returns the value of the result at position.
#### Parameters
`int` $position The numeric position of the column to retrieve in the result
#### Returns
`mixed`
### getInnerStatement() public
```
getInnerStatement(): Cake\Database\StatementInterface
```
Returns the statement object that was decorated by this class.
#### Returns
`Cake\Database\StatementInterface`
### getIterator() public
```
getIterator(): Cake\Database\StatementInterface
```
Statements are iterable as arrays, this method will return the iterator object for traversing all items in the result.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
foreach ($statement as $row) {
//do stuff
}
```
#### Returns
`Cake\Database\StatementInterface`
### lastInsertId() public
```
lastInsertId(string|null $table = null, string|null $column = null): string|int
```
Returns the latest primary inserted using this statement.
#### Parameters
`string|null` $table optional table name or sequence to get last insert value from
`string|null` $column optional the name of the column representing the primary key
#### Returns
`string|int`
### matchTypes() public
```
matchTypes(array $columns, array $types): array
```
Matches columns to corresponding types
Both $columns and $types should either be numeric based or string key based at the same time.
#### Parameters
`array` $columns list or associative array of columns and parameters to be bound with types
`array` $types list or associative array of types
#### Returns
`array`
### rowCount() public
```
rowCount(): int
```
Returns the number of rows returned of affected by last execution
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->rowCount()); // will show 1
```
#### Returns
`int`
Property Detail
---------------
### $\_bufferResults protected
Whether to buffer results in php
#### Type
`bool`
### $\_driver protected
Reference to the driver object associated to this statement.
#### Type
`Cake\Database\DriverInterface`
### $\_hasExecuted protected
Whether this statement has already been executed
#### Type
`bool`
### $\_statement protected
Statement instance implementation, such as PDOStatement or any other custom implementation.
#### Type
`Cake\Database\StatementInterface`
### $queryString public @property-read
#### Type
`string`
cakephp Namespace Formatter Namespace Formatter
===================
### Classes
* ##### [IcuFormatter](class-cake.i18n.formatter.icuformatter)
A formatter that will interpolate variables using the MessageFormatter class
* ##### [SprintfFormatter](class-cake.i18n.formatter.sprintfformatter)
A formatter that will interpolate variables using sprintf and select the correct plural form when required
cakephp Class FallbackPasswordHasher Class FallbackPasswordHasher
=============================
A password hasher that can use multiple different hashes where only one is the preferred one. This is useful when trying to migrate an existing database of users from one password type to another.
**Namespace:** [Cake\Auth](namespace-cake.auth)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this object.
* [$\_hashers](#%24_hashers) protected `arrayCake\Auth\AbstractPasswordHasher>` Holds the list of password hasher objects that will be used
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [check()](#check()) public
Verifies that the provided password corresponds to its hashed version
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [hash()](#hash()) public
Generates password hash.
* ##### [needsRehash()](#needsRehash()) public
Returns true if the password need to be rehashed, with the first hasher present in the list of hashers
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional configuration options for this object. Requires the `hashers` key to be present in the array with a list of other hashers to be used.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### check() public
```
check(string $password, string $hashedPassword): bool
```
Verifies that the provided password corresponds to its hashed version
This will iterate over all configured hashers until one of them returns true.
#### Parameters
`string` $password Plain text password to hash.
`string` $hashedPassword Existing hashed password.
#### Returns
`bool`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
```
$this->configShallow('key', $value);
```
Setting a nested value:
```
$this->configShallow('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->configShallow(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### Usage
Reading the whole config:
```
$this->getConfig();
```
Reading a specific value:
```
$this->getConfig('key');
```
Reading a nested value:
```
$this->getConfig('some.nested.key');
```
Reading with default value:
```
$this->getConfig('some-key', 'default-value');
```
#### Parameters
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### hash() public
```
hash(string $password): string|false
```
Generates password hash.
Uses the first password hasher in the list to generate the hash
#### Parameters
`string` $password Plain text password to hash.
#### Returns
`string|false`
### needsRehash() public
```
needsRehash(string $password): bool
```
Returns true if the password need to be rehashed, with the first hasher present in the list of hashers
Returns true by default since the only implementation users should rely on is the one provided by default in php 5.5+ or any compatible library
#### Parameters
`string` $password The password to verify
#### Returns
`bool`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### Usage
Setting a specific value:
```
$this->setConfig('key', $value);
```
Setting a nested value:
```
$this->setConfig('some.nested.key', $value);
```
Updating multiple config settings at the same time:
```
$this->setConfig(['one' => 'value', 'another' => 'value']);
```
#### Parameters
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this object.
These are merged with user-provided config when the object is used.
#### Type
`array<string, mixed>`
### $\_hashers protected
Holds the list of password hasher objects that will be used
#### Type
`arrayCake\Auth\AbstractPasswordHasher>`
| programming_docs |
cakephp Class Runner Class Runner
=============
Executes the middleware queue and provides the `next` callable that allows the queue to be iterated.
**Namespace:** [Cake\Http](namespace-cake.http)
Property Summary
----------------
* [$fallbackHandler](#%24fallbackHandler) protected `Psr\Http\Server\RequestHandlerInterface|null` Fallback handler to use if middleware queue does not generate response.
* [$queue](#%24queue) protected `Cake\Http\MiddlewareQueue` The middleware queue being run.
Method Summary
--------------
* ##### [handle()](#handle()) public
Handle incoming server request and return a response.
* ##### [run()](#run()) public
Method Detail
-------------
### handle() public
```
handle(ServerRequestInterface $request): Psr\Http\Message\ResponseInterface
```
Handle incoming server request and return a response.
May call other collaborating code to generate the response.
#### Parameters
`ServerRequestInterface` $request The server request
#### Returns
`Psr\Http\Message\ResponseInterface`
### run() public
```
run(Cake\Http\MiddlewareQueue $queue, Psr\Http\Message\ServerRequestInterface $request, Psr\Http\Server\RequestHandlerInterface|null $fallbackHandler = null): Psr\Http\Message\ResponseInterface
```
#### Parameters
`Cake\Http\MiddlewareQueue` $queue The middleware queue
`Psr\Http\Message\ServerRequestInterface` $request The Server Request
`Psr\Http\Server\RequestHandlerInterface|null` $fallbackHandler optional Fallback request handler.
#### Returns
`Psr\Http\Message\ResponseInterface`
Property Detail
---------------
### $fallbackHandler protected
Fallback handler to use if middleware queue does not generate response.
#### Type
`Psr\Http\Server\RequestHandlerInterface|null`
### $queue protected
The middleware queue being run.
#### Type
`Cake\Http\MiddlewareQueue`
cakephp Class MissingDriverException Class MissingDriverException
=============================
Class MissingDriverException
**Namespace:** [Cake\Database\Exception](namespace-cake.database.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional Either the string of the error message, or an array of attributes that are made available in the view, and sprintf()'d into Exception::$\_messageTemplate
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Interface SchemaInterface Interface SchemaInterface
==========================
An interface used by TableSchema objects.
**Namespace:** [Cake\Datasource](namespace-cake.datasource)
Method Summary
--------------
* ##### [addColumn()](#addColumn()) public
Add a column to the table.
* ##### [baseColumnType()](#baseColumnType()) public
Returns the base type name for the provided column. This represent the database type a more complex class is based upon.
* ##### [columns()](#columns()) public
Get the column names in the table.
* ##### [defaultValues()](#defaultValues()) public
Get a hash of columns and their default values.
* ##### [getColumn()](#getColumn()) public
Get column data in the table.
* ##### [getColumnType()](#getColumnType()) public
Returns column type or null if a column does not exist.
* ##### [getOptions()](#getOptions()) public
Gets the options for a table.
* ##### [hasColumn()](#hasColumn()) public
Returns true if a column exists in the schema.
* ##### [isNullable()](#isNullable()) public
Check whether a field is nullable
* ##### [name()](#name()) public
Get the name of the table.
* ##### [removeColumn()](#removeColumn()) public
Remove a column from the table schema.
* ##### [setColumnType()](#setColumnType()) public
Sets the type of a column.
* ##### [setOptions()](#setOptions()) public
Sets the options for a table.
* ##### [typeMap()](#typeMap()) public
Returns an array where the keys are the column names in the schema and the values the database type they have.
Method Detail
-------------
### addColumn() public
```
addColumn(string $name, array<string, mixed>|string $attrs): $this
```
Add a column to the table.
### Attributes
Columns can have several attributes:
* `type` The type of the column. This should be one of CakePHP's abstract types.
* `length` The length of the column.
* `precision` The number of decimal places to store for float and decimal types.
* `default` The default value of the column.
* `null` Whether the column can hold nulls.
* `fixed` Whether the column is a fixed length column. This is only present/valid with string columns.
* `unsigned` Whether the column is an unsigned column. This is only present/valid for integer, decimal, float columns.
In addition to the above keys, the following keys are implemented in some database dialects, but not all:
* `comment` The comment for the column.
#### Parameters
`string` $name The name of the column
`array<string, mixed>|string` $attrs The attributes for the column or the type name.
#### Returns
`$this`
### baseColumnType() public
```
baseColumnType(string $column): string|null
```
Returns the base type name for the provided column. This represent the database type a more complex class is based upon.
#### Parameters
`string` $column The column name to get the base type from
#### Returns
`string|null`
### columns() public
```
columns(): array<string>
```
Get the column names in the table.
#### Returns
`array<string>`
### defaultValues() public
```
defaultValues(): array<string, mixed>
```
Get a hash of columns and their default values.
#### Returns
`array<string, mixed>`
### getColumn() public
```
getColumn(string $name): array<string, mixed>|null
```
Get column data in the table.
#### Parameters
`string` $name The column name.
#### Returns
`array<string, mixed>|null`
### getColumnType() public
```
getColumnType(string $name): string|null
```
Returns column type or null if a column does not exist.
#### Parameters
`string` $name The column to get the type of.
#### Returns
`string|null`
### getOptions() public
```
getOptions(): array<string, mixed>
```
Gets the options for a table.
Table options allow you to set platform specific table level options. For example the engine type in MySQL.
#### Returns
`array<string, mixed>`
### hasColumn() public
```
hasColumn(string $name): bool
```
Returns true if a column exists in the schema.
#### Parameters
`string` $name Column name.
#### Returns
`bool`
### isNullable() public
```
isNullable(string $name): bool
```
Check whether a field is nullable
Missing columns are nullable.
#### Parameters
`string` $name The column to get the type of.
#### Returns
`bool`
### name() public
```
name(): string
```
Get the name of the table.
#### Returns
`string`
### removeColumn() public
```
removeColumn(string $name): $this
```
Remove a column from the table schema.
If the column is not defined in the table, no error will be raised.
#### Parameters
`string` $name The name of the column
#### Returns
`$this`
### setColumnType() public
```
setColumnType(string $name, string $type): $this
```
Sets the type of a column.
#### Parameters
`string` $name The column to set the type of.
`string` $type The type to set the column to.
#### Returns
`$this`
### setOptions() public
```
setOptions(array<string, mixed> $options): $this
```
Sets the options for a table.
Table options allow you to set platform specific table level options. For example the engine type in MySQL.
#### Parameters
`array<string, mixed>` $options The options to set, or null to read options.
#### Returns
`$this`
### typeMap() public
```
typeMap(): array<string, string>
```
Returns an array where the keys are the column names in the schema and the values the database type they have.
#### Returns
`array<string, string>`
cakephp Class CsrfProtectionMiddleware Class CsrfProtectionMiddleware
===============================
Provides CSRF protection & validation.
This middleware adds a CSRF token to a cookie. The cookie value is compared to token in request data, or the X-CSRF-Token header on each PATCH, POST, PUT, or DELETE request. This is known as "double submit cookie" technique.
If the request data is missing or does not match the cookie data, an InvalidCsrfTokenException will be raised.
This middleware integrates with the FormHelper automatically and when used together your forms will have CSRF tokens automatically added when `$this->Form->create(...)` is used in a view.
**Namespace:** [Cake\Http\Middleware](namespace-cake.http.middleware)
**See:** https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site\_Request\_Forgery\_Prevention\_Cheat\_Sheet.html#double-submit-cookie
Constants
---------
* `int` **TOKEN\_VALUE\_LENGTH**
```
16
```
* `int` **TOKEN\_WITH\_CHECKSUM\_LENGTH**
```
56
```
Tokens have an hmac generated so we can ensure that tokens were generated by our application.
Should be TOKEN\_VALUE\_LENGTH + strlen(hmac)
We are currently using sha1 for the hmac which creates 40 bytes.
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Config for the CSRF handling.
* [$skipCheckCallback](#%24skipCheckCallback) protected `callable|null` Callback for deciding whether to skip the token check for particular request.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_addTokenCookie()](#_addTokenCookie()) protected
Add a CSRF token to the response cookies.
* ##### [\_createCookie()](#_createCookie()) protected
Create response cookie
* ##### [\_createToken()](#_createToken()) protected deprecated
Create a new token to be used for CSRF protection
* ##### [\_unsetTokenField()](#_unsetTokenField()) protected
Remove CSRF protection token from request data.
* ##### [\_validateToken()](#_validateToken()) protected
Validate the request data against the cookie token.
* ##### [\_verifyToken()](#_verifyToken()) protected
Verify that CSRF token was originally generated by the receiving application.
* ##### [createToken()](#createToken()) public
Create a new token to be used for CSRF protection
* ##### [isHexadecimalToken()](#isHexadecimalToken()) protected
Test if the token predates salted tokens.
* ##### [process()](#process()) public
Checks and sets the CSRF token depending on the HTTP verb.
* ##### [saltToken()](#saltToken()) public
Apply entropy to a CSRF token
* ##### [skipCheckCallback()](#skipCheckCallback()) public
Set callback for allowing to skip token check for particular request.
* ##### [unsaltToken()](#unsaltToken()) public
Remove the salt from a CSRF token.
* ##### [whitelistCallback()](#whitelistCallback()) public deprecated
Set callback for allowing to skip token check for particular request.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional Config options. See $\_config for valid keys.
### \_addTokenCookie() protected
```
_addTokenCookie(string $token, Psr\Http\Message\ServerRequestInterface $request, Psr\Http\Message\ResponseInterface $response): Psr\Http\Message\ResponseInterface
```
Add a CSRF token to the response cookies.
#### Parameters
`string` $token The token to add.
`Psr\Http\Message\ServerRequestInterface` $request The request to validate against.
`Psr\Http\Message\ResponseInterface` $response The response.
#### Returns
`Psr\Http\Message\ResponseInterface`
### \_createCookie() protected
```
_createCookie(string $value, Psr\Http\Message\ServerRequestInterface $request): Cake\Http\Cookie\CookieInterface
```
Create response cookie
#### Parameters
`string` $value Cookie value
`Psr\Http\Message\ServerRequestInterface` $request The request object.
#### Returns
`Cake\Http\Cookie\CookieInterface`
### \_createToken() protected
```
_createToken(): string
```
Create a new token to be used for CSRF protection
#### Returns
`string`
### \_unsetTokenField() protected
```
_unsetTokenField(Psr\Http\Message\ServerRequestInterface $request): Psr\Http\Message\ServerRequestInterface
```
Remove CSRF protection token from request data.
#### Parameters
`Psr\Http\Message\ServerRequestInterface` $request The request object.
#### Returns
`Psr\Http\Message\ServerRequestInterface`
### \_validateToken() protected
```
_validateToken(Psr\Http\Message\ServerRequestInterface $request): void
```
Validate the request data against the cookie token.
#### Parameters
`Psr\Http\Message\ServerRequestInterface` $request The request to validate against.
#### Returns
`void`
#### Throws
`Cake\Http\Exception\InvalidCsrfTokenException`
When the CSRF token is invalid or missing. ### \_verifyToken() protected
```
_verifyToken(string $token): bool
```
Verify that CSRF token was originally generated by the receiving application.
#### Parameters
`string` $token The CSRF token.
#### Returns
`bool`
### createToken() public
```
createToken(): string
```
Create a new token to be used for CSRF protection
#### Returns
`string`
### isHexadecimalToken() protected
```
isHexadecimalToken(string $token): bool
```
Test if the token predates salted tokens.
These tokens are hexadecimal values and equal to the token with checksum length. While they are vulnerable to BREACH they should rotate over time and support will be dropped in 5.x.
#### Parameters
`string` $token The token to test.
#### Returns
`bool`
### process() public
```
process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface
```
Checks and sets the CSRF token depending on the HTTP verb.
Processes an incoming server request in order to produce a response. If unable to produce the response itself, it may delegate to the provided request handler to do so.
#### Parameters
`ServerRequestInterface` $request The request.
`RequestHandlerInterface` $handler The request handler.
#### Returns
`Psr\Http\Message\ResponseInterface`
### saltToken() public
```
saltToken(string $token): string
```
Apply entropy to a CSRF token
To avoid BREACH apply a random salt value to a token When the token is compared to the session the token needs to be unsalted.
#### Parameters
`string` $token The token to salt.
#### Returns
`string`
### skipCheckCallback() public
```
skipCheckCallback(callable $callback): $this
```
Set callback for allowing to skip token check for particular request.
The callback will receive request instance as argument and must return `true` if you want to skip token check for the current request.
#### Parameters
`callable` $callback A callable.
#### Returns
`$this`
### unsaltToken() public
```
unsaltToken(string $token): string
```
Remove the salt from a CSRF token.
If the token is not TOKEN\_VALUE\_LENGTH \* 2 it is an old unsalted value that is supported for backwards compatibility.
#### Parameters
`string` $token The token that could be salty.
#### Returns
`string`
### whitelistCallback() public
```
whitelistCallback(callable $callback): $this
```
Set callback for allowing to skip token check for particular request.
The callback will receive request instance as argument and must return `true` if you want to skip token check for the current request.
#### Parameters
`callable` $callback A callable.
#### Returns
`$this`
Property Detail
---------------
### $\_config protected
Config for the CSRF handling.
* `cookieName` The name of the cookie to send.
+ `expiry` A strotime compatible value of how long the CSRF token should last. Defaults to browser session.
+ `secure` Whether the cookie will be set with the Secure flag. Defaults to false.
+ `httponly` Whether the cookie will be set with the HttpOnly flag. Defaults to false.
+ `samesite` "SameSite" attribute for cookies. Defaults to `null`. Valid values: `CookieInterface::SAMESITE_LAX`, `CookieInterface::SAMESITE_STRICT`, `CookieInterface::SAMESITE_NONE` or `null`.
+ `field` The form field to check. Changing this will also require configuring FormHelper.
#### Type
`array<string, mixed>`
### $skipCheckCallback protected
Callback for deciding whether to skip the token check for particular request.
CSRF protection token check will be skipped if the callback returns `true`.
#### Type
`callable|null`
cakephp Class ConsoleException Class ConsoleException
=======================
Exception class for Console libraries. This exception will be thrown from Console library classes when they encounter an error.
**Namespace:** [Cake\Console\Exception](namespace-cake.console.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional Either the string of the error message, or an array of attributes that are made available in the view, and sprintf()'d into Exception::$\_messageTemplate
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
| programming_docs |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.