

C Programming Language
======================

 The interface of C standard library is defined by the following collection of headers.




|  |  |
| --- | --- |
| [`<assert.h>`](error "c/error") | [Conditionally compiled macro that compares its argument to zero](error "c/error") |
| [`<complex.h>`](numeric/complex "c/numeric/complex") (since C99) | [Complex number arithmetic](numeric/complex "c/numeric/complex") |
| [`<ctype.h>`](string/byte "c/string/byte") | [Functions to determine the type contained in character data](string/byte "c/string/byte") |
| [`<errno.h>`](error "c/error") | [Macros reporting error conditions](error "c/error") |
| [`<fenv.h>`](numeric/fenv "c/numeric/fenv") (since C99) | [Floating-point environment](numeric/fenv "c/numeric/fenv") |
| [`<float.h>`](types/limits#Limits_of_floating_point_types "c/types/limits") | [Limits of floating-point types](types/limits#Limits_of_floating_point_types "c/types/limits") |
| [`<inttypes.h>`](types/integer "c/types/integer") (since C99) | [Format conversion of integer types](types/integer "c/types/integer") |
| [`<iso646.h>`](language/operator_alternative "c/language/operator alternative") (since C95) | [Alternative operator spellings](language/operator_alternative "c/language/operator alternative") |
| [`<limits.h>`](types/limits "c/types/limits") | [Ranges of integer types](types/limits "c/types/limits") |
| [`<locale.h>`](locale "c/locale") | [Localization utilities](locale "c/locale") |
| [`<math.h>`](numeric/math "c/numeric/math") | [Common mathematics functions](numeric/math "c/numeric/math") |
| [`<setjmp.h>`](program "c/program") | [Nonlocal jumps](program "c/program") |
| [`<signal.h>`](program "c/program") | [Signal handling](program "c/program") |
| [`<stdalign.h>`](types "c/types") (since C11) | [`alignas` and `alignof`](types "c/types") convenience macros  |
| [`<stdarg.h>`](variadic "c/variadic") | [Variable arguments](variadic "c/variadic") |
| [`<stdatomic.h>`](thread#Atomic_operations "c/thread") (since C11) | [Atomic operations](thread#Atomic_operations "c/thread") |
| `<stdbit.h>` (since C23) |  Macros to work with the byte and bit representations of types  |
| [`<stdbool.h>`](types "c/types") (since C99) | [Macros for boolean type](types "c/types") |
| `<stdckdint.h>` (since C23) |  macros for performing checked integer arithmetic  |
| [`<stddef.h>`](types "c/types") | [Common macro definitions](types "c/types") |
| [`<stdint.h>`](types/integer "c/types/integer") (since C99) | [Fixed-width integer types](types/integer "c/types/integer") |
| [`<stdio.h>`](io "c/io") | [Input/output](io "c/io") |
| [`<stdlib.h>`](program "c/program") |  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") |
| [`<stdnoreturn.h>`](language/_noreturn "c/language/ Noreturn") (since C11) | [`noreturn`](language/_noreturn "c/language/ Noreturn") convenience macro  |
| [`<string.h>`](string/byte "c/string/byte") | [String handling](string/byte "c/string/byte") |
| [`<tgmath.h>`](numeric/tgmath "c/numeric/tgmath") (since C99) | [Type-generic math](numeric/tgmath "c/numeric/tgmath") (macros wrapping math.h and complex.h)  |
| [`<threads.h>`](thread "c/thread") (since C11) | [Thread library](thread "c/thread") |
| [`<time.h>`](chrono "c/chrono") | [Time/date utilities](chrono "c/chrono") |
| [`<uchar.h>`](string/multibyte "c/string/multibyte") (since C11) | [UTF-16 and UTF-32 character utilities](string/multibyte "c/string/multibyte") |
| [`<wchar.h>`](string/wide "c/string/wide") (since C95) | [Extended multibyte and wide character utilities](string/wide "c/string/wide") |
| [`<wctype.h>`](string/wide "c/string/wide") (since C95) | [Functions to determine the type contained in wide character data](string/wide "c/string/wide") |

 ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.1.2 Standard headers

* C17 standard (ISO/IEC 9899:2018):
+ 7.1.2 Standard headers (p: 131-132)

* C11 standard (ISO/IEC 9899:2011):
+ 7.1.2 Standard headers (p: 181-182)

* C99 standard (ISO/IEC 9899:1999):
+ 7.1.2 Standard headers (p: 165)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.1.2 Standard headers

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/header "cpp/header") for C++ Standard Library header files |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/header>

C language
==========

 This is a reference of the core C language constructs.




|  |  |  |
| --- | --- | --- |
|  **[Basic concepts](language/basic_concepts "c/language/basic concepts")**.
 [Comments](comment "c/comment")  [ASCII chart](language/ascii "c/language/ascii")  [Character sets and encodings](language/charset "c/language/charset")  [Translation phases](language/translation_phases "c/language/translation phases")  [Punctuation](language/punctuators "c/language/punctuators")  [Identifier](language/identifier "c/language/identifier")  -  [Scope](language/scope "c/language/scope") -  [Lifetime](language/lifetime "c/language/lifetime")  [Lookup and Name Spaces](language/name_space "c/language/name space")  [Type](language/type "c/language/type") -  [Arithmetic types](language/arithmetic_types "c/language/arithmetic types")  [Objects and Alignment](language/object "c/language/object")   [The `main` function](language/main_function "c/language/main function")  [As-if rule](language/as_if "c/language/as if")  [Undefined behavior](language/behavior "c/language/behavior")  [Memory model and Data races](language/memory_model "c/language/memory model").
 **[Keywords](keyword "c/keyword")**.
 **[Preprocessor](preprocessor "c/preprocessor")**.
 [`#if` - `#ifdef` - `#ifndef` - `#elif`](preprocessor/conditional "c/preprocessor/conditional")  [`#elifdef` - `#elifndef`](preprocessor/conditional "c/preprocessor/conditional")(C23)  [`#define` - `#` - `##`](preprocessor/replace "c/preprocessor/replace") [`#include`](preprocessor/include "c/preprocessor/include") - [`#pragma`](preprocessor/impl "c/preprocessor/impl") [`#line`](preprocessor/line "c/preprocessor/line") - [`#error`](preprocessor/error "c/preprocessor/error") [`#warning`](preprocessor/error "c/preprocessor/error")(C23) - [`#embed`](preprocessor/embed "c/preprocessor/embed")(C23).
 **[Statements](language/statements "c/language/statements")**.
[`if`](language/if "c/language/if") - [`switch`](language/switch "c/language/switch") [`for`](language/for "c/language/for") [`while`](language/while "c/language/while") - [`do`-`while`](language/do "c/language/do") [`continue`](language/continue "c/language/continue") - [`break`](language/break "c/language/break") [`goto`](language/goto "c/language/goto") - [`return`](language/return "c/language/return"). |  **[Expressions](language/expressions "c/language/expressions")**.
 [Value categories](language/value_category "c/language/value category")  [Evaluation order and sequencing](language/eval_order "c/language/eval order")  [Constants and literals](language/expressions#Constants_and_literals "c/language/expressions") [Integer constants](language/integer_constant "c/language/integer constant") [Floating constants](language/floating_constant "c/language/floating constant") [Character constants](language/character_constant "c/language/character constant") [`true`/`false`](language/bool_constant "c/language/bool constant")(C23) [`nullptr`](language/nullptr "c/language/nullptr")(C23) [String literals](language/string_literal "c/language/string literal") [Compound literals](language/compound_literal "c/language/compound literal")(C99)  [Constant expressions](language/constant_expression "c/language/constant expression")  [Implicit conversions](language/conversion "c/language/conversion")  [Operators](language/expressions#Operators "c/language/expressions")  [Member access and indirection](language/operator_member_access "c/language/operator member access")  [Logical](language/operator_logical "c/language/operator logical") -  [Comparison](language/operator_comparison "c/language/operator comparison")  [Arithmetic](language/operator_arithmetic "c/language/operator arithmetic") -  [Assignment](language/operator_assignment "c/language/operator assignment")  [Increment and Decrement](language/operator_incdec "c/language/operator incdec")  [Call, Comma, Ternary](language/operator_other "c/language/operator other") [`sizeof`](language/sizeof "c/language/sizeof") - [`_Alignof`](language/_alignof "c/language/ Alignof")(C11)  [Cast operators](language/cast "c/language/cast")  [Operator precedence](language/operator_precedence "c/language/operator precedence")  [Generic selection](language/generic "c/language/generic")(C11).
 **[Initialization](language/initialization "c/language/initialization")**.
 [Scalar](language/scalar_initialization "c/language/scalar initialization")  [Array](language/array_initialization "c/language/array initialization")  [Structure/Union](language/struct_initialization "c/language/struct initialization")  |  **[Declarations](language/declarations "c/language/declarations")**.
 [Pointers](language/pointer "c/language/pointer") -  [Arrays](language/array "c/language/array")  [Enumerations](language/enum "c/language/enum")  [Storage duration and Linkage](language/storage_duration "c/language/storage duration")  [`const`](language/const "c/language/const") - [`volatile`](language/volatile "c/language/volatile") - [`restrict`](language/restrict "c/language/restrict")(C99) [`struct`](language/struct "c/language/struct") - [`union`](language/union "c/language/union") -  [Bit-fields](language/bit_field "c/language/bit field") [`_Alignas`](language/_alignas "c/language/ Alignas")(C11) - [`typedef`](language/typedef "c/language/typedef") [`_Static_assert`](language/_static_assert "c/language/ Static assert")(C11)  [Atomic types](language/atomic "c/language/atomic")(C11)  [External and tentative definitions](language/extern "c/language/extern")  [Attributes](language/attributes "c/language/attributes")(C23).
 **[Functions](language/functions "c/language/functions")**.
 [Function declaration](language/function_declaration "c/language/function declaration")  [Function definition](language/function_definition "c/language/function definition") [`inline`](language/inline "c/language/inline")(C99) [`_Noreturn`](language/_noreturn "c/language/ Noreturn")(C11)(deprecated in C23)  [Variadic arguments](language/variadic "c/language/variadic").
**Miscellaneous**.
 [History of C](language/history "c/language/history")  [Conformance](language/conformance "c/language/conformance")  [Inline assembly](language/asm "c/language/asm")  [Signal handling](https://en.cppreference.com/mwiki/index.php?title=c/language/signal&action=edit&redlink=1 "c/language/signal (page does not exist)")   [Analyzability](language/analyzability "c/language/analyzability")(C11).
 |

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language "cpp/language") for C++ language constructs |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math>

Strings library
===============

 ###   [Null-terminated byte string management](string/byte "c/string/byte")

 ###   [Null-terminated multibyte string management](string/multibyte "c/string/multibyte")

 ###   [Null-terminated wide string management](string/wide "c/string/wide")

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/string "cpp/string") for Strings library |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string>

Error handling
==============

 ###  Error numbers

 

|  Defined in header `<errno.h>` |
| --- |
|  [errno](error/errno "c/error/errno") |  macro which expands to POSIX-compatible thread-local error number variable(macro variable) |
|  [E2BIG, EACCES, ..., EXDEV](error/errno_macros "c/error/errno macros") |  macros for standard POSIX-compatible error conditions  (macro constant) |

 ###  Assertions

 

|  Defined in header `<assert.h>` |
| --- |
|  [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) |
|  [static\_assert](error/static_assert "c/error/static assert")
(C11)(removed in C23) |  issues a compile-time diagnostic if the value of a constant expression is false  (keyword macro) |

 

|  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|  Bounds checking The standard library provides bounds-checked versions of some existing functions (`[gets\_s](io/gets "c/io/gets")`, `[fopen\_s](io/fopen "c/io/fopen")`, `[printf\_s](io/fprintf "c/io/fprintf")`, `[strcpy\_s](string/byte/strcpy "c/string/byte/strcpy")`, `[wcscpy\_s](string/wide/wcscpy "c/string/wide/wcscpy")`, `[mbstowcs\_s](string/multibyte/mbstowcs "c/string/multibyte/mbstowcs")`, `[qsort\_s](algorithm/qsort "c/algorithm/qsort")`, `[getenv\_s](program/getenv "c/program/getenv")`, etc). This functionality is *optional* and is only available if `__STDC_LIB_EXT1__` is defined. The following macros and functions support this functionality.

|  Defined in header `<errno.h>` |
| --- |
|  Defined in header `<stdio.h>` |
| errno\_t
(C11) |  a typedef for the type `int`, used to self-document functions that return `[errno](error/errno "c/error/errno")` values  (typedef) |
|  Defined in header `<stddef.h>` |
|  Defined in header `<stdio.h>` |
|  Defined in header `<stdlib.h>` |
|  Defined in header `<string.h>` |
|  Defined in header `<time.h>` |
|  Defined in header `<wchar.h>` |
| rsize\_t
(C11) |  a typedef for the same type as `[size\_t](types/size_t "c/types/size t")`, used to self-document functions that range-check their parameters at runtime  (typedef) |
|  Defined in header `<stdint.h>` |
| RSIZE\_MAX
(C11) |  largest acceptable size for bounds-checked functions, expands to either constant or variable which may change at runtime (e.g. as the currently allocated memory size changes)(macro variable) |
|  Defined in header `<stdlib.h>` |
|  [set\_constraint\_handler\_s](error/set_constraint_handler_s "c/error/set constraint handler s")
(C11) |  set the error callback for bounds-checked functions  (function) |
|  [abort\_handler\_s](error/abort_handler_s "c/error/abort handler s")
(C11) |  abort callback for the bounds-checked functions  (function) |
|  [ignore\_handler\_s](error/ignore_handler_s "c/error/ignore handler s")
(C11) |  ignore callback for the bounds-checked functions  (function) |

Note: implementations of bounds-checked functions are available as open-source libraries [Safe C](https://github.com/rurban/safeclib/) and [Slibc](https://code.google.com/archive/p/slibc/), and as part of Watcom C. There is also an incompatible set of bounds-checked functions available in Visual Studio. | (since C11) |

 ###  Notes

 Since C23, [`static_assert`](language/_static_assert "c/language/ Static assert") is itself a keyword, which may also be a predefined macro, so `<assert.h>` no longer provides it.


###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.2 Diagnostics <assert.h> (p: 186-187)
+ 7.5 Errors <errno.h> (p: 205)
+ 7.19 Common definitions <stddef.h> (p: 288)
+ 7.20 Integer types <stdint.h> (p: 289-295)
+ 7.21 Input/output <stdio.h> (p: 296-339)
+ 7.22 General utilities <stdlib.h> (p: 340-360)
+ K.3.1.3 Use of errno (p: 584)
+ K.3.2/2 errno\_t (p: 585)
+ K.3.3/2 rsize\_t (p: 585)
+ K.3.4/2 RSIZE\_MAX (p: 585)
+ 7.31.3 Errors <errno.h> (p: 455)
+ 7.31.10 Integer types <stdint.h> (p: 456)
+ 7.31.11 Input/output <stdio.h> (p: 456)
+ 7.31.12 General utilities <stdlib.h> (p: 456)

* C99 standard (ISO/IEC 9899:1999):
+ 7.2 Diagnostics <assert.h> (p: 169)
+ 7.5 Errors <errno.h> (p: 186)
+ 7.26.3 Errors <errno.h> (p: 401)
+ 7.26.8 Integer types <stdint.h> (p: 401)
+ 7.26.9 Input/output <stdio.h> (p: 402)
+ 7.26.10 General utilities <stdlib.h> (p: 402)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.2 DIAGNOSTICS <assert.h>
+ 4.1.3 Errors <errno.h>
+ 4.13.1 Errors <errno.h>
+ 4.13.6 Input/output <stdio.h>
+ 4.13.7 General utilities <stdlib.h>

 ###  See also

 

|  |  |
| --- | --- |
|  [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 "cpp/error") for Error handling |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/error>

Type support
============

 See also  [type system overview](language/types "c/language/types") and  [arithmetic types defined by the language](language/arithmetic_types "c/language/arithmetic types").


###  Basic types

 ####  Additional basic types and convenience macros

 

|  Defined in header `<stddef.h>` |
| --- |
|  [size\_t](types/size_t "c/types/size t") |  unsigned integer type returned by the [`sizeof`](language/sizeof "c/language/sizeof") operator  (typedef) |
|  [ptrdiff\_t](types/ptrdiff_t "c/types/ptrdiff t") |  signed integer type returned when subtracting two pointers  (typedef) |
|  [nullptr\_t](types/nullptr_t "c/types/nullptr t")
(C23) |  the type of the predefined null pointer constant [`nullptr`](language/nullptr "c/language/nullptr")  (typedef) |
|  [NULL](types/null "c/types/NULL") |  implementation-defined null pointer constant  (macro constant) |
|  [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) |
|  [offsetof](types/offsetof "c/types/offsetof") |  byte offset from the beginning of a struct type to specified member  (function macro) |
|  Defined in header `<stdbool.h>` |
| bool
(C99)(removed in C23) |  convenience macro, expands to [`_Bool`](keyword/_bool "c/keyword/ Bool")  (keyword macro) |
| true
(C99)(removed in C23) |  expands to integer constant `1`  (macro constant) |
| false
(C99)(removed in C23) |  expands to integer constant `0`  (macro constant) |
| \_\_bool\_true\_false\_are\_defined
(C99)(deprecated in C23) |  expands to integer constant `1`  (macro constant) |
|  Defined in header `<stdalign.h>` |
| alignas
(C11)(removed in C23) |  convenience macro, expands to keyword [`_Alignas`](keyword/_alignas "c/keyword/ Alignas")  (keyword macro) |
| alignof
(C11)(removed in C23) |  convenience macro, expands to keyword [`_Alignof`](keyword/_alignof "c/keyword/ Alignof")  (keyword macro) |
| \_\_alignas\_is\_defined
(C11)(removed in C23) |  expands to integer constant `1`  (macro constant) |
| \_\_alignof\_is\_defined
(C11)(removed in C23) |  expands to integer constant `1`  (macro constant) |
|  Defined in header `<stdnoreturn.h>` |
| noreturn
(C11)(deprecated in C23) |  convenience macro, expands to [`_Noreturn`](keyword/_noreturn "c/keyword/ Noreturn")  (keyword macro) |

 ####   [Fixed width integer types](types/integer "c/types/integer") (since C99)

 ####   [Numeric limits](types/limits "c/types/limits")

 ###  Notes

 

|  |  |
| --- | --- |
| The type of `true` and `false` is `int` rather than `_Bool`.
A program may undefine and perhaps then redefine the macros `bool`, `true` and `false`. However, such ability is a deprecated feature. | (since C99)(until C23) |
| The type of `true` and `false` is `bool`. It is unspecified whether any of `bool`, `_Bool`, `true`, or `false` is implemented as a predefined macro.
If `bool`, `true`, or `false` (but not `_Bool`) is defined as a predefined macro, a program may undefine and perhaps redefine it. | (since C23) |

 ###  Example

  
```
#include <stdio.h>
#include <stdbool.h>
#include <stdalign.h>
 
int main(void)
{
    printf("%d %d %d\n", true && false, true || false, !false);
    printf("%d %d\n", true ^ true, true + true);
    printf("%zu\n", alignof(short));
}
```
 Possible output:



```
0 1 1
0 2
2
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.15 Alignment <stdalign.h> (p: 196)
+ 7.18 Boolean type and values <stdbool.h> (p: 210)
+ 7.19 Common definitions <stddef.h> (p: 211)
+ 7.23 \_Noreturn <stdnoreturn.h> (p: 263)
+ 7.31.9 Boolean type and values <stdbool.h> (p: 332)

* C11 standard (ISO/IEC 9899:2011):
+ 7.15 Alignment <stdalign.h> (p: 268)
+ 7.18 Boolean type and values <stdbool.h> (p: 287)
+ 7.19 Common definitions <stddef.h> (p: 288)
+ 7.23 \_Noreturn <stdnoreturn.h> (p: 361)
+ 7.31.9 Boolean type and values <stdbool.h> (p: 456)

* C99 standard (ISO/IEC 9899:1999):
+ 7.18 Boolean type and values <stdbool.h> (p: 253)
+ 7.19 Common definitions <stddef.h> (p: 254)
+ 7.26.7 Boolean type and values <stdbool.h> (p: 401)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.1.5 Common definitions <stddef.h>

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/types "cpp/types") for Type support library |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/types>

Program support utilities
=========================

 ###  Program termination

 The following functions manage program termination and resources cleanup.




|  Defined in header `<stdlib.h>` |
| --- |
|  [abort](program/abort "c/program/abort") |  causes abnormal program termination (without cleaning up)  (function) |
|  [exit](program/exit "c/program/exit") |  causes normal program termination with cleaning up  (function) |
|  [quick\_exit](program/quick_exit "c/program/quick exit")
(C11) |  causes normal program termination without completely cleaning up  (function) |
|  [\_Exit](program/_exit "c/program/ Exit")
(C99) |  causes normal program termination without cleaning up  (function) |
|  [atexit](program/atexit "c/program/atexit") |  registers a function to be called on `[exit()](program/exit "c/program/exit")` invocation  (function) |
|  [at\_quick\_exit](program/at_quick_exit "c/program/at quick exit")
(C11) |  registers a function to be called on [`quick_exit`](program/quick_exit "c/program/quick exit") invocation  (function) |
|  [EXIT\_SUCCESSEXIT\_FAILURE](program/exit_status "c/program/EXIT status") |  indicates program execution execution status  (macro constant) |

 ###  Unreachable control flow

 

|  Defined in header `<stddef.h>` |
| --- |
|  [unreachable](program/unreachable "c/program/unreachable")
(C23) |  marks unreachable point of execution  (function macro) |

 ###  Communicating with the environment

 

|  Defined in header `<stdlib.h>` |
| --- |
|  [system](program/system "c/program/system") |  calls the host environment's command processor  (function) |
|  [getenvgetenv\_s](program/getenv "c/program/getenv")
(C11) |  access to the list of environment variables  (function) |

 ###  Signals

 Several functions and macro constants for signal management are provided.




|  Defined in header `<signal.h>` |
| --- |
|  [signal](program/signal "c/program/signal") |  sets a signal handler for particular signal  (function) |
|  [raise](program/raise "c/program/raise") |  runs the signal handler for particular signal  (function) |
|  [sig\_atomic\_t](program/sig_atomic_t "c/program/sig atomic t") |  the integer type that can be accessed as an atomic entity from an asynchronous signal handler  (typedef) |
|  [SIG\_DFLSIG\_IGN](program/sig_strategies "c/program/SIG strategies") |  defines signal handling strategies  (macro constant) |
|  [SIG\_ERR](program/sig_err "c/program/SIG ERR") |  error was encountered  (macro constant) |
|  Signal types  |
|  [SIGABRTSIGFPESIGILLSIGINTSIGSEGVSIGTERM](program/sig_types "c/program/SIG types") |  defines signal types  (macro constant) |

 ###  Non-local jumps

 

|  Defined in header `<setjmp.h>` |
| --- |
|  [setjmp](program/setjmp "c/program/setjmp") |  saves the context  (function macro) |
|  [longjmp](program/longjmp "c/program/longjmp") |  jumps to specified location  (function) |
|  Types  |
|  [jmp\_buf](program/jmp_buf "c/program/jmp buf") |  execution context type  (typedef) |

 ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.13 Nonlocal jumps <setjmp.h> (p: 191-192)
+ 7.14 Signal handling <signal.h> (p: 193-195)
+ 7.22 General utilities <stdlib.h> (p: 248-262)
+ 7.31.7 Signal handling <signal.h> (p: 332)
+ 7.31.12 General utilities <stdlib.h> (p: 333)

* C11 standard (ISO/IEC 9899:2011):
+ 7.13 Nonlocal jumps <setjmp.h> (p: 262-264)
+ 7.14 Signal handling <signal.h> (p: 265-267)
+ 7.22 General utilities <stdlib.h> (p: 340-360)
+ 7.31.7 Signal handling <signal.h> (p: 455)
+ 7.31.12 General utilities <stdlib.h> (p: 456)

* C99 standard (ISO/IEC 9899:1999):
+ 7.13 Nonlocal jumps <setjmp.h> (p: 243-245)
+ 7.14 Signal handling <signal.h> (p: 246-248)
+ 7.20 General utilities <stdlib.h> (p: 306-324)
+ 7.26.6 Signal handling <signal.h> (p: 401)
+ 7.26.10 General utilities <stdlib.h> (p: 402)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.6 NON-LOCAL JUMPS <setjmp.h>
+ 4.7 SIGNAL HANDLING <signal.h>
+ 4.10 GENERAL UTILITIES <stdlib.h>
+ 4.13.5 Signal handling <signal.h>
+ 7.13.7 General utilities <stdlib.h>

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/program "cpp/utility/program") for Program support utilities |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program>

Date and time utilities
=======================

 ###  Functions

 

|  |
| --- |
|  Time manipulation  |
|  Defined in header `<time.h>` |
|  [difftime](chrono/difftime "c/chrono/difftime") |  computes the difference between times  (function) |
|  [time](chrono/time "c/chrono/time") |  returns the current calendar time of the system as time since epoch  (function) |
|  [clock](chrono/clock "c/chrono/clock") |  returns raw processor clock time since the program is started  (function) |
|  [timespec\_get](chrono/timespec_get "c/chrono/timespec get")
(C11) |  returns the calendar time in seconds and nanoseconds based on a given time base  (function) |
|  [timespec\_getres](chrono/timespec_getres "c/chrono/timespec getres")
(C23) |  returns the resolution of calendar time based on a given time base  (function) |
|  Format conversions  |
|  Defined in header `<time.h>` |
|  [asctimeasctime\_s](chrono/asctime "c/chrono/asctime")
(deprecated in C23)(C11) |  converts a `[tm](chrono/tm "c/chrono/tm")` object to a textual representation  (function) |
|  [ctimectime\_s](chrono/ctime "c/chrono/ctime")
(deprecated in C23)(C11) |  converts a `[time\_t](chrono/time_t "c/chrono/time t")` object to a textual representation  (function) |
|  [strftime](chrono/strftime "c/chrono/strftime") |  converts a `[tm](chrono/tm "c/chrono/tm")` object to custom textual representation  (function) |
|  Defined in header `<wchar.h>` |
|  [wcsftime](chrono/wcsftime "c/chrono/wcsftime")
(C95) |  converts a `[tm](chrono/tm "c/chrono/tm")` object to custom wide string textual representation  (function) |
|  Defined in header `<time.h>` |
|  [gmtimegmtime\_rgmtime\_s](chrono/gmtime "c/chrono/gmtime")
(C23)(C11) |  converts time since epoch to calendar time expressed as Coordinated Universal Time (UTC)  (function) |
|  [localtimelocaltime\_rlocaltime\_s](chrono/localtime "c/chrono/localtime")
(C23)(C11) |  converts time since epoch to calendar time expressed as local time  (function) |
|  [mktime](chrono/mktime "c/chrono/mktime") |  converts calendar time to time since epoch  (function) |

 ###  Constants

 

|  Defined in header `<time.h>` |
| --- |
|  [CLOCKS\_PER\_SEC](chrono/clocks_per_sec "c/chrono/CLOCKS PER SEC") |  number of processor clock ticks per second  (macro constant) |

 ###  Types

 

|  Defined in header `<time.h>` |
| --- |
|  [tm](chrono/tm "c/chrono/tm") |  calendar time type  (struct) |
|  [time\_t](chrono/time_t "c/chrono/time t") |  calendar time since epoch type  (typedef) |
|  [clock\_t](chrono/clock_t "c/chrono/clock t") |  processor time since era type  (typedef) |
|  [timespec](chrono/timespec "c/chrono/timespec")
(C11) |  time in seconds and nanoseconds  (struct) |

 ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27 Date and time <time.h> (p: 284-291)
+ 7.29.5.1 The wcsftime function (p: 320-321)
+ 7.31.14 Date and time <time.h> (p: 333)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27 Date and time <time.h> (p: 388-397)
+ 7.29.5.1 The wcsftime function (p: 439-440)
+ 7.31.14 Date and time <time.h> (p: 456)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23 Date and time <time.h> (p: 338-347)
+ 7.24.5.1 The wcsftime function (p: 385-386)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12 DATE AND TIME <time.h>

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c "cpp/chrono/c") for C Date and time utilities |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono>

File input/output
=================

 The `<stdio.h>` header provides generic file operation support and supplies functions with narrow character input/output capabilities.


The [`<wchar.h>`](string/wide "c/string/wide") header supplies functions with wide character input/output capabilities.


I/O streams are denoted by objects of type `[FILE](io/file "c/io/FILE")` that can only be accessed and manipulated through pointers of type `[FILE](http://en.cppreference.com/w/c/io/FILE)\*`. Each stream is associated with an external physical device (file, standard input stream, printer, serial port, etc).


###  Types

 

|  Defined in header `<stdio.h>` |
| --- |
|  [FILE](io/file "c/io/FILE") |  object type, capable of holding all information needed to control a C I/O stream  (typedef) |
|  [fpos\_t](io/fpos_t "c/io/fpos t") |  non-array complete object type, capable of uniquely specifying a position and multibyte parser state in a file  (typedef) |

 ###  Predefined standard streams

 

|  Defined in header `<stdio.h>` |
| --- |
|  [stdinstdoutstderr](io/std_streams "c/io/std streams") |  expression of type `[FILE](http://en.cppreference.com/w/c/io/FILE)\*` associated with the input streamexpression of type `[FILE](http://en.cppreference.com/w/c/io/FILE)\*` associated with the output streamexpression of type `[FILE](http://en.cppreference.com/w/c/io/FILE)\*` associated with the error output stream  (macro constant) |

 ###  Functions

 

|  |
| --- |
|  File access  |
|  Defined in header `<stdio.h>` |
|  [fopenfopen\_s](io/fopen "c/io/fopen")
(C11) |  opens a file  (function) |
|  [freopenfreopen\_s](io/freopen "c/io/freopen")
(C11) |  open an existing stream with a different name  (function) |
|  [fclose](io/fclose "c/io/fclose") |  closes a file  (function) |
|  [fflush](io/fflush "c/io/fflush") |  synchronizes an output stream with the actual file  (function) |
|  [setbuf](io/setbuf "c/io/setbuf") |  sets the buffer for a file stream  (function) |
|  [setvbuf](io/setvbuf "c/io/setvbuf") |  sets the buffer and its size for a file stream  (function) |
|  Defined in header `<wchar.h>` |
|  [fwide](io/fwide "c/io/fwide")
(C95) |  switches a file stream between wide character I/O and narrow character I/O  (function) |
|  Direct input/output  |
|  Defined in header `<stdio.h>` |
|  [fread](io/fread "c/io/fread") |  reads from a file  (function) |
|  [fwrite](io/fwrite "c/io/fwrite") |  writes to a file  (function) |
|  Unformatted input/output  |
|  Narrow character  |
|  Defined in header `<stdio.h>` |
|  [fgetcgetc](io/fgetc "c/io/fgetc") |  gets a character from a file stream  (function) |
|  [fgets](io/fgets "c/io/fgets") |  gets a character string from a file stream  (function) |
|  [fputcputc](io/fputc "c/io/fputc") |  writes a character to a file stream  (function) |
|  [fputs](io/fputs "c/io/fputs") |  writes a character string to a file stream  (function) |
|  [getchar](io/getchar "c/io/getchar") |  reads a character from `[stdin](io/std_streams "c/io/std streams")`  (function) |
|  [getsgets\_s](io/gets "c/io/gets")
(removed in C11)(C11) |  reads a character string from `stdin`  (function) |
|  [putchar](io/putchar "c/io/putchar") |  writes a character to `stdout`  (function) |
|  [puts](io/puts "c/io/puts") |  writes a character string to `[stdout](io/std_streams "c/io/std streams")`  (function) |
|  [ungetc](io/ungetc "c/io/ungetc") |  puts a character back into a file stream  (function) |
|  Wide character  |
|  Defined in header `<wchar.h>` |
|  [fgetwcgetwc](io/fgetwc "c/io/fgetwc")
(C95) |  gets a wide character from a file stream  (function) |
|  [fgetws](io/fgetws "c/io/fgetws")
(C95) |  gets a wide string from a file stream  (function) |
|  [fputwcputwc](io/fputwc "c/io/fputwc")
(C95) |  writes a wide character to a file stream  (function) |
|  [fputws](io/fputws "c/io/fputws")
(C95) |  writes a wide string to a file stream  (function) |
|  [getwchar](io/getwchar "c/io/getwchar")
(C95) |  reads a wide character from `stdin`  (function) |
|  [putwchar](io/putwchar "c/io/putwchar")
(C95) |  writes a wide character to `[stdout](io/std_streams "c/io/std streams")`  (function) |
|  [ungetwc](io/ungetwc "c/io/ungetwc")
(C95) |  puts a wide character back into a file stream  (function) |
|  Formatted input/output  |
|  Narrow character  |
|  Defined in header `<stdio.h>` |
|  [scanffscanfsscanfscanf\_sfscanf\_ssscanf\_s](io/fscanf "c/io/fscanf")
(C11)(C11)(C11) |  reads formatted input from `[stdin](io/std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [vscanfvfscanfvsscanfvscanf\_svfscanf\_svsscanf\_s](io/vfscanf "c/io/vfscanf")
(C99)(C99)(C99)(C11)(C11)(C11) |  reads formatted input from `[stdin](io/std_streams "c/io/std streams")`, a file stream or a buffer using variable argument list  (function) |
|  [printffprintfsprintfsnprintfprintf\_sfprintf\_ssprintf\_ssnprintf\_s](io/fprintf "c/io/fprintf")
(C99)(C11)(C11)(C11)(C11) |  prints formatted output to `[stdout](io/std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [vprintfvfprintfvsprintfvsnprintfvprintf\_svfprintf\_svsprintf\_svsnprintf\_s](io/vfprintf "c/io/vfprintf")
(C99)(C11)(C11)(C11)(C11) |  prints formatted output to `[stdout](io/std_streams "c/io/std streams")`, a file stream or a buffer using variable argument list  (function) |
|  Wide character  |
|  Defined in header `<wchar.h>` |
|  [wscanffwscanfswscanfwscanf\_sfwscanf\_sswscanf\_s](io/fwscanf "c/io/fwscanf")
(C95)(C95)(C95)(C11)(C11)(C11) |  reads formatted wide character input from `[stdin](io/std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [vwscanfvfwscanfvswscanfvwscanf\_svfwscanf\_svswscanf\_s](io/vfwscanf "c/io/vfwscanf")
(C99)(C99)(C99)(C11)(C11)(C11) |  reads formatted wide character input from `[stdin](io/std_streams "c/io/std streams")`, a file stream or a buffer using variable argument list  (function) |
|  [wprintffwprintfswprintfwprintf\_sfwprintf\_sswprintf\_ssnwprintf\_s](io/fwprintf "c/io/fwprintf")
(C95)(C95)(C95)(C11)(C11)(C11)(C11) |  prints formatted wide character output to `[stdout](io/std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [vwprintfvfwprintfvswprintfvwprintf\_svfwprintf\_svswprintf\_svsnwprintf\_s](io/vfwprintf "c/io/vfwprintf")
(C95)(C95)(C95)(C11)(C11)(C11)(C11) |  prints formatted wide character output to `[stdout](io/std_streams "c/io/std streams")`, a file stream or a buffer using variable argument list  (function) |
|  File positioning  |
|  Defined in header `<stdio.h>` |
|  [ftell](io/ftell "c/io/ftell") |  returns the current file position indicator  (function) |
|  [fgetpos](io/fgetpos "c/io/fgetpos") |  gets the file position indicator  (function) |
|  [fseek](io/fseek "c/io/fseek") |  moves the file position indicator to a specific location in a file  (function) |
|  [fsetpos](io/fsetpos "c/io/fsetpos") |  moves the file position indicator to a specific location in a file  (function) |
|  [rewind](io/rewind "c/io/rewind") |  moves the file position indicator to the beginning in a file  (function) |
|  Error handling  |
|  Defined in header `<stdio.h>` |
|  [clearerr](io/clearerr "c/io/clearerr") |  clears errors  (function) |
|  [feof](io/feof "c/io/feof") |  checks for the end-of-file  (function) |
|  [ferror](io/ferror "c/io/ferror") |  checks for a file error  (function) |
|  [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) |
|  Operations on files  |
|  Defined in header `<stdio.h>` |
|  [remove](io/remove "c/io/remove") |  erases a file  (function) |
|  [rename](io/rename "c/io/rename") |  renames a file  (function) |
|  [tmpfiletmpfile\_s](io/tmpfile "c/io/tmpfile")
(C11) |  returns a pointer to a temporary file  (function) |
|  [tmpnamtmpnam\_s](io/tmpnam "c/io/tmpnam")
(C11) |  returns a unique filename  (function) |

 ###  Macro constants

 

|  Defined in header `<stdio.h>` |
| --- |
| EOF |  integer constant expression of type `int` and negative value  (macro constant) |
| FOPEN\_MAX |  maximum number of files that can be open simultaneously  (macro constant) |
| FILENAME\_MAX |  size needed for an array of `char` to hold the longest supported file name  (macro constant) |
| BUFSIZ |  size of the buffer used by `[setbuf](io/setbuf "c/io/setbuf")`  (macro constant) |
| \_IOFBF\_IOLBF\_IONBF |  argument to `[setvbuf](io/setvbuf "c/io/setvbuf")` indicating fully buffered I/Oargument to `[setvbuf](io/setvbuf "c/io/setvbuf")` indicating line buffered I/Oargument to `[setvbuf](io/setvbuf "c/io/setvbuf")` indicating unbuffered I/O  (macro constant) |
| SEEK\_SETSEEK\_CURSEEK\_END |  argument to `[fseek](io/fseek "c/io/fseek")` indicating seeking from beginning of the fileargument to `[fseek](io/fseek "c/io/fseek")` indicating seeking from the current file positionargument to `[fseek](io/fseek "c/io/fseek")` indicating seeking from end of the file  (macro constant) |
| TMP\_MAXTMP\_MAX\_S
(C11) |  maximum number of unique filenames that can be generated by `[tmpnam](io/tmpnam "c/io/tmpnam")`maximum number of unique filenames that can be generated by `tmpnam_s`  (macro constant) |
| L\_tmpnamL\_tmpnam\_s
(C11) |  size needed for an array of `char` to hold the result of `[tmpnam](io/tmpnam "c/io/tmpnam")`size needed for an array of `char` to hold the result of `tmpnam_s`  (macro constant) |

 ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.21 Input/output <stdio.h> (p: TBD)
+ 7.29 Extended multibyte and wide character utilities <wchar.h> (p: TBD)
+ 7.31.11 Input/output <stdio.h> (p: TBD)
+ 7.31.16 Extended multibyte and wide character utilities <wchar.h> (p: TBD)
+ K.3.5 Input/output <stdio.h> (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.21 Input/output <stdio.h> (p: TBD)
+ 7.29 Extended multibyte and wide character utilities <wchar.h> (p: TBD)
+ 7.31.11 Input/output <stdio.h> (p: TBD)
+ 7.31.16 Extended multibyte and wide character utilities <wchar.h> (p: TBD)
+ K.3.5 Input/output <stdio.h> (p: TBD)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21 Input/output <stdio.h> (p: 296-339)
+ 7.29 Extended multibyte and wide character utilities <wchar.h> (p: 402-446)
+ 7.31.11 Input/output <stdio.h> (p: 456)
+ 7.31.16 Extended multibyte and wide character utilities <wchar.h> (p: 456)
+ K.3.5 Input/output <stdio.h> (p: 586-603)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19 Input/output <stdio.h> (p: 262-305)
+ 7.24 Extended multibyte and wide character utilities <wchar.h> (p: 348-392)
+ 7.26.9 Input/output <stdio.h> (p: 402)
+ 7.26.12 Extended multibyte and wide character utilities <wchar.h> (p: 402)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9 INPUT/OUTPUT <stdio.h>
+ 4.13.6 Input/output <stdio.h>

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c "cpp/io/c") for C-style file input/output |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io>

\_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 <stdio.h>
#include <stdlib.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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.7.4 Function specifiers (p: TBD)
+ 7.23 \_Noreturn <stdnoreturn.h> (p: TBD)

* 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

 

|  |  |
| --- | --- |
| `[[[noreturn](attributes/noreturn "c/language/attributes/noreturn")]]`(C23)`[[[\_Noreturn](attributes/noreturn "c/language/attributes/noreturn")]]`(C23)(deprecated) |  indicates that the function does not return(attribute specifier) |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/attributes/noreturn "cpp/language/attributes/noreturn") for `[[noreturn]]` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/_Noreturn>

Numeric limits
==============

 ###  Limits of integer types

 

|  |
| --- |
|  Limits of core language integer types  |
|  Defined in header `<limits.h>` |
| BOOL\_WIDTH
(C23) |  bit width of \_Bool  (macro constant) |
| CHAR\_BIT |  number of bits in a byte  (macro constant) |
| MB\_LEN\_MAX |  maximum number of bytes in a multibyte character  (macro constant) |
| CHAR\_WIDTH
(C23) |  bit width of char, same as `CHAR_BIT`  (macro constant) |
| CHAR\_MIN |  minimum value of char  (macro constant) |
| CHAR\_MAX |  maximum value of char  (macro constant) |
| SCHAR\_WIDTHSHRT\_WIDTHINT\_WIDTHLONG\_WIDTHLLONG\_WIDTH
(C23)(C23)(C23)(C23)(C23) |  bit width of signed char, short, int, long, and long long respectively  (macro constant) |
| SCHAR\_MINSHRT\_MININT\_MINLONG\_MINLLONG\_MIN
(C99) |  minimum value of signed char, short, int, long and long long respectively  (macro constant) |
| SCHAR\_MAXSHRT\_MAXINT\_MAXLONG\_MAXLLONG\_MAX
(C99) |  maximum value of signed char, short, int, long and long long respectively  (macro constant) |
| UCHAR\_WIDTHUSHRT\_WIDTHUINT\_WIDTHULONG\_WIDTHULLONG\_WIDTH
(C23)(C23)(C23)(C23)(C23) |  bit width of unsigned char, unsigned short, unsigned int, unsigned long, and unsigned long long respectively  (macro constant) |
| UCHAR\_MAXUSHRT\_MAXUINT\_MAXULONG\_MAXULLONG\_MAX
(C99) |  maximum value of unsigned char, unsigned short, unsigned int,unsigned long and unsigned long long respectively  (macro constant) |
|  Limits of library type aliases  |
|  Defined in header `<stdint.h>` |
| PTRDIFF\_WIDTH
(C23) |  bit width of object of `[ptrdiff\_t](ptrdiff_t "c/types/ptrdiff t")` type  (macro constant) |
| PTRDIFF\_MIN
(C99) |  minimum value of `[ptrdiff\_t](ptrdiff_t "c/types/ptrdiff t")`  (macro constant) |
| PTRDIFF\_MAX
(C99) |  maximum value of `[ptrdiff\_t](ptrdiff_t "c/types/ptrdiff t")`  (macro constant) |
| SIZE\_WIDTH
(C23) |  bit width of object of `[size\_t](size_t "c/types/size t")` type  (macro constant) |
| SIZE\_MAX
(C99) |  maximum value of `[size\_t](size_t "c/types/size t")`  (macro constant) |
| SIG\_ATOMIC\_WIDTH
(C23) |  bit width of object of `[sig\_atomic\_t](../program/sig_atomic_t "c/program/sig atomic t")` type  (macro constant) |
| SIG\_ATOMIC\_MIN
(C99) |  minimum value of `[sig\_atomic\_t](../program/sig_atomic_t "c/program/sig atomic t")`  (macro constant) |
| SIG\_ATOMIC\_MAX
(C99) |  maximum value of `[sig\_atomic\_t](../program/sig_atomic_t "c/program/sig atomic t")`  (macro constant) |
| WINT\_WIDTH
(C23) |  bit width of object of wint\_t type  (macro constant) |
| WINT\_MIN
(C99) |  minimum value of `wint_t`  (macro constant) |
| WINT\_MAX
(C99) |  maximum value of `wint_t`  (macro constant) |
|  Defined in header `<wchar.h>` |
|  Defined in header `<stdint.h>` |
| WCHAR\_WIDTH
(C23) |  bit width of object of wchar\_t type  (macro constant) |
| WCHAR\_MIN
(C99) |  minimum value of wchar\_t  (macro constant) |
| WCHAR\_MAX
(C99) |  maximum value of wchar\_t  (macro constant) |

 ####  Notes

 The types of these constants, other than `CHAR_BIT` and `MB_LEN_MAX`, are required to match the results of the [integral promotions](../language/conversion#Integer_promotions "c/language/conversion") as applied to objects of the types they describe: `CHAR_MAX` may have type int or unsigned int, but never char. Similarly `USHRT_MAX` may not be of an unsigned type: its type may be int.


A freestanding implementation may lack `[sig\_atomic\_t](../program/sig_atomic_t "c/program/sig atomic t")` and/or wint\_t typedef names, in which case the `SIG_ATOMIC_*` and/or `WINT_*` macros are correspondingly absent.


####  Example

  
```
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
 
int main(void)
{
    printf("CHAR_BIT       = %d\n", CHAR_BIT);
    printf("MB_LEN_MAX     = %d\n\n", MB_LEN_MAX);
 
    printf("CHAR_MIN       = %+d\n", CHAR_MIN);
    printf("CHAR_MAX       = %+d\n", CHAR_MAX);
    printf("SCHAR_MIN      = %+d\n", SCHAR_MIN);
    printf("SCHAR_MAX      = %+d\n", SCHAR_MAX);
    printf("UCHAR_MAX      = %u\n\n", UCHAR_MAX);
 
    printf("SHRT_MIN       = %+d\n", SHRT_MIN);
    printf("SHRT_MAX       = %+d\n", SHRT_MAX);
    printf("USHRT_MAX      = %u\n\n", USHRT_MAX);
 
    printf("INT_MIN        = %+d\n", INT_MIN);
    printf("INT_MAX        = %+d\n", INT_MAX);
    printf("UINT_MAX       = %u\n\n", UINT_MAX);
 
    printf("LONG_MIN       = %+ld\n", LONG_MIN);
    printf("LONG_MAX       = %+ld\n", LONG_MAX);
    printf("ULONG_MAX      = %lu\n\n", ULONG_MAX);
 
    printf("LLONG_MIN      = %+lld\n", LLONG_MIN);
    printf("LLONG_MAX      = %+lld\n", LLONG_MAX);
    printf("ULLONG_MAX     = %llu\n\n", ULLONG_MAX);
 
    printf("PTRDIFF_MIN    = %td\n", PTRDIFF_MIN);
    printf("PTRDIFF_MAX    = %+td\n", PTRDIFF_MAX);
    printf("SIZE_MAX       = %zu\n", SIZE_MAX);
    printf("SIG_ATOMIC_MIN = %+jd\n",(intmax_t)SIG_ATOMIC_MIN);
    printf("SIG_ATOMIC_MAX = %+jd\n",(intmax_t)SIG_ATOMIC_MAX);
    printf("WCHAR_MIN      = %+jd\n",(intmax_t)WCHAR_MIN);
    printf("WCHAR_MAX      = %+jd\n",(intmax_t)WCHAR_MAX);
    printf("WINT_MIN       = %jd\n", (intmax_t)WINT_MIN);
    printf("WINT_MAX       = %jd\n", (intmax_t)WINT_MAX);
}
```
 Possible output:



```
CHAR_BIT       = 8
MB_LEN_MAX     = 16
 
CHAR_MIN       = -128
CHAR_MAX       = +127
SCHAR_MIN      = -128
SCHAR_MAX      = +127
UCHAR_MAX      = 255
 
SHRT_MIN       = -32768
SHRT_MAX       = +32767
USHRT_MAX      = 65535
 
INT_MIN        = -2147483648
INT_MAX        = +2147483647
UINT_MAX       = 4294967295
 
LONG_MIN       = -9223372036854775808
LONG_MAX       = +9223372036854775807
ULONG_MAX      = 18446744073709551615
 
LLONG_MIN      = -9223372036854775808
LLONG_MAX      = +9223372036854775807
ULLONG_MAX     = 18446744073709551615
 
PTRDIFF_MIN    = -9223372036854775808
PTRDIFF_MAX    = +9223372036854775807
SIZE_MAX       = 18446744073709551615
SIG_ATOMIC_MIN = -2147483648
SIG_ATOMIC_MAX = +2147483647
WCHAR_MIN      = -2147483648
WCHAR_MAX      = +2147483647
WINT_MIN       = 0
WINT_MAX       = 4294967295
```
  ###  Limits of floating-point types

 

|  Defined in header `<float.h>` |
| --- |
| FLT\_RADIX |  the radix (integer base) used by the representation of all three floating-point types  (macro constant) |
| DECIMAL\_DIG
(C99) |  conversion from long double to decimal with at least `DECIMAL_DIG` digits and back to long double is the identity conversion: this is the decimal precision required to serialize/deserialize a long double  (macro constant) |
| FLT\_DECIMAL\_DIGDBL\_DECIMAL\_DIGLDBL\_DECIMAL\_DIG
(C11) |  conversion from float/double/long double to decimal with at least `FLT_DECIMAL_DIG`/`DBL_DECIMAL_DIG`/`LDBL_DECIMAL_DIG` digits and back is the identity conversion: this is the decimal precision required to serialize/deserialize a floating-point value. Defined to at least `6`, `10`, and `10` respectively, or `9` for IEEE float and `17` for IEEE double (see also the C++ analog: [`max_digits10`](https://en.cppreference.com/w/cpp/types/numeric_limits/max_digits10 "cpp/types/numeric limits/max digits10"))  (macro constant) |
| FLT\_MINDBL\_MINLDBL\_MIN |  minimum, normalized, positive value of float, double and long double respectively  (macro constant) |
| FLT\_TRUE\_MINDBL\_TRUE\_MINLDBL\_TRUE\_MIN
(C11) |  minimum positive value of float, double and long double respectively  (macro constant) |
| FLT\_MAXDBL\_MAXLDBL\_MAX |  maximum finite value of float, double and long double respectively  (macro constant) |
| FLT\_EPSILONDBL\_EPSILONLDBL\_EPSILON |  absolute value difference between `1.0` and the next representable value for float, double and long double respectively  (macro constant) |
| FLT\_DIGDBL\_DIGLDBL\_DIG |  number of decimal digits that are guaranteed to be preserved in text → float/double/long double → text roundtrip without change due to rounding or overflow (see the C++ analog [`digits10`](https://en.cppreference.com/w/cpp/types/numeric_limits/digits10 "cpp/types/numeric limits/digits10") for detail)  (macro constant) |
| FLT\_MANT\_DIGDBL\_MANT\_DIGLDBL\_MANT\_DIG |  number of base-`FLT_RADIX` digits that are in the floating-point mantissa and that can be represented without losing precision for float, double and long double respectively  (macro constant) |
| FLT\_MIN\_EXPDBL\_MIN\_EXPLDBL\_MIN\_EXP |  minimum negative integer such that `FLT_RADIX` raised by power one less than that integer is a normalized float, double and long double respectively  (macro constant) |
| FLT\_MIN\_10\_EXPDBL\_MIN\_10\_EXPLDBL\_MIN\_10\_EXP |  minimum negative integer such that 10 raised by power one less than that integer is a normalized float, double and long double respectively  (macro constant) |
| FLT\_MAX\_EXPDBL\_MAX\_EXPLDBL\_MAX\_EXP |  maximum positive integer such that `FLT_RADIX` raised by power one less than that integer is a representable finite float, double and long double respectively  (macro constant) |
| FLT\_MAX\_10\_EXPDBL\_MAX\_10\_EXPLDBL\_MAX\_10\_EXP |  maximum positive integer such that 10 raised by power one less than that integer is a representable finite float, double and long double respectively  (macro constant) |
|  [FLT\_ROUNDS](limits/flt_rounds "c/types/limits/FLT ROUNDS") |  rounding mode of floating-point arithmetic  (macro constant) |
|  [FLT\_EVAL\_METHOD](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) |
| FLT\_HAS\_SUBNORMDBL\_HAS\_SUBNORMLDBL\_HAS\_SUBNORM
(C11) |  whether the type supports subnormal ([denormal](https://en.wikipedia.org/wiki/Denormal_number "enwiki:Denormal number")) numbers:`-1` – indeterminable, `​0​` – absent, `1` – present  (macro constant) |

 ####  Example

  
```
#include <float.h>
#include <math.h>
#include <stdio.h>
 
int main(void)
{
    printf("DECIMAL_DIG     = %d\n", DECIMAL_DIG);
    printf("FLT_DECIMAL_DIG = %d\n", FLT_DECIMAL_DIG);
    printf("FLT_RADIX       = %d\n", FLT_RADIX);
    printf("FLT_MIN         = %e\n", FLT_MIN);
    printf("FLT_MAX         = %e\n", FLT_MAX);
    printf("FLT_EPSILON     = %e\n", FLT_EPSILON);
    printf("FLT_DIG         = %d\n", FLT_DIG);
    printf("FLT_MANT_DIG    = %d\n", FLT_MANT_DIG);
    printf("FLT_MIN_EXP     = %d\n", FLT_MIN_EXP);
    printf("FLT_MIN_10_EXP  = %d\n", FLT_MIN_10_EXP);
    printf("FLT_MAX_EXP     = %d\n", FLT_MAX_EXP);
    printf("FLT_MAX_10_EXP  = %d\n", FLT_MAX_10_EXP);
    printf("FLT_ROUNDS      = %d\n", FLT_ROUNDS);
    printf("FLT_EVAL_METHOD = %d\n", FLT_EVAL_METHOD);
    printf("FLT_HAS_SUBNORM = %d\n", FLT_HAS_SUBNORM);
}
```
 Possible output:



```
DECIMAL_DIG     = 37
FLT_DECIMAL_DIG = 9
FLT_RADIX       = 2
FLT_MIN         = 1.175494e-38
FLT_MAX         = 3.402823e+38
FLT_EPSILON     = 1.192093e-07
FLT_DIG         = 6
FLT_MANT_DIG    = 24
FLT_MIN_EXP     = -125
FLT_MIN_10_EXP  = -37
FLT_MAX_EXP     = 128
FLT_MAX_10_EXP  = 38
FLT_ROUNDS      = 1
FLT_EVAL_METHOD = 1
FLT_HAS_SUBNORM = 1
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 5.2.4.2 Numerical limits (p: 20-27)
+ 7.20.3 Limits of other integer types (p: 215-216)

* C11 standard (ISO/IEC 9899:2011):
+ 5.2.4.2 Numerical limits (p: 26-34)
+ 7.20.3 Limits of other integer types (p: 293-294)

* C99 standard (ISO/IEC 9899:1999):
+ 5.2.4.2 Numerical limits (p: 21-28)
+ 7.18.3 Limits of other integer types (p: 259-260)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 2.2.4.2 Numerical limits

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/types/climits "cpp/types/climits") for C numeric limits interface |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/types/limits>

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 parts is infinite, even if the other part is NaN.


A complex or imaginary number is finite if both parts are neither infinities nor NaNs.


A complex or imaginary number is a zero if both parts 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex>

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](https://en.wikipedia.org/wiki/DIN_66003 "enwiki: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" (even though it is four letters long `%:%:` is also considered a digraph).




|  Primary  |  Alternative  |
| --- | --- |
| `{` | `<%` |
| 
} | `%>` |
| `[` | `<:` |
| `]` | `:>` |
| `#` | `%:` |
| `##` | `%:%:` |

  Trigraphs (removed in C23)
---------------------------

 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

 
Demonstrates alternative operator spellings from the **`<iso646.h>`** as well as use of digraphs and trigraphs. If command line arguments contain spaces they should be wrapped in the quotation marks, e.g., `"Third World!"`.



```
%:include <stdio.h>
%:include <stdlib.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:>);
    %>
    else
    <%
       printf("Hello %s??/n", argc? argv??(42??'42??) : __FILE__);
    %>
 
    return EXIT_SUCCESS;
??>
```
 Possible output:



```
Hello ./a.out
```
  ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_alternative "cpp/language/operator alternative") for Alternative operator representations |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/operator_alternative>

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](multibyte/char8_t "c/string/multibyte/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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte>

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)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/tgmath>

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](../language/ascii "c/language/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 and from 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) |
|  [strfromfstrfromdstrfromld](byte/strfromf "c/string/byte/strfromf")
(C23)(C23)(C23) |  converts a floating point value to a byte string  (function) |
|  Defined in header `<inttypes.h>` |
|  [strtoimaxstrtoumax](byte/strtoimax "c/string/byte/strtoimax")
(C99)(C99) |  converts a byte string to `[intmax\_t](../types/integer "c/types/integer")` or `[uintmax\_t](../types/integer "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\_explicitmemset\_s](byte/memset "c/string/byte/memset")
(C23)(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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/random>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/basic_concepts>

C keywords
==========

 This is a list of reserved keywords in C. Since they are used by the language, these keywords are not available for re-definition. As an exception, they are not considered reserved in [attribute-tokens](language/attributes "c/language/attributes") (since C23).




|  |  |  |  |
| --- | --- | --- | --- |
| [`alignas`](keyword/alignas "c/keyword/alignas") (C23) [`alignof`](keyword/alignof "c/keyword/alignof") (C23) [`auto`](keyword/auto "c/keyword/auto") [`bool`](keyword/bool "c/keyword/bool") (C23) [`break`](keyword/break "c/keyword/break") [`case`](keyword/case "c/keyword/case") [`char`](keyword/char "c/keyword/char") [`const`](keyword/const "c/keyword/const") [`constexpr`](https://en.cppreference.com/mwiki/index.php?title=c/keyword/constexpr&action=edit&redlink=1 "c/keyword/constexpr (page does not exist)") (C23) [`continue`](keyword/continue "c/keyword/continue") [`default`](keyword/default "c/keyword/default") [`do`](keyword/do "c/keyword/do") [`double`](keyword/double "c/keyword/double") [`else`](keyword/else "c/keyword/else") [`enum`](keyword/enum "c/keyword/enum"). | [`extern`](keyword/extern "c/keyword/extern") [`false`](keyword/false "c/keyword/false") (C23) [`float`](keyword/float "c/keyword/float") [`for`](keyword/for "c/keyword/for") [`goto`](keyword/goto "c/keyword/goto") [`if`](keyword/if "c/keyword/if") [`inline`](keyword/inline "c/keyword/inline") (C99) [`int`](keyword/int "c/keyword/int") [`long`](keyword/long "c/keyword/long") [`nullptr`](keyword/nullptr "c/keyword/nullptr") (C23) [`register`](keyword/register "c/keyword/register") [`restrict`](keyword/restrict "c/keyword/restrict") (C99) [`return`](keyword/return "c/keyword/return") [`short`](keyword/short "c/keyword/short") [`signed`](keyword/signed "c/keyword/signed"). | [`sizeof`](keyword/sizeof "c/keyword/sizeof") [`static`](keyword/static "c/keyword/static") [`static_assert`](keyword/static_assert "c/keyword/static assert") (C23) [`struct`](keyword/struct "c/keyword/struct") [`switch`](keyword/switch "c/keyword/switch") [`thread_local`](keyword/thread_local "c/keyword/thread local") (C23) [`true`](keyword/true "c/keyword/true") (C23) [`typedef`](keyword/typedef "c/keyword/typedef") [`typeof`](keyword/typeof "c/keyword/typeof") (C23) [`typeof_unqual`](keyword/typeof_unqual "c/keyword/typeof unqual") (C23) [`union`](keyword/union "c/keyword/union") [`unsigned`](keyword/unsigned "c/keyword/unsigned") [`void`](keyword/void "c/keyword/void") [`volatile`](keyword/volatile "c/keyword/volatile") [`while`](keyword/while "c/keyword/while"). | [`_Alignas`](keyword/_alignas "c/keyword/ Alignas") (C11) [`_Alignof`](keyword/_alignof "c/keyword/ Alignof") (C11) [`_Atomic`](keyword/_atomic "c/keyword/ Atomic") (C11) [`_BitInt`](https://en.cppreference.com/mwiki/index.php?title=c/keyword/_BitInt&action=edit&redlink=1 "c/keyword/ BitInt (page does not exist)") (C23) [`_Bool`](keyword/_bool "c/keyword/ Bool") (C99) [`_Complex`](keyword/_complex "c/keyword/ Complex") (C99) [`_Decimal128`](keyword/_decimal128 "c/keyword/ Decimal128") (C23) [`_Decimal32`](keyword/_decimal32 "c/keyword/ Decimal32") (C23) [`_Decimal64`](keyword/_decimal64 "c/keyword/ Decimal64") (C23) [`_Generic`](keyword/_generic "c/keyword/ Generic") (C11) [`_Imaginary`](keyword/_imaginary "c/keyword/ Imaginary") (C99) [`_Noreturn`](keyword/_noreturn "c/keyword/ Noreturn") (C11) [`_Static_assert`](keyword/_static_assert "c/keyword/ Static assert") (C11) [`_Thread_local`](keyword/_thread_local "c/keyword/ Thread local") (C11). |

 The most common keywords that begin with an underscore are generally used through their convenience macros:




|  |  |  |
| --- | --- | --- |
| keyword  | used as  | defined in  |
| [`_Alignas`](keyword/_alignas "c/keyword/ Alignas") (C11) | [`alignas`](types "c/types") (removed in C23) | `stdalign.h` |
| [`_Alignof`](keyword/_alignof "c/keyword/ Alignof") (C11) | [`alignof`](types "c/types") (removed in C23) | `stdalign.h` |
| [`_Atomic`](keyword/_atomic "c/keyword/ Atomic") (C11) | [`atomic_bool, atomic_int, ...`](thread "c/thread") | `stdatomic.h` |
| [`_BitInt`](https://en.cppreference.com/mwiki/index.php?title=c/keyword/_BitInt&action=edit&redlink=1 "c/keyword/ BitInt (page does not exist)") (C23) | (no macro)  |  |
| [`_Bool`](keyword/_bool "c/keyword/ Bool") (C99) | [`bool`](types "c/types") (removed in C23) | `stdbool.h` |
| [`_Complex`](keyword/_complex "c/keyword/ Complex") (C99) | [`complex`](numeric/complex/complex "c/numeric/complex/complex") | `complex.h` |
| [`_Decimal128`](keyword/_decimal128 "c/keyword/ Decimal128") (C23) | (no macro)  |  |
| [`_Decimal32`](keyword/_decimal32 "c/keyword/ Decimal32") (C23) | (no macro)  |  |
| [`_Decimal64`](keyword/_decimal64 "c/keyword/ Decimal64") (C23) | (no macro)  |  |
| [`_Generic`](keyword/_generic "c/keyword/ Generic") (C11) | (no macro)  |  |
| [`_Imaginary`](keyword/_imaginary "c/keyword/ Imaginary") (C99) | [`imaginary`](numeric/complex/imaginary "c/numeric/complex/imaginary") | `complex.h` |
| [`_Noreturn`](keyword/_noreturn "c/keyword/ Noreturn") (C11) | [`noreturn`](types "c/types") | `stdnoreturn.h` |
| [`_Static_assert`](keyword/_static_assert "c/keyword/ Static assert") (C11) | [`static_assert`](error/static_assert "c/error/static assert") (removed in C23) | `assert.h` |
| [`_Thread_local`](keyword/_thread_local "c/keyword/ Thread local") (C11) | [`thread_local`](thread/thread_local "c/thread/thread local") (removed in C23) | `threads.h` |

 Also, each name that begins with a double underscore `__` or an underscore `_` followed by an uppercase letter is reserved: see [identifier](language/identifier#Reserved_identifiers "c/language/identifier") for details.


Note that digraphs `<%`, `%>`, `<:`, `:>`, `%:`, and `%:%:` provide an [alternative way to represent standard tokens](language/operator_alternative "c/language/operator alternative").


The following tokens are recognized by the [preprocessor](preprocessor "c/preprocessor") when they are used *within* the context of a preprocessor directive:




|  |  |  |  |
| --- | --- | --- | --- |
| [`if`](preprocessor/conditional "c/preprocessor/conditional") [`elif`](preprocessor/conditional "c/preprocessor/conditional") [`else`](preprocessor/conditional "c/preprocessor/conditional") [`endif`](preprocessor/conditional "c/preprocessor/conditional"). | [`ifdef`](preprocessor/conditional "c/preprocessor/conditional") [`ifndef`](preprocessor/conditional "c/preprocessor/conditional") [`elifdef`](preprocessor/conditional "c/preprocessor/conditional") (C23) [`elifndef`](preprocessor/conditional "c/preprocessor/conditional") (C23) [`define`](preprocessor/replace "c/preprocessor/replace") [`undef`](preprocessor/replace "c/preprocessor/replace"). | [`include`](preprocessor/include "c/preprocessor/include") [`embed`](preprocessor/embed "c/preprocessor/embed") (C23) [`line`](preprocessor/line "c/preprocessor/line") [`error`](preprocessor/error "c/preprocessor/error") [`warning`](preprocessor/error "c/preprocessor/error") (C23) [`pragma`](preprocessor/impl "c/preprocessor/impl"). | [`defined`](preprocessor/conditional "c/preprocessor/conditional") [`__has_include`](preprocessor/include "c/preprocessor/include") (C23) [`__has_embed`](preprocessor/embed "c/preprocessor/embed") (C23) [`__has_c_attribute`](language/attributes#Attribute_testing "c/language/attributes") (C23). |

 The following tokens are recognized by the preprocessor when they are used *outside* the context of a preprocessor directive:




|  |
| --- |
| [`_Pragma`](preprocessor/impl "c/preprocessor/impl") (C99). |

 The following additional keywords are classified as extensions and conditionally-supported:




|  |
| --- |
| [`asm`](language/asm "c/language/asm") [`fortran`](keyword/fortran "c/keyword/fortran"). |

 ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 6.4.1 Keywords (p: 42-43)
+ J.5.9 The fortran keyword (p: 422)
+ J.5.10 The asm keyword (p: 422)

* C11 standard (ISO/IEC 9899:2011):
+ 6.4.1 Keywords (p: 58-59)
+ J.5.9 The fortran keyword (p: 580)
+ J.5.10 The asm keyword (p: 580)

* C99 standard (ISO/IEC 9899:1999):
+ 6.4.1 Keywords (p: 50)
+ J.5.9 The fortran keyword (p: 514)
+ J.5.10 The asm keyword (p: 514)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.1 Keywords
+ G.5.9 The fortran keyword
+ G.5.10 The asm keyword

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/keyword "cpp/keyword") for C++ keywords |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword>

Preprocessor
============

 The preprocessor is executed at [translation phase 4](language/translation_phases "c/language/translation phases"), before the compilation. The result of preprocessing is a single file which is then passed to the actual compiler.


###  Directives

 The preprocessing directives control the behavior of the preprocessor. Each directive occupies one line and has the following format:


* `#` character
* preprocessing instruction (one of `define`, `undef`, `include`, `if`, `ifdef`, `ifndef`, `else`, `elif`, `elifdef`, `elifndef` (since C23), `endif`, `line`, `embed` (since C23), `error`, `warning` (since C23), `pragma`) [[1]](#cite_note-1)
* arguments (depends on the instruction)
* line break

 The null directive (`#` followed by a line break) is allowed and has no effect.


###  Capabilities

 The preprocessor has the source file translation capabilities:


* **[conditionally](preprocessor/conditional "c/preprocessor/conditional")** compile of parts of source file (controlled by directive `#if`, `#ifdef`, `#ifndef`, `#else`, `#elif`, `#elifdef`, `#elifndef` (since C23) and `#endif`).
* **[replace](preprocessor/replace "c/preprocessor/replace")** text macros while possibly concatenating or quoting identifiers (controlled by directives `#define` and `#undef`, and operators `#` and `##`)
* **[include](preprocessor/include "c/preprocessor/include")** other files (controlled by directive `#include` and checked with `__has_include` (since C23))
* cause an **[error](preprocessor/error "c/preprocessor/error")** or **[warning](preprocessor/error "c/preprocessor/error")** (since C23) (controlled by directive `#error` or `#warning` respectively (since C23))

 The following aspects of the preprocessor can be controlled:


* **[implementation defined](preprocessor/impl "c/preprocessor/impl")** behavior (controlled by directive `#pragma` and operator `_Pragma` (since C99))
* **[file name and line information](preprocessor/line "c/preprocessor/line")** available to the preprocessor (controlled by directives `#line`)

 ###  Footnotes

 1. These are the directives defined by the standard. The standard does not define behavior for other directives: they might be ignored, have some useful meaning, or make the program ill-formed. Even if otherwise ignored, they are removed from the source code when the preprocessor is done. A common non-standard extension is the directive `#warning` which emits a user-defined message during compilation. (until C23)

 ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 6.10 Preprocessing directives (p: 117-129)

* C11 standard (ISO/IEC 9899:2011):
+ 6.10 Preprocessing directives (p: 160-178)

* C99 standard (ISO/IEC 9899:1999):
+ 6.10 Preprocessing directives (p: 145-162)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.8 PREPROCESSING DIRECTIVES

 ###  See also

 

|  |
| --- |
| [C documentation](preprocessor/replace#Predefined_macros "c/preprocessor/replace") for Predefined Macro Symbols |
| [C documentation](symbol_index/macro "c/symbol index/macro") for Macro Symbol Index |
| [C++ documentation](https://en.cppreference.com/w/cpp/preprocessor "cpp/preprocessor") for Preprocessor |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/preprocessor>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/statements>

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](../locale/lc_categories "c/locale/LC categories")` 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) |  scalar 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide>

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 initializer ﻿s (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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/initialization>

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
+ a [typeof](typeof "c/language/typeof") specifier (since C23)

* zero or one storage-class specifiers: [`typedef`](typedef "c/language/typedef"), [`constexpr`](https://en.cppreference.com/mwiki/index.php?title=c/language/constexpr&action=edit&redlink=1 "c/language/constexpr (page does not exist)"), [`auto`](auto "c/language/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. The type of a variable might also be inferred if `auto` specifier is used. (since C23).


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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/declarations>

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 a ? b : c 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 `char8_t`, (since C23) `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[]`, `char8_t[]` (since C23), `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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/expressions>

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 non-[inline](inline "c/language/inline") (since C99) function that is used in an expression (unless [unevaluated](expressions#Unevaluated_expressions "c/language/expressions")) must be [defined only once](extern#One_definition_rule "c/language/extern") in a program.


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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/functions>

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 [n3096](https://open-std.org/JTC1/SC22/WG14/www/docs/n3096.pdf) 2023-04-01)

 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

 

|  |  |
| --- | --- |
| 1.  | [The Development of the C Language](https://www.bell-labs.com/usr/dmr/www/chist.html) by Dennis M. Ritchie  |
| 2.  | [Rationale for the C99 standard](https://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/history>

Comments
========

 Comments serve as a sort of in-code documentation. When inserted into a program, they are effectively ignored by the compiler; they are solely intended to be used as notes by the humans that read source code.


###  Syntax

 

|  |  |  |
| --- | --- | --- |
| `/*` comment `*/` |  (1)  |  |
| `//` comment |  (2)  | (since C99) |

 
1) Often known as "C-style" or "multi-line" comments. 
2) Often known as "C++-style" or "single-line" comments. All comments are removed from the program at [translation phase 3](language/translation_phases "c/language/translation phases") by replacing each comment with a single whitespace character.


###  C-style

 C-style comments are usually used to comment large blocks of text or small fragments of code; however, they can be used to comment single lines. To insert text as a C-style comment, simply surround the text with `/*` and `*/`. C-style comments tell the compiler to ignore all content between `/*` and `*/`. Although it is not part of the C standard, `/**` and `**/` are often used to indicate documentation blocks; this is legal because the second asterisk is simply treated as part of the comment.


Except within a [character constant](language/character_constant "c/language/character constant"), a [string literal](language/string_literal "c/language/string literal"), or a comment, the characters `/*` introduce a comment. The contents of such a comment are examined only to identify multibyte characters and to find the characters `*/` that terminate the comment. C-style comments cannot be nested.




|  |  |
| --- | --- |
|  C++-style C++-style comments are usually used to comment single lines of text or code; however, they can be placed together to form multi-line comments. To insert text as a C++-style comment, simply precede the text with `//` and follow the text with the new line character. C++-style comments tell the compiler to ignore all content between `//` and a new line.
Except within a [character constant](language/character_constant "c/language/character constant"), a [string literal](language/string_literal "c/language/string literal"), or a comment, the characters `//` introduce a comment that includes all multibyte characters up to, but not including, the next new-line character. The contents of such a comment are examined only to identify multibyte characters and to find the new-line character that terminates the comment. C++-style comments can be nested:

```
//  y = f(x);   // invoke algorithm
```
 A C-style comment may appear within a C++-style comment:

```
//  y = f(x);   /* invoke algorithm */
```
 A C++-style comment may appear within a C-style comment; this is a mechanism for excluding a small block of source code:

```
/*
    y = f(x);   // invoke algorithms
    z = g(x);
*/
```
 | (since C99) |

 ###  Notes

 Because comments [are removed](language/translation_phases "c/language/translation phases") before the preprocessor stage, a macro cannot be used to form a comment and an unterminated C-style comment doesn't spill over from an #include'd file.



```
/* An attempt to use a macro to form a comment. */
/* But, a space replaces characters "//".       */
#ifndef DEBUG
    #define PRINTF //
#else
    #define PRINTF printf
#endif
...  
PRINTF("Error in file %s at line %i\n", __FILE__, __LINE__);
```
 Besides commenting out, other mechanisms used for source code exclusion are:



```
#if 0
    puts("this will not be compiled");
    /* no conflict with C-style comments */
    // no conflict with C++-style comments
#endif
```
 and.



```
if(0) {
    puts("this will be compiled but not be executed");
    /* no conflict with C-style comments */
    // no conflict with C++-style comments
}
```
 The introduction of // comments in C99 was a breaking change in some rare circumstances:



```
a = b //*divisor:*/ c
+ d; /* C89 compiles a = b / c + d;
        C99 compiles a = b + d; */
```
 ###  Example

  
```
#include <stdio.h>
/*
C-style comments can contain
multiple lines.
*/
 
/* Or, just one line. */
 
// C++-style comments can comment one line.
 
// Or, they can
// be strung together.
 
int main(void)
{
  // The below code won't be run
  // puts("Hello");
 
  // The below code will be run
  puts("World");
 
  // A note regarding backslash + newline.
  // Despite belonging to translation phase 2 (vs phase 3 for comments),
  // '\' still determines which portion of the source code is considered
  // as 'comments':
  // This comment will be promoted to the next line \
  puts("Won't be run"); // may issue a warning "multi-line comment"
  puts("Hello, again");
}
```
 Output:



```
World
Hello, again
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 6.4.9 Comments (p: 54)

* C11 standard (ISO/IEC 9899:2011):
+ 6.4.9 Comments (p: 75)

* C99 standard (ISO/IEC 9899:1999):
+ 6.4.9 Comments (p: 66)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.1.9 Comments

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/comments "cpp/comments") for Comments |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/comment>

Variadic functions
==================

 Variadic functions are functions (e.g. `[printf](io/fprintf "c/io/fprintf")`) which take a variable number of arguments.


The declaration of a variadic function uses an ellipsis as the last parameter, e.g. `int [printf](http://en.cppreference.com/w/c/io/fprintf)(const char\* format, ...);`. See [variadic arguments](language/variadic "c/language/variadic") for additional detail on the syntax and automatic argument conversions.


Accessing the variadic arguments from the function body uses the following library facilities:




|  |
| --- |
|  Macros  |
|  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) |
|  Type  |
|  [va\_list](variadic/va_list "c/variadic/va list") |  holds the information needed by va\_start, va\_arg, va\_end, and va\_copy  (typedef) |

 ###  Example

 
Print values of different types.



```
#include <stdio.h>
#include <stdarg.h>
 
void simple_printf(const char* fmt, ...)
{
    va_list args;
    va_start(args, fmt);
 
    while (*fmt != '\0') {
        if (*fmt == 'd') {
            int i = va_arg(args, int);
            printf("%d\n", i);
        } else if (*fmt == 'c') {
            // A 'char' variable will be promoted to 'int'
            // A character literal in C is already 'int' by itself
            int c = va_arg(args, int);
            printf("%c\n", c);
        } else if (*fmt == 'f') {
            double d = va_arg(args, double);
            printf("%f\n", d);
        }
        ++fmt;
    }
 
    va_end(args);
}
 
int main(void)
{
    simple_printf("dcff", 3, 'a', 1.999, 42.5); 
}
```
 Output:



```
3
a
1.999000
42.50000
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.16 Variable arguments <stdarg.h> (p: 269-272)

* C99 standard (ISO/IEC 9899:1999):
+ 7.15 Variable arguments <stdarg.h> (p: 249-252)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.8 VARIABLE ARGUMENTS <stdarg.h>

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/variadic "cpp/utility/variadic") for Variadic functions |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/variadic>

ASCII Chart
===========

 The following chart contains all 128 ASCII decimal **(dec)**, octal **(oct)**, hexadecimal **(hex)** and character **(ch)** codes.




|  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `dec` | `oct` | `hex` | `ch` |  | `dec` | `oct` | `hex` | `ch` |  | `dec` | `oct` | `hex` | `ch` |  | `dec` | `oct` | `hex` | `ch` |
|  `0` | `0` | `00` | `NUL` (null)  | `32` | `40` | `20` | (space)  | `64` | `100` | `40` | `@` |  `96` | `140` | `60` | ``` |
|  `1` | `1` | `01` | `SOH` (start of header)  | `33` | `41` | `21` | `!` | `65` | `101` | `41` | `A` |  `97` | `141` | `61` | `a` |
|  `2` | `2` | `02` | `STX` (start of text)  | `34` | `42` | `22` | `"` | `66` | `102` | `42` | `B` |  `98` | `142` | `62` | `b` |
|  `3` | `3` | `03` | `ETX` (end of text)  | `35` | `43` | `23` | `#` | `67` | `103` | `43` | `C` |  `99` | `143` | `63` | `c` |
|  `4` | `4` | `04` | `EOT` (end of transmission)  | `36` | `44` | `24` | `$` | `68` | `104` | `44` | `D` | `100` | `144` | `64` | `d` |
|  `5` | `5` | `05` | `ENQ` (enquiry)  | `37` | `45` | `25` | `%` | `69` | `105` | `45` | `E` | `101` | `145` | `65` | `e` |
|  `6` | `6` | `06` | `ACK` (acknowledge)  | `38` | `46` | `26` | `&` | `70` | `106` | `46` | `F` | `102` | `146` | `66` | `f` |
|  `7` | `7` | `07` | `BEL` (bell)  | `39` | `47` | `27` | `'` | `71` | `107` | `47` | `G` | `103` | `147` | `67` | `g` |
|  `8` | `10` | `08` | `BS` (backspace)  | `40` | `50` | `28` | `(` | `72` | `110` | `48` | `H` | `104` | `150` | `68` | `h` |
|  `9` | `11` | `09` | `HT` (horizontal tab)  | `41` | `51` | `29` | `)` | `73` | `111` | `49` | `I` | `105` | `151` | `69` | `i` |
| `10` | `12` | `0a` | `LF` (line feed - new line)  | `42` | `52` | `2a` | `*` | `74` | `112` | `4a` | `J` | `106` | `152` | `6a` | `j` |
| `11` | `13` | `0b` | `VT` (vertical tab)  | `43` | `53` | `2b` | `+` | `75` | `113` | `4b` | `K` | `107` | `153` | `6b` | `k` |
| `12` | `14` | `0c` | `FF` (form feed - new page)  | `44` | `54` | `2c` | `,` | `76` | `114` | `4c` | `L` | `108` | `154` | `6c` | `l` |
| `13` | `15` | `0d` | `CR` (carriage return)  | `45` | `55` | `2d` | `-` | `77` | `115` | `4d` | `M` | `109` | `155` | `6d` | `m` |
| `14` | `16` | `0e` | `SO` (shift out)  | `46` | `56` | `2e` | `.` | `78` | `116` | `4e` | `N` | `110` | `156` | `6e` | `n` |
| `15` | `17` | `0f` | `SI` (shift in)  | `47` | `57` | `2f` | `/` | `79` | `117` | `4f` | `O` | `111` | `157` | `6f` | `o` |
| `16` | `20` | `10` | `DLE` (data link escape)  | `48` | `60` | `30` | `0` | `80` | `120` | `50` | `P` | `112` | `160` | `70` | `p` |
| `17` | `21` | `11` | `DC1` (device control 1)  | `49` | `61` | `31` | `1` | `81` | `121` | `51` | `Q` | `113` | `161` | `71` | `q` |
| `18` | `22` | `12` | `DC2` (device control 2)  | `50` | `62` | `32` | `2` | `82` | `122` | `52` | `R` | `114` | `162` | `72` | `r` |
| `19` | `23` | `13` | `DC3` (device control 3)  | `51` | `63` | `33` | `3` | `83` | `123` | `53` | `S` | `115` | `163` | `73` | `s` |
| `20` | `24` | `14` | `DC4` (device control 4)  | `52` | `64` | `34` | `4` | `84` | `124` | `54` | `T` | `116` | `164` | `74` | `t` |
| `21` | `25` | `15` | `NAK` (negative acknowledge)  | `53` | `65` | `35` | `5` | `85` | `125` | `55` | `U` | `117` | `165` | `75` | `u` |
| `22` | `26` | `16` | `SYN` (synchronous idle)  | `54` | `66` | `36` | `6` | `86` | `126` | `56` | `V` | `118` | `166` | `76` | `v` |
| `23` | `27` | `17` | `ETB` (end of transmission block)  | `55` | `67` | `37` | `7` | `87` | `127` | `57` | `W` | `119` | `167` | `77` | `w` |
| `24` | `30` | `18` | `CAN` (cancel)  | `56` | `70` | `38` | `8` | `88` | `130` | `58` | `X` | `120` | `170` | `78` | `x` |
| `25` | `31` | `19` | `EM` (end of medium)  | `57` | `71` | `39` | `9` | `89` | `131` | `59` | `Y` | `121` | `171` | `79` | `y` |
| `26` | `32` | `1a` | `SUB` (substitute)  | `58` | `72` | `3a` | `:` | `90` | `132` | `5a` | `Z` | `122` | `172` | `7a` | `z` |
| `27` | `33` | `1b` | `ESC` (escape)  | `59` | `73` | `3b` | `;` | `91` | `133` | `5b` | `[` | `123` | `173` | `7b` | `{` |
| `28` | `34` | `1c` | `FS` (file separator)  | `60` | `74` | `3c` | `<` | `92` | `134` | `5c` | `\`  | `124` | `174` | `7c` | `|` |
| `29` | `35` | `1d` | `GS` (group separator)  | `61` | `75` | `3d` | `=` | `93` | `135` | `5d` | `]` | `125` | `175` | `7d` | `}` |
| `30` | `36` | `1e` | `RS` (record separator)  | `62` | `76` | `3e` | `>` | `94` | `136` | `5e` | `^` | `126` | `176` | `7e` | `~` |
| `31` | `37` | `1f` | `US` (unit separator)  | `63` | `77` | `3f` | `?` | `95` | `137` | `5f` | `_` | `127` | `177` | `7f` | `DEL` (delete)  |

 Note: in Unicode, the ASCII character block is known as [`U+0000..U+007F` Basic Latin](http://www.unicode.org/charts/PDF/U0000.pdf).


###  Example

  
```
#include <stdio.h>
 
int main(void)
{
    puts("Printable ASCII:");
    for (int i = 32; i < 127; ++i) {
        putchar(i);
        putchar(i % 16 == 15 ? '\n' : ' ');
    }
}
```
 Possible output:



```
Printable ASCII:
  ! " # $ % & ' ( ) * + , - . /
0 1 2 3 4 5 6 7 8 9 : ; < = > ?
@ 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 { | } ~
```
  ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/ascii "cpp/language/ascii") for ASCII Chart |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/ascii>

Localization support
====================

 

|  Defined in header `<locale.h>` |
| --- |
|  [setlocale](locale/setlocale "c/locale/setlocale") |  gets and sets the current C locale  (function) |
|  [localeconv](locale/localeconv "c/locale/localeconv") |  queries numeric and monetary formatting details of the current locale  (function) |
|  [lconv](locale/lconv "c/locale/lconv") |  formatting details, returned by `[localeconv](http://en.cppreference.com/w/c/locale/localeconv)`  (struct) |
|  Locale categories  |
|  [LC\_ALLLC\_COLLATELC\_CTYPELC\_MONETARYLC\_NUMERICLC\_TIME](locale/lc_categories "c/locale/LC categories") |  locale categories for `[setlocale](http://en.cppreference.com/w/c/locale/setlocale)`  (macro constant) |

 ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.11 Localization <locale.h> (p: 223-230)
+ 7.31.6 Localization <locale.h> (p: 455)

* C99 standard (ISO/IEC 9899:1999):
+ 7.11 Localization <locale.h> (p: 204-211)
+ 7.26.5 Localization <locale.h> (p: 401)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.4 LOCALIZATION <locale.h>
+ 4.13.3 Localization <locale.h>

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/locale "cpp/locale") for Localization library |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/locale>

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

 * C17 standard (ISO/IEC 9899:2018):
+ 7.6 Floating-point environment <fenv.h> (p: 150-156)
+ 7.31.4 Floating-point environment <fenv.h> (p: 332)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/fenv>

Character sets and encodings
============================

 ###  Basic character set

  The *basic character set* consists of the following 95 characters:




|  Code unit | Character | Glyph  |
| --- | --- | --- |
| U+0009 | Character tabulation |  |
| U+000B | Line tabulation |  |
| U+000C | Form feed (FF) |  |
| U+0020 | Space |  |
| U+0021 | Exclamation mark | `!` |
| U+0022 | Quotation mark | `"` |
| U+0023 | Number sign | `#` |
| U+0025 | Percent sign | `%` |
| U+0026 | Ampersand | `&` |
| U+0027 | Apostrophe | `'` |
| U+0028 | Left parenthesis | `(` |
| U+0029 | Right parenthesis | `)` |
| U+002A | Asterisk | `*` |
| U+002B | Plus sign | `+` |
| U+002C | Comma | `,` |
| U+002D | Hyphen-minus | `-` |
| U+002E | Full stop | `.` |
| U+002F | Solidus | `/` |
| U+0030 .. U+0039 | Digit zero .. nine | `0 1 2 3 4 5 6 7 8 9` |
| U+003A | Colon | `:` |
| U+003B | Semicolon | `;` |
| U+003C | Less-than sign | `<` |
| U+003D | Equals sign | `=` |
| U+003E | Greater-than sign | `>` |
| U+003F | Question mark | `?` |
| U+0041 .. U+005A | Latin capital letter A .. 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`. |
| U+005B | Left square bracket | `[` |
| U+005C | Reverse solidus | `\` |
| U+005D | Right square bracket | `]` |
| U+005E | Circumflex accent | `^` |
| U+005F | Low line | `_` |
| U+0061 .. U+007A | Latin small letter a .. 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`. |
| U+007B | Left curly bracket | `{` |
| U+007C | Vertical line | `|` |
| U+007D | Right curly bracket | `}` |
| U+007E | Tilde | `~` |

 Unlike C++, the U+000A LINE FEED (LF) character is not included in basic 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 character set is also known as *basic source character set*.


###  Basic execution character set

 The *basic execution character set* contains all the members of the basic character set, plus the following characters:




|  Code unit  |  Character  |
| --- | --- |
| U+0000 | Null  |
| U+0007 | Bell  |
| U+0008 | Backspace  |
| U+000A | Line feed (LF)  |
| U+000D | Carriage return (CR)  |

 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 U+0000 NULL character has the value 0.


The representation of each member of the basic execution character sets fit in a byte.


In C++, basic execution character set is also known as *basic literal character set* and *basic execution wide-character set*.


###  Literal encodings

 The *literal encoding* is an implementation-defined mapping of the characters of the execution character set to the values in a [character constant](character_constant "c/language/character constant") or [string literal](string_literal "c/language/string literal") without encoding prefix. It supports a mapping from all the basic execution character set values into the implementation-defined encoding. It may contain multibyte character sequences.




|  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| The following characters are not in basic execution character set, but they are required to be encoded as a single byte in an ordinary character constant or ordinary string literal.

|  Code unit | Character | Glyph  |
| --- | --- | --- |
| U+0024 | Dollar Sign | `$` |
| U+0040 | Commercial At | `@` |
| U+0060 | Grave Accent | ``` |

 | (since C23) |

 The *wide literal encoding* is an implementation-defined mapping of the characters of the execution character set to the values in an `L`-prefixed character constant or string literal. It supports a mapping from all the basic execution character set values into the implementation-defined encoding. If an implementation does not define `__STDC_MB_MIGHT_NEQ_WC__`, the mapping produces values identical to the literal encoding for all the basic execution character set values. One or more values may map to one or more values of the extended execution character set.




|  |  |
| --- | --- |
| The UTF-8 encoding is used for mapping characters of the execution character set to a `u8`-prefixed character constant or (since C23) string literal.
An implementation-defined encoding (until C23)The UTF-16 encoding (since C23) is used for mapping characters of the execution character set to a `u`-prefixed character constant or string literal.
An implementation-defined encoding (until C23)The UTF-32 encoding (since C23) is used for mapping characters of the execution character set to a `U`-prefixed character constant or string literal. | (since C11) |

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/charset>

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. (until C23)
 ###  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` or `#embed` (since C23) directive, in `__has_include` and `__has_embed` expressions (since C23) 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

 * C17 standard (ISO/IEC 9899:2018):
+ 5.1.1.2 Translation phases (p: 9-10)
+ 5.2.1 Character sets (p: 17)
+ 6.4 Lexical elements (p: 41-54)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/translation_phases>

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 an [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 an [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 an 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"), [`_Alignof`](_alignof "c/language/ Alignof") (since C11) , [`typeof`](typeof "c/language/typeof") or [`typeof_unqual`](https://en.cppreference.com/mwiki/index.php?title=c/language/typeof_unqual&action=edit&redlink=1 "c/language/typeof unqual (page does not exist)") (since C23) expression, delimit the operand.
* In an [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 an [`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.
* In a [function-like macro invocation](../preprocessor/replace#Function-like_macros "c/preprocessor/replace"), delimit the macro arguments or prevent commas from being interpreted as argument separators.
* Part of a `defined`, `__has_include`, `__has_embed` 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)
* Part of [`__VA_OPT__`](../preprocessor/replace "c/preprocessor/replace") replacement in a variadic macro definition. (since C23)
* In a preprocessor parameter used in [`#embed` directives](../preprocessor/embed "c/preprocessor/embed") and `__has_embed` preprocessing expressions, delimit the preprocessor parameter clause. (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.
* Introduce an [enum base](enum "c/language/enum"), which specifies the underlying type of the enum. (since C23)
* In a [generic association](generic "c/language/generic"), delimit the type-id or `default` and the selected expression. (since C11)

 ###  `...`

 * 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 an [attribute](attributes "c/language/attributes"), indicate attribute scope. (since C23)
* In a preprocessor prefixed parameter (used by [`#embed`](../preprocessor/embed "c/preprocessor/embed") and `__has_embed`), indicate 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 an [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")
+ a [`__has_include` preprocessing expression](../preprocessor/include "c/preprocessor/include") (since C23)
+ a [`#embed` directive](../preprocessor/embed "c/preprocessor/embed") (since C23)
+ a [`__has_embed` preprocessing expression](../preprocessor/embed "c/preprocessor/embed") (since C23)
+ implementation-defined locations within a [`#pragma` directive](../preprocessor/impl "c/preprocessor/impl")

 ###  `>`

 * [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")
+ a [`__has_include` preprocessing expression](../preprocessor/include "c/preprocessor/include") (since C23)
+ a [`#embed` directive](../preprocessor/embed "c/preprocessor/embed") (since C23)
+ a [`__has_embed` preprocessing expression](../preprocessor/embed "c/preprocessor/embed") (since C23)
+ implementation-defined locations within a [`#pragma` directive](../preprocessor/impl "c/preprocessor/impl")

 ###  `<=`

 * [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 an [enum](enum "c/language/enum") declaration
+ a function parameter list
+ the macro parameter list in a [function-like macro definition](../preprocessor/replace#Function-like_macros "c/preprocessor/replace")
+ the macro argument list in a [function-like macro invocation](../preprocessor/replace#Function-like_macros "c/preprocessor/replace"), unless found between an inner set of parentheses
+ 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"), separate the controlling expression and the generic association list. (since C11)

 ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 6.4.6 Punctuators (p: 68-69)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/punctuators>

Dynamic memory management
=========================

 ###  Functions

 

|  Defined in header `<stdlib.h>` |
| --- |
|  [malloc](memory/malloc "c/memory/malloc") |  allocates memory  (function) |
|  [calloc](memory/calloc "c/memory/calloc") |  allocates and zeroes memory  (function) |
|  [realloc](memory/realloc "c/memory/realloc") |  expands previously allocated memory block  (function) |
|  [free](memory/free "c/memory/free") |  deallocates previously allocated memory  (function) |
|  [free\_sized](memory/free_sized "c/memory/free sized")
(C23) |  deallocates previously allocated sized memory  (function) |
|  [free\_aligned\_sized](memory/free_aligned_sized "c/memory/free aligned sized")
(C23) |  deallocates previously allocated sized and aligned memory  (function) |
|  [aligned\_alloc](memory/aligned_alloc "c/memory/aligned alloc")
(C11) |  allocates aligned memory  (function) |

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/memory/c "cpp/memory/c") for C memory management library |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/memory>

Algorithms
==========

 

|  Defined in header `<stdlib.h>` |
| --- |
|  [qsortqsort\_s](algorithm/qsort "c/algorithm/qsort")
(C11) |  sorts a range of elements with unspecified type  (function) |
|  [bsearchbsearch\_s](algorithm/bsearch "c/algorithm/bsearch")
(C11) |  searches an array for an element of unspecified type  (function) |

 ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.22.5 Searching and sorting utilities (p: 354-356)
+ K.3.6.3 Searching and sorting utilities (p: 607-609)

* C99 standard (ISO/IEC 9899:1999):
+ 7.20.5 Searching and sorting utilities (p: 318-319)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.5 Searching and sorting utilities

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/algorithm "cpp/algorithm") for Algorithms library |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/algorithm>

Numerics
========

 The C numerics library includes common mathematical functions and types, as well as support for random number generation.


###   [Common mathematical functions](numeric/math "c/numeric/math")

 The header `math.h` provides [standard C library mathematical functions](numeric/math "c/numeric/math") such as `[fabs](numeric/math/fabs "c/numeric/math/fabs")`, `[sqrt](numeric/math/sqrt "c/numeric/math/sqrt")`, and `[sin](numeric/math/sin "c/numeric/math/sin")`.


###   [Floating-point environment](numeric/fenv "c/numeric/fenv")

 The header `fenv.h` defines [flags and functions related to exceptional floating-point state](numeric/fenv "c/numeric/fenv"), such as overflow and division by zero.


###   [Pseudo-random number generation](numeric/random "c/numeric/random")

 The header `stdlib.h` also includes C-style random number generation via `[srand](numeric/random/srand "c/numeric/random/srand")` and `[rand](numeric/random/rand "c/numeric/random/rand")`.


###   [Complex number arithmetic](numeric/complex "c/numeric/complex")

 The header `complex.h` provides types and functions about [complex numbers](numeric/complex "c/numeric/complex").


###   [Type-generic math](numeric/tgmath "c/numeric/tgmath")

 The header `tgmath.h` provides some macros for a function which names XXX:


* real function:
+ `float` variant `XXXf`
+ `double` variant `XXX`
+ `long double` variant `XXXl`

* complex function:
+ `float` variant `cXXXf`
+ `double` variant `cXXX`
+ `long double` variant `cXXXl`

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/numeric "cpp/numeric") for Numerics library |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric>

Fixed width integer types (since C99)
=====================================

 ###  Types

 

|  Defined in header `<stdint.h>` |
| --- |
| `int8_t``int16_t``int32_t``int64_t` |  signed integer type with width of exactly 8, 16, 32 and 64 bits respectivelywith no padding bits and using 2's complement for negative values(provided only if the implementation directly supports the type)  |
| `int_fast8_t``int_fast16_t``int_fast32_t``int_fast64_t` |  fastest signed integer type with width of at least 8, 16, 32 and 64 bits respectively  |
| `int_least8_t``int_least16_t``int_least32_t``int_least64_t` |  smallest signed integer type with width of at least 8, 16, 32 and 64 bits respectively  |
| `intmax_t` |  maximum width integer type  |
| `intptr_t` |  integer type capable of holding a pointer  |
| `uint8_t``uint16_t``uint32_t``uint64_t` |  unsigned integer type with width of exactly 8, 16, 32 and 64 bits respectively (provided only if the implementation directly supports the type)  |
| `uint_fast8_t``uint_fast16_t``uint_fast32_t``uint_fast64_t` |  fastest unsigned integer type with width of at least 8, 16, 32 and 64 bits respectively  |
| `uint_least8_t``uint_least16_t``uint_least32_t``uint_least64_t` |  smallest unsigned integer type with width of at least 8, 16, 32 and 64 bits respectively  |
| `uintmax_t` |  maximum width unsigned integer type  |
| `uintptr_t` |  unsigned integer type capable of holding a pointer  |

 The implementation may define typedef names `int*N*_t`, `int_fast*N*_t`, `int_least*N*_t`, `uint*N*_t`, `uint_fast*N*_t`, and `uint_least*N*_t` when *N* is not 8, 16, 32 or 64. Typedef names of the form `int*N*_t` may only be defined if the implementation supports an integer type of that width with no padding. Thus, uint24\_t denotes an unsigned integer type with a width of exactly 24 bits.


Each of the macros listed in below is defined if and only if the implementation defines the corresponding typedef name. The macros `INT*N*_C` and `UINT*N*_C` correspond to the typedef names `int_least*N*_t` and `uint_least*N*_t`, respectively.


###  Macro constants

 

|  Defined in header `<stdint.h>` |
| --- |
|  Signed integers : width  |
| INT8\_WIDTHINT16\_WIDTHINT32\_WIDTHINT64\_WIDTH
(C23)(optional) |  bit width of an object of type int8\_t, int16\_t, int32\_t, int64\_t (exactly 8, 16, 32, 64)  (macro constant) |
| INT\_FAST8\_WIDTHINT\_FAST16\_WIDTHINT\_FAST32\_WIDTHINT\_FAST64\_WIDTH
(C23) |  bit width of an object of type int\_fast8\_t, int\_fast16\_t, int\_fast32\_t, int\_fast64\_t  (macro constant) |
| INT\_LEAST8\_WIDTHINT\_LEAST16\_WIDTHINT\_LEAST32\_WIDTHINT\_LEAST64\_WIDTH
(C23) |  bit width of an object of type int\_least8\_t, int\_least16\_t, int\_least32\_t, int\_least64\_t  (macro constant) |
| INTPTR\_WIDTH
(C23)(optional) |  bit width of an object of type intptr\_t  (macro constant) |
| INTMAX\_WIDTH
(C23) |  bit width of an object of type intmax\_t  (macro constant) |
|  Signed integers : minimum value  |
| INT8\_MININT16\_MININT32\_MININT64\_MIN |  minimum value of an object of type int8\_t, int16\_t, int32\_t, int64\_t  (macro constant) |
| INT\_FAST8\_MININT\_FAST16\_MININT\_FAST32\_MININT\_FAST64\_MIN |  minimum value of an object of type int\_fast8\_t, int\_fast16\_t, int\_fast32\_t, int\_fast64\_t  (macro constant) |
| INT\_LEAST8\_MININT\_LEAST16\_MININT\_LEAST32\_MININT\_LEAST64\_MIN |  minimum value of an object of type int\_least8\_t, int\_least16\_t, int\_least32\_t, int\_least64\_t  (macro constant) |
| INTPTR\_MIN |  minimum value of an object of type intptr\_t  (macro constant) |
| INTMAX\_MIN |  minimum value of an object of type intmax\_t  (macro constant) |
|  Signed integers : maximum value  |
| INT8\_MAXINT16\_MAXINT32\_MAXINT64\_MAX |  maximum value of an object of type int8\_t, int16\_t, int32\_t, int64\_t  (macro constant) |
| INT\_FAST8\_MAXINT\_FAST16\_MAXINT\_FAST32\_MAXINT\_FAST64\_MAX |  maximum value of an object of type int\_fast8\_t, int\_fast16\_t, int\_fast32\_t, int\_fast64\_t  (macro constant) |
| INT\_LEAST8\_MAXINT\_LEAST16\_MAXINT\_LEAST32\_MAXINT\_LEAST64\_MAX |  maximum value of an object of type int\_least8\_t, int\_least16\_t, int\_least32\_t, int\_least64\_t  (macro constant) |
| INTPTR\_MAX |  maximum value of an object of type intptr\_t  (macro constant) |
| INTMAX\_MAX |  maximum value of an object of type intmax\_t  (macro constant) |
|  Unsigned integers : width  |
| UINT8\_WIDTHUINT16\_WIDTHUINT32\_WIDTHUINT64\_WIDTH
(C23)(optional) |  bit width of an object of type uint8\_t, uint16\_t, uint32\_t, uint64\_t (exactly 8, 16, 32, 64)  (macro constant) |
| UINT\_FAST8\_WIDTHUINT\_FAST16\_WIDTHUINT\_FAST32\_WIDTHUINT\_FAST64\_WIDTH
(C23) |  bit width of an object of type uint\_fast8\_t, uint\_fast16\_t, uint\_fast32\_t, uint\_fast64\_t  (macro constant) |
| UINT\_LEAST8\_WIDTHUINT\_LEAST16\_WIDTHUINT\_LEAST32\_WIDTHUINT\_LEAST64\_WIDTH
(C23) |  bit width of an object of type uint\_least8\_t, uint\_least16\_t, uint\_least32\_t, uint\_least64\_t  (macro constant) |
| UINTPTR\_WIDTH
(C23)(optional) |  bit width of an object of type uintptr\_t  (macro constant) |
| UINTMAX\_WIDTH
(C23) |  bit width of an object of type uintmax\_t  (macro constant) |
|  Unsigned integers : maximum value  |
| UINT8\_MAXUINT16\_MAXUINT32\_MAXUINT64\_MAX |  maximum value of an object of type uint8\_t, uint16\_t, uint32\_t, uint64\_t  (macro constant) |
| UINT\_FAST8\_MAXUINT\_FAST16\_MAXUINT\_FAST32\_MAXUINT\_FAST64\_MAX |  maximum value of an object of type uint\_fast8\_t, uint\_fast16\_t, uint\_fast32\_t, uint\_fast64\_t  (macro constant) |
| UINT\_LEAST8\_MAXUINT\_LEAST16\_MAXUINT\_LEAST32\_MAXUINT\_LEAST64\_MAX |  maximum value of an object of type uint\_least8\_t, uint\_least16\_t, uint\_least32\_t, uint\_least64\_t  (macro constant) |
| UINTPTR\_MAX |  maximum value of an object of type uintptr\_t  (macro constant) |
| UINTMAX\_MAX |  maximum value of an object of type uintmax\_t  (macro constant) |

 ###  Function macros for minimum-width integer constants

 

|  |  |
| --- | --- |
| INT8\_CINT16\_CINT32\_CINT64\_C |  expands to an integer constant expression having the value specified by its argument and the type int\_least8\_t, int\_least16\_t, int\_least32\_t, int\_least64\_t respectively  (function macro) |
| INTMAX\_C |  expands to an integer constant expression having the value specified by its argument and the type intmax\_t  (function macro) |
| UINT8\_CUINT16\_CUINT32\_CUINT64\_C |  expands to an integer constant expression having the value specified by its argument and the type uint\_least8\_t, uint\_least16\_t, uint\_least32\_t, uint\_least64\_t respectively  (function macro) |
| UINTMAX\_C |  expands to an integer constant expression having the value specified by its argument and the type uintmax\_t  (function macro) |

 
```
#include <stdint.h>
UINT64_C(0x123) // might expand to 0x123ULL or 0x123UL
```
 ###  Format macro constants

 

|  Defined in header `<inttypes.h>` |
| --- |

 ####  Format constants for the `[fprintf](../io/fprintf "c/io/fprintf")` family of functions

 Each of the `PRI` macros listed here is defined if and only if the implementation defines the corresponding typedef name.




| Equivalentfor int orunsigned int | Description  | Macros for data types  |
| --- | --- | --- |
| `[u]intx_t`
 | `[u]int_leastx_t` | `[u]int_fastx_t` | `[u]intmax_t` | `[u]intptr_t` |
| `d` | output of a signed decimal integer value  | PRId**x** | PRIdLEAST**x** | PRIdFAST**x** | PRIdMAX  | PRIdPTR  |
| `i` | PRIi**x** | PRIiLEAST**x** | PRIiFAST**x** | PRIiMAX  | PRIiPTR  |
| `u` | output of an unsigned decimal integer value  | PRIu**x** | PRIuLEAST**x** | PRIuFAST**x** | PRIuMAX  | PRIuPTR  |
| `o` | output of an unsigned octal integer value  | PRIo**x** | PRIoLEAST**x** | PRIoFAST**x** | PRIoMAX  | PRIoPTR  |
| `x` | output of an unsigned lowercase hexadecimal integer value  | PRIx**x** | PRIxLEAST**x** | PRIxFAST**x** | PRIxMAX  | PRIxPTR  |
| `X` | output of an unsigned uppercase hexadecimal integer value  | PRIX**x** | PRIXLEAST**x** | PRIXFAST**x** | PRIXMAX  | PRIXPTR  |

 ####  Format constants for the `[fscanf](../io/fscanf "c/io/fscanf")` family of functions

 Each of the `SCN` macros listed in here is defined if and only if the implementation defines the corresponding typedef name and has a suitable `[fscanf](../io/fscanf "c/io/fscanf")` length modifier for the type.




| Equivalentfor int orunsigned int | Description  | Macros for data types  |
| --- | --- | --- |
| `[u]intx_t`
 | `[u]int_leastx_t` | `[u]int_fastx_t` | `[u]intmax_t` | `[u]intptr_t` |
| `d` | input of a signed decimal integer value  | SCNd**x** | SCNdLEAST**x** | SCNdFAST**x** | SCNdMAX  | SCNdPTR  |
| `i` | input of a signed integer value (base is determined by the first characters parsed)  | SCNi**x** | SCNiLEAST**x** | SCNiFAST**x** | SCNiMAX  | SCNiPTR  |
| `u` | input of an unsigned decimal integer value  | SCNu**x** | SCNuLEAST**x** | SCNuFAST**x** | SCNuMAX  | SCNuPTR  |
| `o` | input of an unsigned octal integer value  | SCNo**x** | SCNoLEAST**x** | SCNoFAST**x** | SCNoMAX  | SCNoPTR  |
| `x` | input of an unsigned hexadecimal integer value  | SCNx**x** | SCNxLEAST**x** | SCNxFAST**x** | SCNxMAX  | SCNxPTR  |

 ###  Example

  
```
#include <inttypes.h>
#include <stdio.h>
 
int main(void)
{
    printf("%zu\n", sizeof(int64_t));
    printf("%s\n", PRId64);
    printf("%+"PRId64"\n", INT64_MIN);
    printf("%+"PRId64"\n", INT64_MAX);
 
    int64_t n = 7;
    printf("%+"PRId64"\n", n);
}
```
 Possible output:



```
8
lld
-9223372036854775808
+9223372036854775807
+7
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.8.1 Macros for format specifiers (p: TBD)
+ 7.18 Integer types <stdint.h> (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.8.1 Macros for format specifiers (p: 158-159)
+ 7.18 Integer types <stdint.h> (p: 212-216)

* C11 standard (ISO/IEC 9899:2011):
+ 7.8.1 Macros for format specifiers (p: 217-218)
+ 7.18 Integer types <stdint.h> (p: 289-295)

* C99 standard (ISO/IEC 9899:1999):
+ 7.8.1 Macros for format specifiers (p: 198-199)
+ 7.18 Integer types <stdint.h> (p: 255-261)

 ###  See also

 * [Arithmetic types](../language/arithmetic_types "c/language/arithmetic types")

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/types/integer "cpp/types/integer") for Fixed width integer types |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/types/integer>

Identifier
==========

 An *identifier* is an arbitrarily long sequence of digits, underscores, lowercase and uppercase Latin letters, and Unicode characters specified using `\u` and `\U` [escape](escape "c/language/escape") notation (since C99), of class [XID\_Continue](https://www.unicode.org/reports/tr31/#Table_Lexical_Classes_for_Identifiers) (since C23). A valid identifier must begin with a non-digit character (Latin letter, underscore, or Unicode non-digit character (since C99)(until C23), or Unicode character of class [XID\_Start](https://www.unicode.org/reports/tr31/#Table_Lexical_Classes_for_Identifiers)) (since C23)). Identifiers are case-sensitive (lowercase and uppercase letters are distinct). Every identifier must conform to [Normalization Form C](https://www.unicode.org/charts/normalization/). (since C23).




|  |  |
| --- | --- |
| It is implementation-defined if raw (not escaped) Unicode characters are allowed in identifiers:

```
char *\U0001f431 = "cat"; // supported
char *🐱 = "cat"; // implementation-defined
                  // (e.g. works with Clang, but not GCC prior to version 10)
                  // both are ill formed in C23. Emoji are not XID_Start characters
```
 | (since C99)(until C23) |

 

|  |  |
| --- | --- |
| Implementation-defined characters whose corresponding code points in [ISO/IEC 10646](http://unicode.org/L2/L2010/10038-fcd10646-main.pdf) (Unicode) have the XID\_Start or XID\_Continue property can appear in the beginning or after the first character of an identifier respectively. | (since C23) |

 Identifiers can denote the following types of entities:


* [objects](object "c/language/object")
* [functions](functions "c/language/functions")
* tags ([struct](struct "c/language/struct"), [union](union "c/language/union"), or [enumerations](enum "c/language/enum"))
* structure or union members
* enumeration constants
* [typedef](typedef "c/language/typedef") names
* [label](statements#Labels "c/language/statements") names
* [macro](../preprocessor/replace "c/preprocessor/replace") names
* [macro parameter](../preprocessor/replace "c/preprocessor/replace") names

 Every identifier other than macro names or macro parameter names has [scope](scope "c/language/scope"), belongs to a [name space](name_space "c/language/name space"), and may have [linkage](storage_duration "c/language/storage duration"). The same identifier can denote different entities at different points in the program, or may denote different entities at the same point if the entities are in different name spaces.


###  Reserved identifiers

 The following identifiers are *reserved* and may not be declared in a program (doing so invokes undefined behavior):


1. The identifiers that are [keywords](../keyword "c/keyword") cannot be used for other purposes. In particular #define or #undef of an identifier that is identical to a keyword is not allowed.
2. All external identifiers that begin with an underscore.
3. All identifiers that begin with an underscore followed by a capital letter or by another underscore (these reserved identifiers allow the library to use numerous behind-the-scenes non-external macros and functions).
4. All external identifiers defined by the standard library (in hosted environment). This means that no user-supplied external names are allowed to match any library names, not even if declaring a function that is identical to a library function.
5. Identifiers declared as reserved for the implementation or future use by the standard library (see below).
6. Identifiers declared as potentially reserved and provided by the implementation (see below). (since C23)

 All other identifiers are available. Identifiers that are not reserved or potentially reserved (since C23) can be used with no fear of unexpected collisions when moving programs from one compiler and library to another.


Note: in C++, identifiers with a double underscore anywhere are reserved everywhere; in C, only the ones that begin with a double underscore are reserved.


####  Reserved and potentially reserved identifiers in the library

 The standard library reserves every identifiers it provides. Reserved identifiers that have [external linkage](storage_duration "c/language/storage duration") (e.g. name of every standard function) are reserved regardless which header is included. Other reserved identifiers are reserved when any of its associated headers is included.




|  |  |
| --- | --- |
| Potentially reserved identifiers are intended to be used by the implementation and future revision of standard. If a potentially reserved identifier is provided by the implementation, it becomes reserved.
Implementations are only allowed to provide [external definitions](extern "c/language/extern") of potentially reserved identifiers that are reserved as function names.
Potentially reserved identifiers that are not provided by the implementation are not reserved. They can be declared or defined by the user without undefined behavior. However, such usage is not portable. | (since C23) |

 Following identifiers are reserved or potentially reserved (since C23) for the implementation or future use by the standard library.


* *function names*, all of which are potentially reserved (since C23)
	+ `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) and their -f and -l suffixed variants, in [`<complex.h>`](../numeric/complex "c/numeric/complex") (since C99)
	+ beginning with `is` or `to` followed by a lowercase letter, in [`<ctype.h>`](../string/byte "c/string/byte") and [`<wctype.h>`](../string/wide "c/string/wide") (since C95)
	+ beginning with `str` or `wcs` (since C23) followed by a lowercase letter, in [`<stdlib.h>`](../string/byte "c/string/byte") and [`<inttypes.h>`](../types/integer "c/types/integer") (since C23)
	+ beginning with `cr_`, in [`<math.h>`](../numeric/math "c/numeric/math") (since C23)
	+ beginning with `wcs` followed by a lowercase letter, in [`<wchar.h>`](../string/wide "c/string/wide") (since C95)
	+ beginning with `atomic_` followed by a lowercase letter, in [`<stdatomic.h>`](../thread "c/thread") (since C11)
	+ beginning with `cnd_`, `mtx_`, `thrd_` or `tss_` followed by a lowercase letter, in [`<threads.h>`](../thread "c/thread") (since C11)
* *typedef names*, all of which are potentially reserved (since C23)
	+ beginning with `int` or `uint` and ending with `_t`, in [`<stdint.h>`](../types/integer "c/types/integer") (since C99)
	+ beginning with `atomic_` or `memory_` followed by a lowercase letter, in [`<stdatomic.h>`](../thread "c/thread") (since C11)
	+ beginning with `cnd_`, `mtx_`, `thrd_` or `tss_` followed by a lowercase letter, in [`<threads.h>`](../thread "c/thread") (since C11)
* *macro names*
	+ beginning with `E` followed by a digit or an uppercase letter, in [`<errno.h>`](../error/errno_macros "c/error/errno macros")
	+ beginning with `FE_` followed by an uppercase letter, in [`<fenv.h>`](../numeric/fenv "c/numeric/fenv") (since C99)
	+ beginning with `DBL_`, `DEC32_`, `DEC64_`, `DEC128_`, `DEC_`, `FLT_`, or `LDBL_` followed by an uppercase letter, in [`<float.h>`](../types/limits "c/types/limits"); these identifiers are potentially reserved (since C23)
	+ beginning with `INT` or `UINT` and ending with `_MAX`, `_MIN`, `_WIDTH` (since C23), or `_C`, in [`<stdint.h>`](../types/integer "c/types/integer"); these identifiers are potentially reserved (since C23) (since C99)
	+ beginning with `PRI` or `SCN` followed by lowercase letter or the letter `X`, in [`<inttypes.h>`](../types/integer "c/types/integer"); these identifiers are potentially reserved (since C23) (since C99)
	+ beginning with `LC_` followed by an uppercase letter, in [`<locale.h>`](../locale/lc_categories "c/locale/LC categories")
	+ beginning with `FP_` followed by an uppercase letter, in [`<math.h>`](../numeric/math "c/numeric/math") (since C23)
	+ beginning with `MATH_` followed by an uppercase letter, in [`<math.h>`](../numeric/math "c/numeric/math"); these identifiers are potentially reserved (since C23)
	+ beginning with `SIG` or `SIG_` followed by an uppercase letter, in [`<signal.h>`](../program "c/program")
	+ beginning with `TIME_` followed by an uppercase letter, in [`<time.h>`](../chrono/timespec_get "c/chrono/timespec get") (since C11)
	+ beginning with `ATOMIC_` followed by an uppercase letter, in [`<stdatomic.h>`](../thread "c/thread"); these identifiers are potentially reserved (since C23) (since C11)
* *enumeration constants*, all of which are potentially reserved (since C23)
	+ beginning with `memory_order_` followed by a lowercase letter, in [`<stdatomic.h>`](../thread "c/thread") (since C11)
	+ beginning with `cnd_`, `mtx_`, `thrd_` or `tss_` followed by a lowercase letter, in [`<threads.h>`](../thread "c/thread") (since C11)

 

|  |  |
| --- | --- |
| Implementations are recommended to warn when on declaration or definition of potentially reserved identifiers, except when.* the declaration is a non-definition declaration of an identifier with external linkage provided by the implementation, and
* the type used in the declaration is [compatible](types#Compatible_types "c/language/types") with that used in the definition.
 | (since C23) |

 ###  Translation limits

 Even though there is no specific limit on the length of identifiers, early compilers had limits on the number of significant initial characters in identifiers and the linkers imposed stricter limits on the names with [external linkage](storage_duration "c/language/storage duration"). C requires that at least the following limits are supported by any standard-compliant implementation:




|  |  |
| --- | --- |
| * 31 significant initial characters in an internal identifier or a macro name
* 6 significant initial characters in an external identifier
* 511 external identifiers in one translation unit
* 127 identifiers with block scope declared in one block
* 1024 macro identifiers simultaneously defined in one preprocessing translation unit
 | (until C99) |
| * 63 significant initial characters in an internal identifier or a macro name
* 31 significant initial characters in an external identifier
* 4095 external identifiers in one translation unit
* 511 identifiers with block scope declared in one block
* 4095 macro identifiers simultaneously defined in one preprocessing translation unit
 | (since C99) |

 ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 5.2.4.1 Translation limits (p: 19-20)
+ 6.4.2 Identifiers (p: 43)
+ 6.10.8 Predefined macro names (p: 127-129)
+ 6.11.9 Predefined macro names (p: 130)
+ 7.31 Future library directions (p: 332-333)
+ K.3.1.2 Reserved identifiers (p: 425)

* C11 standard (ISO/IEC 9899:2011):
+ 5.2.4.1 Translation limits (p: 25-26)
+ 6.4.2 Identifiers (p: 59-60)
+ 6.10.8 Predefined macro names (p: 175-176)
+ 6.11.9 Predefined macro names (p: 179)
+ 7.31 Future library directions (p: 455-457)
+ K.3.1.2 Reserved identifiers (p: 584)

* C99 standard (ISO/IEC 9899:1999):
+ 5.2.4.1 Translation limits (p: 20-21)
+ 6.4.2 Identifiers (p: 51-52)
+ 6.10.8 Predefined macro names (p: 160-161)
+ 6.11.9 Predefined macro names (p: 163)
+ 7.26 Future library directions (p: 401-402)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 2.2.4.1 Translation limits
+ 3.1.2 Identifiers
+ 3.8.8 Predefined macro names

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/identifiers "cpp/language/identifiers") for Identifiers |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/identifier>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/scope>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/lifetime>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/name_space>

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

 Constructing a complete object type such that the number of bytes in its object representation is not representable in the type `[size\_t](../types/size_t "c/types/size t")` (i.e. the result type of [`sizeof`](sizeof "c/language/sizeof") operator), including forming such a VLA type at runtime, (since C99) is undefined behavior.


###  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](bit_field "c/language/bit field") 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
 | (until C23) |

 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, a program necessitating the composite type of both types has undefined behavior.
* 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.

 The element type of the composite type is the composite type of the two element types. 

|  |  |
| --- | --- |
| * 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.
 | (until C23) |

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

 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 (*)[]); // C23: Error: conflicting types for 'f'
// 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/type>

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, or copy another object into that object as an array of character type, 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/object>

Concurrency support library
===========================

 C includes built-in support for threads, atomic operations, mutual exclusion, condition variables, and thread-specific storages.


These features are optionally provided:


* if the macro constant `__STDC_NO_THREADS__` is defined by the compiler, the header `<threads.h>` and all of the names provided in it are not provided;
* if the macro constant `__STDC_NO_ATOMICS__` is defined by the compiler, the header `<stdatomic.h>` and all of the names provided in it are not provided.

 ###  Threads

 

|  Defined in header `<threads.h>` |
| --- |
| `thrd_t` |  implementation-defined complete object type identifying a thread  |
|  [thrd\_create](thread/thrd_create "c/thread/thrd create")
(C11) |  creates a thread  (function) |
|  [thrd\_equal](thread/thrd_equal "c/thread/thrd equal")
(C11) |  checks if two identifiers refer to the same thread  (function) |
|  [thrd\_current](thread/thrd_current "c/thread/thrd current")
(C11) |  obtains the current thread identifier  (function) |
|  [thrd\_sleep](thread/thrd_sleep "c/thread/thrd sleep")
(C11) |  suspends execution of the calling thread for the given period of time  (function) |
|  [thrd\_yield](thread/thrd_yield "c/thread/thrd yield")
(C11) |  yields the current time slice  (function) |
|  [thrd\_exit](thread/thrd_exit "c/thread/thrd exit")
(C11) |  terminates the calling thread  (function) |
|  [thrd\_detach](thread/thrd_detach "c/thread/thrd detach")
(C11) |  detaches a thread  (function) |
|  [thrd\_join](thread/thrd_join "c/thread/thrd join")
(C11) |  blocks until a thread terminates  (function) |
|  [thrd\_successthrd\_timedoutthrd\_busythrd\_nomemthrd\_error](thread/thrd_errors "c/thread/thrd errors")
(C11) |  indicates a thread error status  (constant) |
| thrd\_start\_t
(C11) |  a typedef of the function pointer type `int(*)(void*)`, used by `[thrd\_create](http://en.cppreference.com/w/c/thread/thrd_create)`  (typedef) |

 ###  Atomic operations

 

|  Defined in header `<stdatomic.h>` |
| --- |
|  Operations on atomic types  |
|  [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/atomic_lock_free_consts "c/atomic/ATOMIC LOCK FREE consts")
(C11) |  indicates that the given atomic type is lock-free  (macro constant) |
|  [atomic\_is\_lock\_free](atomic/atomic_is_lock_free "c/atomic/atomic is lock free")
(C11) |  indicates whether the atomic object is lock-free  (function) |
|  [atomic\_storeatomic\_store\_explicit](atomic/atomic_store "c/atomic/atomic store")
(C11) |  stores a value in an atomic object  (function) |
|  [atomic\_loadatomic\_load\_explicit](atomic/atomic_load "c/atomic/atomic load")
(C11) |  reads a value from an atomic object  (function) |
|  [atomic\_exchangeatomic\_exchange\_explicit](atomic/atomic_exchange "c/atomic/atomic exchange")
(C11) |  swaps a value with the value of an atomic object  (function) |
|  [atomic\_compare\_exchange\_strongatomic\_compare\_exchange\_strong\_explicitatomic\_compare\_exchange\_weakatomic\_compare\_exchange\_weak\_explicit](atomic/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) |
|  [atomic\_fetch\_addatomic\_fetch\_add\_explicit](atomic/atomic_fetch_add "c/atomic/atomic fetch add")
(C11) |  atomic addition  (function) |
|  [atomic\_fetch\_subatomic\_fetch\_sub\_explicit](atomic/atomic_fetch_sub "c/atomic/atomic fetch sub")
(C11) |  atomic subtraction  (function) |
|  [atomic\_fetch\_oratomic\_fetch\_or\_explicit](atomic/atomic_fetch_or "c/atomic/atomic fetch or")
(C11) |  atomic bitwise OR  (function) |
|  [atomic\_fetch\_xoratomic\_fetch\_xor\_explicit](atomic/atomic_fetch_xor "c/atomic/atomic fetch xor")
(C11) |  atomic bitwise exclusive OR  (function) |
|  [atomic\_fetch\_andatomic\_fetch\_and\_explicit](atomic/atomic_fetch_and "c/atomic/atomic fetch and")
(C11) |  atomic bitwise AND  (function) |
|  Flag type and operations  |
|  [atomic\_flag](atomic/atomic_flag "c/atomic/atomic flag")
(C11) |  lock-free atomic boolean flag  (struct) |
|  [atomic\_flag\_test\_and\_setatomic\_flag\_test\_and\_set\_explicit](atomic/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/atomic_flag_clear "c/atomic/atomic flag clear")
(C11) |  sets an atomic\_flag to false  (function) |
|  Initialization  |
|  [atomic\_init](atomic/atomic_init "c/atomic/atomic init")
(C11) |  initializes an existing atomic object  (function) |
|  [ATOMIC\_VAR\_INIT](atomic/atomic_var_init "c/atomic/ATOMIC VAR INIT")
(C11)(deprecated in C17)(removed in C23) |  initializes a new atomic object  (function macro) |
|  [ATOMIC\_FLAG\_INIT](atomic/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) |
|  Memory synchronization ordering  |
|  [memory\_order](atomic/memory_order "c/atomic/memory order")
(C11) |  defines memory ordering constraints  (enum) |
|  [kill\_dependency](atomic/kill_dependency "c/atomic/kill dependency")
(C11) |  breaks a dependency chain for `[memory\_order\_consume](http://en.cppreference.com/w/c/atomic/memory_order)`  (function macro) |
|  [atomic\_thread\_fence](atomic/atomic_thread_fence "c/atomic/atomic thread fence")
(C11) |  generic memory order-dependent fence synchronization primitive  (function) |
|  [atomic\_signal\_fence](atomic/atomic_signal_fence "c/atomic/atomic signal fence")
(C11) |  fence between a thread and a signal handler executed in the same thread  (function) |
|  Convenience type aliases  |
|  Typedef name  |  Full type name  |
| `atomic_bool`(C11) | `_Atomic _Bool` |
| `atomic_char`(C11) | `_Atomic char` |
| `atomic_schar`(C11) | `_Atomic signed char` |
| `atomic_uchar`(C11) | `_Atomic unsigned char` |
| `atomic_short`(C11) | `_Atomic short` |
| `atomic_ushort`(C11) | `_Atomic unsigned short` |
| `atomic_int`(C11) | `_Atomic int` |
| `atomic_uint`(C11) | `_Atomic unsigned int` |
| `atomic_long`(C11) | `_Atomic long` |
| `atomic_ulong`(C11) | `_Atomic unsigned long` |
| `atomic_llong`(C11) | `_Atomic long long` |
| `atomic_ullong`(C11) | `_Atomic unsigned long long` |
| `atomic_char8_t`(C23) | `_Atomic char8_t` |
| `atomic_char16_t`(C11) | `_Atomic char16_t` |
| `atomic_char32_t`(C11) | `_Atomic char32_t` |
| `atomic_wchar_t`(C11) | `_Atomic wchar_t` |
| `atomic_int_least8_t`(C11) | `_Atomic [int\_least8\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_least8_t`(C11) | `_Atomic [uint\_least8\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_least16_t`(C11) | `_Atomic [int\_least16\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_least16_t`(C11) | `_Atomic [uint\_least16\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_least32_t`(C11) | `_Atomic [int\_least32\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_least32_t`(C11) | `_Atomic [uint\_least32\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_least64_t`(C11) | `_Atomic [int\_least64\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_least64_t`(C11) | `_Atomic [uint\_least64\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_fast8_t`(C11) | `_Atomic [int\_fast8\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_fast8_t`(C11) | `_Atomic [uint\_fast8\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_fast16_t`(C11) | `_Atomic [int\_fast16\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_fast16_t`(C11) | `_Atomic [uint\_fast16\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_fast32_t`(C11) | `_Atomic [int\_fast32\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_fast32_t`(C11) | `_Atomic [uint\_fast32\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_fast64_t`(C11) | `_Atomic [int\_fast64\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_fast64_t`(C11) | `_Atomic [uint\_fast64\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_intptr_t`(C11) | `_Atomic [intptr\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uintptr_t`(C11) | `_Atomic [uintptr\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_size_t`(C11) | `_Atomic [size\_t](http://en.cppreference.com/w/c/types/size_t)` |
| `atomic_ptrdiff_t`(C11) | `_Atomic [ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)` |
| `atomic_intmax_t`(C11) | `_Atomic [intmax\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uintmax_t`(C11) | `_Atomic [uintmax\_t](http://en.cppreference.com/w/c/types/integer)` |

 ###  Mutual exclusion

 

|  Defined in header `<threads.h>` |
| --- |
| `mtx_t` |  mutex identifier  |
|  [mtx\_init](thread/mtx_init "c/thread/mtx init")
(C11) |  creates a mutex  (function) |
|  [mtx\_lock](thread/mtx_lock "c/thread/mtx lock")
(C11) |  blocks until locks a mutex  (function) |
|  [mtx\_timedlock](thread/mtx_timedlock "c/thread/mtx timedlock")
(C11) |  blocks until locks a mutex or times out  (function) |
|  [mtx\_trylock](thread/mtx_trylock "c/thread/mtx trylock")
(C11) |  locks a mutex or returns without blocking if already locked  (function) |
|  [mtx\_unlock](thread/mtx_unlock "c/thread/mtx unlock")
(C11) |  unlocks a mutex  (function) |
|  [mtx\_destroy](thread/mtx_destroy "c/thread/mtx destroy")
(C11) |  destroys a mutex  (function) |
|  [mtx\_plainmtx\_recursivemtx\_timed](thread/mtx_types "c/thread/mtx types")
(C11)(C11)(C11) |  defines the type of a mutex  (enum) |
|  Call once  |
|  [call\_once](thread/call_once "c/thread/call once")
(C11) |  calls a function exactly once  (function) |

 ###  Condition variables

 

|  Defined in header `<threads.h>` |
| --- |
| `cnd_t` |  condition variable identifier  |
|  [cnd\_init](thread/cnd_init "c/thread/cnd init")
(C11) |  creates a condition variable  (function) |
|  [cnd\_signal](thread/cnd_signal "c/thread/cnd signal")
(C11) |  unblocks one thread blocked on a condition variable  (function) |
|  [cnd\_broadcast](thread/cnd_broadcast "c/thread/cnd broadcast")
(C11) |  unblocks all threads blocked on a condition variable  (function) |
|  [cnd\_wait](thread/cnd_wait "c/thread/cnd wait")
(C11) |  blocks on a condition variable  (function) |
|  [cnd\_timedwait](thread/cnd_timedwait "c/thread/cnd timedwait")
(C11) |  blocks on a condition variable, with a timeout  (function) |
|  [cnd\_destroy](thread/cnd_destroy "c/thread/cnd destroy")
(C11) |  destroys a condition variable  (function) |

 ###  Thread-local storage

 

|  Defined in header `<threads.h>` |
| --- |
|  [thread\_local](thread/thread_local "c/thread/thread local")
(C11)(removed in C23) |  convenience macro for storage-class specifier `_Thread_local`  (keyword macro) |
| `tss_t` |  thread-specific storage pointer  |
|  [TSS\_DTOR\_ITERATIONS](thread/tss_dtor_iterations "c/thread/TSS DTOR ITERATIONS")
(C11) |  maximum number of times destructors are called  (macro constant) |
| `tss_dtor_t` |  function pointer type `void(*)(void*)`, used for TSS destructor  |
|  [tss\_create](thread/tss_create "c/thread/tss create")
(C11) |  creates thread-specific storage pointer with a given destructor  (function) |
|  [tss\_get](thread/tss_get "c/thread/tss get")
(C11) |  reads from thread-specific storage  (function) |
|  [tss\_set](thread/tss_set "c/thread/tss set")
(C11) |  write to thread-specific storage  (function) |
|  [tss\_delete](thread/tss_delete "c/thread/tss delete")
(C11) |  releases the resources held by a given thread-specific pointer  (function) |

 ###  Reserved identifiers

 In future revisions of the C standard:


* function names, type names, and enumeration constants that begin with either `cnd_`, `mtx_`, `thrd_`, or `tss_`, and a lowercase letter may be added to the declarations in the `<threads.h>` header;
* macros that begin with `ATOMIC_` and an uppercase letter may be added to the macros defined in the `<stdatomic.h>` header;
* typedef names that begin with either `atomic_` or `memory_`, and a lowercase letter may be added to the declarations in the `<stdatomic.h>` header;
* enumeration constants that begin with `memory_order_` and a lowercase letter may be added to the definition of the `[memory\_order](atomic/memory_order "c/atomic/memory order")` type in the `<stdatomic.h>` header;
* function names that begin with `atomic_` and a lowercase letter may be added to the declarations in the `<stdatomic.h>` header.

 Identifiers reserved for functions names are always potentially (since C23) reserved for use as identifiers with external linkage, while other identifiers list here are potentially (since C23) reserved when `<stdatomic.h>` is included.


Declaring, defining, or `#undef`ing such an identifier results in undefined behavior if it is provided by the standard or implementation (since C23). Portable programs should not use those identifiers.


###  References

 * C23 standard (ISO/IEC 9899:2023):
* C17 standard (ISO/IEC 9899:2018):
+ 7.17 Atomics <stdatomic.h> (p: 200-209)
+ 7.26 Threads <threads.h> (p: 274-283)
+ 7.31.8 Atomics <stdatomic.h> (p: 332)
+ 7.31.15 Threads <threads.h> (p: 333)

* C11 standard (ISO/IEC 9899:2011):
+ 7.17 Atomics <stdatomic.h> (p: 273-286)
+ 7.26 Threads <threads.h> (p: 376-387)
+ 7.31.8 Atomics <stdatomic.h> (p: 455-456)
+ 7.31.15 Threads <threads.h> (p: 456)

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/thread "cpp/thread") for Concurrency support library |

 ###  External links

 

|  |
| --- |
| [GNU GCC Libc Manual: ISO C Mutexes](https://www.gnu.org/software/libc/manual/html_node/ISO-C-Mutexes.html) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread>

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

 * C23 standard (ISO/IEC 9899:2023):
+ 5.1.2.2.1 Program startup (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/main_function>

As-if rule
==========

 Allows any and all code transformations that do not change the observable behavior of the program.


###  Explanation

 The C compiler is permitted to perform any changes to the program as long as the following remains true:




|  |  |
| --- | --- |
| 1) At every [sequence point](eval_order "c/language/eval order"), the values of all [volatile](volatile "c/language/volatile") objects are stable (previous evaluations are complete, new evaluations not started).  | (until C11) |
| 1) Accesses (reads and writes) to [volatile](volatile "c/language/volatile") objects occur strictly according to the semantics of the expressions in which they occur. In particular, they are [not reordered](../atomic/memory_order "c/atomic/memory order") with respect to other volatile accesses on the same thread.  | (since C11) |

 
2) At program termination, data written to files is exactly as if the program was executed as written. 
3) Prompting text which is sent to interactive devices will be shown before the program waits for input. 

|  |  |
| --- | --- |
| 4) If the pragma  [`#pragma STDC FENV_ACCESS`](../preprocessor/impl#Standard_pragmas "c/preprocessor/impl") is supported and is set to `ON`, the changes to the [floating-point environment](../numeric/fenv "c/numeric/fenv") (floating-point exceptions and rounding modes) are guaranteed to be observed by the floating-point arithmetic operators and function calls as if executed as written, except that * the result of any floating-point expression other than cast and assignment may have range and precision of a floating-point type different from the type of the expression (see `[FLT\_EVAL\_METHOD](../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")`),
* notwithstanding the above, intermediate results of any floating-point expression may be calculated as if to infinite range and precision (unless  [`#pragma STDC FP_CONTRACT`](../preprocessor/impl#Standard_pragmas "c/preprocessor/impl") is `OFF`).
 | (since C99) |

 ###  Notes

 ###  See also

 * [Order of evaluation](eval_order "c/language/eval order")

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/as_if "cpp/language/as if") for as-if rule |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/as_if>

Arithmetic types
================

 (See also [type](type "c/language/type") for type system overview and [the list of type-related utilities](../types "c/types") that are provided by the C library.).




|  |  |
| --- | --- |
|  Boolean type* `_Bool` (also accessible as the macro [`bool`](../types "c/types")) (until C23)`bool` (since C23) - type, capable of holding one of the two values: `1` and `​0​` (also accessible as the macros [`true`](../types "c/types") and [`false`](../types "c/types")) (until C23)`true` and `false` (since C23).

Note that [conversion](conversion "c/language/conversion") to \_Bool (until C23)bool (since C23) does not work the same as conversion to other integer types: `(bool)0.5` evaluates to `true`, whereas `(int)0.5` evaluates to `​0​`. | (since C99) |

 ###  Character types

 * `signed char` - type for signed character representation.
* `unsigned char` - type for unsigned character representation. Also used to inspect [object representations](object "c/language/object") (raw memory).
* `char` - type for character representation. Equivalent to either `signed char` or `unsigned char` (which one is implementation-defined and may be controlled by a compiler commandline switch), but `char` is a distinct type, different from both `signed char` and `unsigned char`.

 Note that the standard library also defines [typedef](typedef "c/language/typedef") names [`wchar_t`](../string/wide "c/string/wide") , [`char16_t`](../string/multibyte "c/string/multibyte") and [`char32_t`](../string/multibyte "c/string/multibyte") (since C11) to represent wide characters and [`char8_t`](../string/multibyte "c/string/multibyte") for UTF-8 characters (since C23).


###  Integer types

 * `short int` (also accessible as `short`, may use the keyword `signed`)
* `unsigned short int` (also accessible as `unsigned short`)
* `int` (also accessible as `signed int`)
* `unsigned int` (also accessible as `unsigned`), the unsigned counterpart of `int`, implementing modulo arithmetic. Suitable for bit manipulations.
* `long int` (also accessible as `long`)
* `unsigned long int` (also accessible as `unsigned long`)

 This is the most optimal integer type for the platform, and is guaranteed to be at least 16 bits. Most current systems use 32 bits (see Data models below). 

|  |  |
| --- | --- |
| * `long long int` (also accessible as `long long`)
* `unsigned long long int` (also accessible as `unsigned long long`)
 | (since C99) |

 

|  |  |
| --- | --- |
| * `_Bitint(n)` (where `n` is replaced by precise width, that cannot be larger than `BITINT_MAXWIDTH` from [`<limits.h>`](../types/limits "c/types/limits"))
* `unsigned _Bitint(n)` (where `n` is replaced by precise width, that cannot be larger than `BITINT_MAXWIDTH` from [`<limits.h>`](../types/limits "c/types/limits"))
 | (since C23) |

 Note: as with all type specifiers, any order is permitted: `unsigned long long int` and `long int unsigned long` name the same type.


The following table summarizes all available integer types and their properties:




|  Type specifier  |  Equivalent type  |  Width in bits by data model  |
| --- | --- | --- |
|  C standard  |  LP32  |  ILP32  |  LLP64  |  LP64  |
| 
```
char
```
 | char |  at least **8** | **8** | **8** | **8** | **8** |
| 
```
signed char
```
 | signed char |
| 
```
unsigned char
```
 | unsigned char |
| 
```
short
```
 | short int |  at least **16** | **16** | **16** | **16** | **16** |
| 
```
short int
```
 |
| 
```
signed short
```
 |
| 
```
signed short int
```
 |
| 
```
unsigned short
```
 | unsigned short int |
| 
```
unsigned short int
```
 |
| 
```
int
```
 | int |  at least **16** | **16** | **32** | **32** | **32** |
| 
```
signed
```
 |
| 
```
signed int
```
 |
| 
```
unsigned
```
 | unsigned int |
| 
```
unsigned int
```
 |
| 
```
long
```
 | long int |  at least **32** | **32** | **32** | **32** | **64** |
| 
```
long int
```
 |
| 
```
signed long
```
 |
| 
```
signed long int
```
 |
| 
```
unsigned long
```
 | unsigned long int |
| 
```
unsigned long int
```
 |
| 
```
long long
```
 | long long int (C99) |  at least **64** | **64** | **64** | **64** | **64** |
| 
```
long long int
```
 |
| 
```
signed long long
```
 |
| 
```
signed long long int
```
 |
| 
```
unsigned long long
```
 | unsigned long long int (C99) |
| 
```
unsigned long long int
```
 |

 Besides the minimal bit counts, the C Standard guarantees that `1` == `sizeof(char)` ≤ `sizeof(short)` ≤ `sizeof(int)` ≤ `sizeof(long)` ≤ `sizeof(long long)`.


Note: this allows the extreme case in which [byte](https://en.wikipedia.org/wiki/byte "enwiki:byte") are sized 64 bits, all types (including `char`) are 64 bits wide, and `sizeof` returns 1 for every type.


Note: integer arithmetic is defined differently for the signed and unsigned integer types. See [arithmetic operators](operator_arithmetic "c/language/operator arithmetic"), in particular [integer overflows](operator_arithmetic#Overflows "c/language/operator arithmetic").


####  Data models

 The choices made by each implementation about the sizes of the fundamental types are collectively known as *data model*. Four data models found wide acceptance:


32 bit systems:


* **LP32** or **2/4/4** (int is 16-bit, long and pointer are 32-bit)
+ Win16 API

* **ILP32** or **4/4/4** (int, long, and pointer are 32-bit);
+ Win32 API
+ Unix and Unix-like systems (Linux, Mac OS X)

 64 bit systems:


* **LLP64** or **4/4/8** (int and long are 32-bit, pointer is 64-bit)
+ Win64 API

* **LP64** or **4/8/8** (int is 32-bit, long and pointer are 64-bit)
+ Unix and Unix-like systems (Linux, Mac OS X)

 Other models are very rare. For example, **ILP64** (**8/8/8**: int, long, and pointer are 64-bit) only appeared in some early 64-bit Unix systems (e.g. Unicos on Cray).


Note that exact-width integer types are available in [`<stdint.h>`](../types/integer "c/types/integer") since C99.


###  Real floating types

 C has three or six (since C23) types for representing real floating-point values:


* `float` - single precision floating-point type. Matches [IEEE-754 binary32 format](https://en.wikipedia.org/wiki/Single-precision_floating-point_format "enwiki:Single-precision floating-point format") if supported.
* `double` - double precision floating-point type. Matches [IEEE-754 binary64 format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format "enwiki:Double-precision floating-point format") if supported.
* `long double` - extended precision floating-point type. Matches [IEEE-754 binary128 format](https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format "enwiki:Quadruple-precision floating-point format") if supported, otherwise matches [IEEE-754 binary64-extended format](https://en.wikipedia.org/wiki/Extended_precision "enwiki:Extended precision") if supported, otherwise matches some non-IEEE-754 extended floating-point format as long as its precision is better than binary64 and range is at least as good as binary64, otherwise matches IEEE-754 binary64 format.
	+ binary128 format is used by some HP-UX, SPARC, MIPS, ARM64, and z/OS implementations.
	+ The most well known IEEE-754 binary64-extended format is 80-bit x87 extended precision format. It is used by many x86 and x86-64 implementations (a notable exception is MSVC, which implements `long double` in the same format as `double`, i.e. binary64).

 

|  |  |
| --- | --- |
| 
 If the implementation predefines the macro constant `__STDC_IEC_60559_DFP__`, the following decimal floating-point types are also supported. * `_Decimal32` - Represents [IEEE-754 decimal32 format](https://en.wikipedia.org/wiki/decimal32_floating-point_format "enwiki:decimal32 floating-point format").
* `_Decimal64` - Represents [IEEE-754 decimal64 format](https://en.wikipedia.org/wiki/decimal64_floating-point_format "enwiki:decimal64 floating-point format").
* `_Decimal128` - Represents [IEEE-754 decimal128 format](https://en.wikipedia.org/wiki/decimal128_floating-point_format "enwiki:decimal128 floating-point format").

 
 Otherwise, these decimal floating-point types are not supported. 
 | (since C23) |

 Floating-point types may support special values:


* *infinity* (positive and negative), see [`INFINITY`](../numeric/math/infinity "c/numeric/math/INFINITY")
* the *negative zero*, `-0.0`. It compares equal to the positive zero, but is meaningful in some arithmetic operations, e.g. `1.0/0.0 == INFINITY`, but `1.0/-0.0 == -INFINITY`)
* *not-a-number* (NaN), which does not compare equal with anything (including itself). Multiple bit patterns represent NaNs, see `[nan](../numeric/math/nan "c/numeric/math/nan")`, [`NAN`](../numeric/math/nan "c/numeric/math/NAN"). Note that C takes no special notice of signaling NaNs (specified by IEEE-754), and treats all NaNs as quiet.

 Real floating-point numbers may be used with [arithmetic operators](operator_arithmetic "c/language/operator arithmetic") + - / \* and various mathematical functions from [`<math.h>`](../numeric/math "c/numeric/math"). Both built-in operators and library functions may raise floating-point exceptions and set `[errno](../error/errno "c/error/errno")` as described in [`math_errhandling`](../numeric/math/math_errhandling "c/numeric/math/math errhandling").


Floating-point expressions may have greater range and precision than indicated by their types, see `[FLT\_EVAL\_METHOD](../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")`. [Assignment](operator_assignment "c/language/operator assignment"), [return](return "c/language/return"), and [cast](cast "c/language/cast") force the range and precision to the one associated with the declared type.


Floating-point expressions may also be *contracted*, that is, calculated as if all intermediate values have infinite range and precision, see  [`#pragma STDC FP_CONTRACT`](../preprocessor/impl#Standard_pragmas "c/preprocessor/impl").


Some operations on floating-point numbers are affected by and modify the state of [the floating-point environment](../numeric/fenv "c/numeric/fenv") (most notably, the rounding direction).


[Implicit conversions](conversion "c/language/conversion") are defined between real floating types and integer, complex, and imaginary types.


See [Limits of floating-point types](../types/limits#Limits_of_floating-point_types "c/types/limits") and the [`<math.h>`](../numeric/math "c/numeric/math") library for additional details, limits, and properties of the floating-point types.




|  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- |
|  Complex floating types Complex floating types model the mathematical [complex number](https://en.wikipedia.org/wiki/complex_number "enwiki:complex number"), that is the numbers that can be written as a sum of a real number and a real number multiplied by the imaginary unit: a + bi.
The three complex types are.* `float _Complex` (also available as `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)` if [`<complex.h>`](../numeric/complex "c/numeric/complex") is included)
* `double _Complex` (also available as `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)` if [`<complex.h>`](../numeric/complex "c/numeric/complex") is included)
* `long double _Complex` (also available as `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)` if [`<complex.h>`](../numeric/complex "c/numeric/complex") is included)

Note: as with all type specifiers, any order is permitted: `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `[complex](http://en.cppreference.com/w/c/numeric/complex/complex) long double`, and even `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex) long` name the same type.

```
#include <complex.h>
#include <stdio.h>
 
int main(void)
{
    double complex z = 1 + 2*I;
    z = 1 / z;
    printf("1/(1.0+2.0i) = %.1f%+.1fi\n", creal(z), cimag(z));
}
```
 Output:

```
1/(1.0+2.0i) = 0.2-0.4i
```


|  |  |
| --- | --- |
| If the macro constant `__STDC_NO_COMPLEX__` is defined by the implementation, the complex types (as well as the library header [`<complex.h>`](../numeric/complex "c/numeric/complex")) are not provided. | (since C11) |

Each complex type has the same [object representation](object "c/language/object") and [alignment requirements](object "c/language/object") as an [array](array "c/language/array") of two elements of the corresponding real type (`float` for `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `double` for `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, `long double` for `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`). The first element of the array holds the real part, and the second element of the array holds the imaginary component.

```
float a[4] = {1, 2, 3, 4};
float complex z1, z2;
memcpy(&z1, a, sizeof z1); // z1 becomes 1.0 + 2.0i
memcpy(&z2, a+2, sizeof z2); // z2 becomes 3.0 + 4.0i
```
 Complex numbers may be used with [arithmetic operators](operator_arithmetic "c/language/operator arithmetic") + - \* and /, possibly mixed with imaginary and real numbers. There are many mathematical functions defined for complex numbers in [`<complex.h>`](../numeric/complex "c/numeric/complex"). Both built-in operators and library functions may raise floating-point exceptions and set `[errno](../error/errno "c/error/errno")` as described in [`math_errhandling`](../numeric/math/math_errhandling "c/numeric/math/math errhandling").
Increment and decrement are not defined for complex types.
Relational operators are not defined for complex types (there is no notion of "less than"). [Implicit conversions](conversion "c/language/conversion") are defined between complex types and other arithmetic types.
In order to support the one-infinity model of complex number arithmetic, C regards any complex value with at least one infinite part as an infinity even if its other part is a NaN, guarantees that all operators and functions honor basic properties of infinities and provides `[cproj](../numeric/complex/cproj "c/numeric/complex/cproj")` to map all infinities to the canonical one (see [arithmetic operators](operator_arithmetic "c/language/operator arithmetic") for the exact rules).

```
#include <complex.h>
#include <math.h>
#include <stdio.h>
 
int main(void)
{
    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%+f*i\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%+f*i\n", creal(y), cimag(y));
}
```
 Possible output:

```
inf+inf*i 
inf+nan*i
```
 C also treats multiple infinities so as to preserve directional information where possible, despite the inherent limitations of the Cartesian representation:
multiplying the imaginary unit by real infinity gives the correctly-signed imaginary infinity: i × ∞ = i∞. Also, i × (∞ – i∞) = ∞ + i∞ indicates the reasonable quadrant.
 Imaginary floating types Imaginary floating types model the mathematical [imaginary numbers](https://en.wikipedia.org/wiki/imaginary_numbers "enwiki:imaginary numbers"), that is numbers that can be written as a real number multiplied by the imaginary unit: bi The three imaginary types are.* `float _Imaginary` (also available as `float [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)` if [`<complex.h>`](../numeric/complex "c/numeric/complex") is included)
* `double _Imaginary` (also available as `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)` if [`<complex.h>`](../numeric/complex "c/numeric/complex") is included)
* `long double _Imaginary` (also available as `long double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)` if [`<complex.h>`](../numeric/complex "c/numeric/complex") is included)

Note: as with all type specifiers, any order is permitted: `long double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, `[imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary) long double`, and even `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary) long` name the same type.

```
#include <complex.h>
#include <stdio.h>
 
int main(void)
{
    double imaginary z = 3*I;
    z = 1 / z;
    printf("1/(3.0i) = %+.1fi\n", cimag(z));
}
```
 Output:

```
1/(3.0i) = -0.3i
```


|  |  |
| --- | --- |
| An implementation that defines `__STDC_IEC_559_COMPLEX__` is recommended, but not required to support imaginary numbers. POSIX recommends checking if the macro `[\_Imaginary\_I](../numeric/complex/imaginary_i "c/numeric/complex/Imaginary I")` is defined to identify imaginary number support. | (until C11) |
| Imaginary numbers are supported if `__STDC_IEC_559_COMPLEX__` (until C23)`__STDC_IEC_60559_COMPLEX__` (since C23) is defined. | (since C11) |

Each of the three imaginary types has the same [object representation](object "c/language/object") and [alignment requirement](object "c/language/object") as its *corresponding real type* (`float` for `float [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, `double` for `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`, `long double` for `long double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`).
Note: despite that, imaginary types are distinct and [not compatible](type#Compatible_types "c/language/type") with their corresponding real types, which prohibits aliasing.
Imaginary numbers may be used with [arithmetic operators](operator_arithmetic "c/language/operator arithmetic") + - \* and /, possibly mixed with complex and real numbers. There are many mathematical functions defined for imaginary numbers in [`<complex.h>`](../numeric/complex "c/numeric/complex"). Both built-in operators and library functions may raise floating-point exceptions and set `[errno](../error/errno "c/error/errno")` as described in [`math_errhandling`](../numeric/math/math_errhandling "c/numeric/math/math errhandling").
Increment and decrement are not defined for imaginary types. [Implicit conversions](conversion "c/language/conversion") are defined between imaginary types and other arithmetic types.
The imaginary numbers make it possible to express all complex numbers using the natural notation `x + I*y` (where `I` is defined as `[\_Imaginary\_I](../numeric/complex/imaginary_i "c/numeric/complex/Imaginary I")`). Without imaginary types, certain special complex values cannot be created naturally. For example, if `I` is defined as `[\_Complex\_I](../numeric/complex/complex_i "c/numeric/complex/Complex I")`, then writing `0.0 + I*INFINITY` gives NaN as the real part, and `[CMPLX](http://en.cppreference.com/w/c/numeric/complex/CMPLX)(0.0, INFINITY)` must be used instead. Same goes for the numbers with the negative zero imaginary component, which are meaningful when working with the library functions with branch cuts, such as `[csqrt](../numeric/complex/csqrt "c/numeric/complex/csqrt")`: `1.0 - 0.0*I` results in the positive zero imaginary component if `I` is defined as `[\_Complex\_I](../numeric/complex/complex_i "c/numeric/complex/Complex I")` and the negative zero imaginary part requires the use of `[CMPLX](../numeric/complex/cmplx "c/numeric/complex/CMPLX")` or `[conj](../numeric/complex/conj "c/numeric/complex/conj")`.
Imaginary types also simplify implementations; multiplication of an imaginary by a complex can be implemented straightforwardly with two multiplications if the imaginary types are supported, instead of four multiplications and two additions. | (since C99) |

 ###  Keywords

 * [`bool`](../keyword/bool "c/keyword/bool"), [`true`](../keyword/true "c/keyword/true"), [`false`](../keyword/false "c/keyword/false"), [`char`](../keyword/char "c/keyword/char"), [`int`](../keyword/int "c/keyword/int"), [`short`](../keyword/short "c/keyword/short"), [`long`](../keyword/long "c/keyword/long"), [`signed`](../keyword/signed "c/keyword/signed"), [`unsigned`](../keyword/unsigned "c/keyword/unsigned"), [`float`](../keyword/float "c/keyword/float"), [`double`](../keyword/double "c/keyword/double").
* [`_Bool`](../keyword/_bool "c/keyword/ Bool"), [`_Complex`](../keyword/_complex "c/keyword/ Complex"), [`_Imaginary`](../keyword/_imaginary "c/keyword/ Imaginary"), [`_Decimal32`](../keyword/_decimal32 "c/keyword/ Decimal32"), [`_Decimal64`](../keyword/_decimal64 "c/keyword/ Decimal64"), [`_Decimal128`](../keyword/_decimal128 "c/keyword/ Decimal128").

 ###  Range of values

 The following table provides a reference for the limits of common numeric representations.


Prior to C23, the C Standard allowed any signed integer representation, and the minimum guaranteed range of N-bit signed integers was from \(\scriptsize -(2^{N-1}-1)\)-(2N-1  
-1) to \(\scriptsize +2^{N-1}-1\)+2N-1  
-1 (e.g. **-127** to **127** for a signed 8-bit type), which corresponds to the limits of [one's complement](https://en.wikipedia.org/wiki/one%27s_complement "enwiki:one's complement") or [sign-and-magnitude](https://en.wikipedia.org/wiki/Signed_number_representations#Sign-and-magnitude_method "enwiki:Signed number representations").


However, all popular data models (including all of ILP32, LP32, LP64, LLP64) and almost all C compilers use [two's complement](https://en.wikipedia.org/wiki/two%27s_complement "enwiki:two's complement") representation (the only known exceptions are some compliers for UNISYS), and as of C23, it is the only representation allowed by the standard, with the guaranteed range from \(\scriptsize -2^{N-1}\)-2N-1  
 to \(\scriptsize +2^{N-1}-1\)+2N-1  
-1 (e.g. **-128** to **127** for a signed 8-bit type).




| Type  | Size in bits  | Format  | Value range  |
| --- | --- | --- | --- |
|  Approximate  |  Exact  |
| character  | 8  | signed  |  | **−128** to **127** |
| unsigned  |  | **0** to **255** |
| 16  | UTF-16  |  | **0** to **65535** |
| 32  | UTF-32  |  | **0** to **1114111** (**0x10ffff**)  |
| integer  | 16  | signed  | **± 3.27 · 104** | **−32768** to **32767** |
| unsigned  | **0** to **6.55 · 104** | **0** to **65535** |
| 32  | signed  | **± 2.14 · 109** | **−2,147,483,648** to **2,147,483,647** |
| unsigned  | **0** to **4.29 · 109** | **0** to **4,294,967,295** |
| 64  | signed  | **± 9.22 · 1018** | **−9,223,372,036,854,775,808** to **9,223,372,036,854,775,807** |
| unsigned  | **0** to **1.84 · 1019** | **0** to **18,446,744,073,709,551,615** |
| binary floating point  | 32  | [IEEE-754](https://en.wikipedia.org/wiki/Single-precision_floating-point_format "enwiki:Single-precision floating-point format") | * min subnormal:**± 1.401,298,4 · 10−45**
* min normal:**± 1.175,494,3 · 10−38**
* max:**± 3.402,823,4 · 1038**
 | * min subnormal:**±0x1p−149**
* min normal:**±0x1p−126**
* max:**±0x1.fffffep+127**
 |
| 64  | [IEEE-754](https://en.wikipedia.org/wiki/Double-precision_floating-point_format "enwiki:Double-precision floating-point format") | * min subnormal:**± 4.940,656,458,412 · 10−324**
* min normal:**± 2.225,073,858,507,201,4 · 10−﻿308**
* max:**± 1.797,693,134,862,315,7 · 10308**
 | * min subnormal:**±0x1p−1074**
* min normal:**±0x1p−1022**
* max:**±0x1.fffffffffffffp+1023**
 |
| 80[[note 1]](#cite_note-1) | [x86](https://en.wikipedia.org/wiki/Extended_precision "enwiki:Extended precision") | * min subnormal:**± 3.645,199,531,882,474,602,528 · 10−4951**
* min normal:**± 3.362,103,143,112,093,506,263 · 10−4932**
* max:**± 1.189,731,495,357,231,765,021 · 104932**
 | * min subnormal:**±0x1p−16445**
* min normal:**±0x1p−16382**
* max:**±0x1.fffffffffffffffep+16383**
 |
| 128  | [IEEE-754](https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format "enwiki:Quadruple-precision floating-point format") | * min subnormal:**± 6.475,175,119,438,025,110,924,438,958,227,646,552,5 · 10−4966**
* min normal:**± 3.362,103,143,112,093,506,262,677,817,321,752,602,6 · 10−4932**
* max:**± 1.189,731,495,357,231,765,085,759,326,628,007,016,2 · 104932**
 | * min subnormal:**±0x1p−16494**
* min normal:**±0x1p−16382**
* max:**±0x1.ffffffffffffffffffffffffffffp+16383**
 |
|  decimal floating point  |  32  | [IEEE-754](https://en.wikipedia.org/wiki/decimal32_floating-point_format "enwiki:decimal32 floating-point format") |  | * min subnormal:**± 1 · 10-101**
* min normal:**± 1 · 10-95**
* max:**± 9.999'999 · 1096**
 |
|  64  | [IEEE-754](https://en.wikipedia.org/wiki/decimal64_floating-point_format "enwiki:decimal64 floating-point format") |  | * min subnormal:**± 1 · 10-398**
* min normal:**± 1 · 10-383**
* max:**± 9.999'999'999'999'999 · 10384**
 |
|  128  | [IEEE-754](https://en.wikipedia.org/wiki/decimal128_floating-point_format "enwiki:decimal128 floating-point format") |  | * min subnormal:**± 1 · 10-6176**
* min normal:**± 1 · 10-6143**
* max:**± 9.999'999'999'999'999'999'999'999'999'999'999 · 106144**
 |

 1. The object representation usually occupies 96/128 bits on 32/64-bit platforms respectively.

 Note: actual (as opposed to guaranteed minimal) ranges are available in the library headers [`<limits.h>`](../types/limits "c/types/limits") and [`<float.h>`](../types/limits#Limits_of_floating_point_types "c/types/limits").


###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/types "cpp/language/types") for Fundamental types |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/arithmetic_types>

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.




|  |  |
| --- | --- |
| For versions (3,4), replacement-list may contain the token sequence `__VA_OPT__ (` content `)`, which is replaced by content if `__VA_ARGS__` is non-empty, and expands to nothing otherwise.

```
#define F(...) f(0 __VA_OPT__(,) __VA_ARGS__)
F(a, b, c) // replaced by f(0, a, b, c)
F()        // replaced by f(0)
 
#define G(X, ...) f(0, X __VA_OPT__(,) __VA_ARGS__)
G(a, b, c) // replaced by f(0, a, b, c)
G(a, )     // replaced by f(0, a)
G(a)       // replaced by f(0, a)
 
#define SDEF(sname, ...) S sname __VA_OPT__(= { __VA_ARGS__ })
SDEF(foo);       // replaced by S foo;
SDEF(bar, 1, 2); // replaced by S bar = { 1, 2 };
```
 | (since C23) |

   
 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](http://en.cppreference.com/w/c/io/fprintf) ([stderr](http://en.cppreference.com/w/c/io/std_streams), 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)
* `202311L` (C23)  (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) |
| \_\_STDC\_UTF\_16\_\_
(C23) |  expands to `1` to indicate that `char16_t` use UTF-16 encoding  (macro constant) |
| \_\_STDC\_UTF\_32\_\_
(C23) |  expands to `1` to indicate that `char32_t` use UTF-32 encoding  (macro constant) |
| \_\_STDC\_EMBED\_NOT\_FOUND\_\_\_\_STDC\_EMBED\_FOUND\_\_\_\_STDC\_EMBED\_EMPTY\_\_
(C23) |  expand to `​0​`, `1`, and `2`, respectively  (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 `202311L` if IEC 60559 binary floating-point arithmetic is supported  (macro constant) |
| \_\_STDC\_IEC\_60559\_DFP\_\_
(C23) |  expands to `202311L` if IEC 60559 decimal floating-point arithmetic is supported  (macro constant) |
| \_\_STDC\_IEC\_60559\_COMPLEX\_\_
(C23) |  expands to `202311L` if IEC 60559 complex arithmetic is supported  (macro constant) |
| \_\_STDC\_IEC\_60559\_TYPES\_\_
(C23) |  expands to `202311L` if IEC 60559 interchange and extended types are 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(billion);               // note the lack of quotes
}
```
 Output:



```
quadruple(13): 52
double(21): 42
34
billion
```
  ###  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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.10.4 Macro replacement (p: 187-184)
+ 6.10.9 Predefined macro names (p: 186-188)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/preprocessor/replace>

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.6 Pragma directive (p: 127)
+ 6.10.9 Pragma operator (p: 129)

* C11 standard (ISO/IEC 9899:2011):
+ 6.10.6 Pragma directive (p: 174)
+ 6.10.9 Pragma operator (p: 178)

* C99 standard (ISO/IEC 9899:1999):
+ 6.10.6 Pragma directive (p: 159)
+ 6.10.9 Pragma operator (p: 161-162)

* 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

 

|  |  |
| --- | --- |
| 1.  | [C++ pragmas in Visual Studio 2019](https://docs.microsoft.com/en-us/cpp/preprocessor/pragma-directives-and-the-pragma-keyword?view=vs-2019) |
| 2.  | [Pragmas](https://gcc.gnu.org/onlinedocs/gcc/Pragmas.html) accepted by GCC  |
| 3.  | [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  |
| 4.  | [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  |
| 5.  | [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) |
| 6.  | [HP aCC compiler pragmas](http://h21007.www2.hp.com/portal/download/files/unprot/aCxx/Online_Help/pragmas.htm) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/preprocessor/impl>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/preprocessor/line>

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__ >= 202311L
#  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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/preprocessor/error>

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 1 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;
    // Endless loop with no side effects is UB
    for (int a = 1, b = 1, c = 1; 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

 

|  |  |
| --- | --- |
| 1.  | [What Every C Programmer Should Know About Undefined Behavior #1/3](https://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html) |
| 2.  | [What Every C Programmer Should Know About Undefined Behavior #2/3](https://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html) |
| 3.  | [What Every C Programmer Should Know About Undefined Behavior #3/3](https://blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html) |
| 4.  | [Undefined behavior can result in time travel (among other things, but time travel is the funkiest)](https://blogs.msdn.com/b/oldnewthing/archive/2014/06/27/10537746.aspx) |
| 5.  | [Understanding Integer Overflow in C/C++](https://www.cs.utah.edu/~regehr/papers/overflow12.pdf) |
| 6.  | [Undefined Behavior and Fermat’s Last Theorem](https://web.archive.org/web/20201108094235/https://kukuruku.co/post/undefined-behavior-and-fermats-last-theorem/) |
| 7.  | [Fun with NULL pointers, part 1](https://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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/behavior>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/memory_model>

Source file inclusion
=====================

 Includes another source file into the current source file at the line immediately after the directive.


###  Syntax

 

|  |  |  |
| --- | --- | --- |
| `#include <` h-char-sequence `>` new-line |  (1)  |  |
| `#include "` q-char-sequence `"` new-line |  (2)  |  |
| `#include` pp-tokens new-line |  (3)  |  |
| `__has_include` `(` `"` q-char-sequence `"` `)``__has_include` `(` `<` h-char-sequence `>` `)` |  (4)  | (since C23) |
| `__has_include` `(` string-literal `)``__has_include` `(` `<` h-pp-tokens `>` `)` |  (5)  | (since C23) |

 
1) Searches for a header identified uniquely by h-char-sequence and replaces the directive by the entire contents of the header. 
2) Searches for a source file identified by q-char-sequence and replaces the directive by the entire contents of the source file. It may fallback to (1) and treat q-char-sequence as a header identifier. 
3) If neither (1) nor (2) is matched, pp-tokens will undergo macro replacement. The directive after replacement will be tried to match with (1) or (2) again. 
4) Checks whether a header or source file is available for inclusion. 
5) If (4) is not matched, h-pp-tokens will undergo macro replacement. The directive after replacement will be tried to match with (4) again. 

|  |  |  |
| --- | --- | --- |
| new-line |  -  |  The new-line character  |
| h-char-sequence |  -  |  A sequence of one or more h-chars, where the appearance of any of the following causes undefined behavior: * the character `'`
* the character `"`
* the character `\`
* the character sequence `//`
* the character sequence `/*`
 |
| h-char |  -  |  Any member of the [source character set](../language/translation_phases#Phase_5 "c/language/translation phases") except new-line and `>` |
| q-char-sequence |  -  |  A sequence of one or more q-chars, where the appearance of any of the following causes undefined behavior: * the character `'`
* the character `\`
* the character sequence `//`
* the character sequence `/*`
 |
| q-char |  -  |  Any member of the [source character set](../language/translation_phases#Phase_5 "c/language/translation phases") except new-line and `"` |
| pp-tokens |  -  |  A sequence of one or more [preprocessing tokens](../language/translation_phases#Phase_3 "c/language/translation phases") |
| string-literal |  -  |  A [string literal](../language/string_literal "c/language/string literal") |
| h-pp-tokens |  -  |  A sequence of one or more [preprocessing tokens](../language/translation_phases#Phase_3 "c/language/translation phases") except `>` |

 ###  Explanation

 
1) Searches for the file identified by h-char-sequence 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 is 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 identified by q-char-sequence 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). 
3) The preprocessing tokens after `include` in the directive are processed just as in normal text (i.e., each identifier currently defined as a macro name is replaced by its replacement list of preprocessing tokens). The directive resulting after all replacements shall match one of the two previous forms. The method by which a sequence of preprocessing tokens between `<` and `>` preprocessing token pair or a pair of `"` characters is combined into a single header name preprocessing token is implementation-defined. 
```
#include
```
 
5) This form is considered only if syntax (4) does not match, in which case the preprocessing tokens are processed just as in normal text. In the case the file is not found, the program is ill-formed.




|  |  |
| --- | --- |
| `__has_include` can be expanded in the expression of  [`#if`](conditional "c/preprocessor/conditional") and  [`#elif`](conditional "c/preprocessor/conditional"). It is treated as a defined macro by  [`#ifdef`](conditional "c/preprocessor/conditional"),  [`#ifndef`](conditional "c/preprocessor/conditional"),  [`#elifdef`](conditional "c/preprocessor/conditional"),  [`#elifndef`](conditional "c/preprocessor/conditional") and [`defined`](conditional "c/preprocessor/conditional") but cannot be used anywhere else. | (since C23) |

 ###  Notes

 Typical implementations search only standard include directories for syntax (1). The standard C library is implicitly included in these standard include directories. The standard include directories usually can be controlled by the user through compiler options.


The intent of syntax (2) is to search for the files that are not controlled by the implementation. Typical implementations first search the directory where the current file resides then falls back to (1).


When a file is included, it is processed by [translation phases](../language/translation_phases "c/language/translation phases") 1-4, which may include, recursively, expansion of the nested `#include` directives, up to an implementation-defined nesting limit. To avoid repeated inclusion of the same file and endless recursion when a file includes itself, perhaps transitively, *header guards* are commonly used: the entire header is wrapped in.



```
#ifndef FOO_H_INCLUDED /* any name uniquely mapped to file name */
#define FOO_H_INCLUDED
// contents of the file are here
#endif
```
 Many compilers also implement the non-standard [`pragma`](impl "c/preprocessor/impl") `#pragma once` with similar effects: it disables processing of a file if the same file (where file identity is determined in OS-specific way) has already been included.


A `__has_include` result of `1` only means that a header or source file with the specified name exists. It does not mean that the header or source file, when included, would not cause an error or would contain anything useful.


###  Example

 ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 6.4.7 Header names (p: 69)
+ 6.10.1 Conditional inclusion (p: 165-169)
+ 6.10.2 Source file inclusion (p: 169-170)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/preprocessor/include>

Binary resource inclusion (since C23)
=====================================

 #embed is a preprocessor directive to include (binary) resources in the build, where a resource is defined as a source of data accessible from the translation environment.


###  Syntax

 

|  |  |  |
| --- | --- | --- |
| `#embed <` h-char-sequence `>` embed-parameter-sequence ﻿(optional) new-line |  (1)  |  |
| `#embed "` q-char-sequence `"` embed-parameter-sequence ﻿(optional) new-line |  (2)  |  |
| `#embed` pp-tokens new-line |  (3)  |  |
| `__has_embed` `(` `"` q-char-sequence `"` embed-parameter-sequence ﻿(optional) `)``__has_embed` `(` `<` h-char-sequence `>` embed-parameter-sequence ﻿(optional) `)` |  (4)  |  |
| `__has_embed` `(` string-literal pp-balanced-token-sequence ﻿(optional) `)``__has_embed` `(` `<` h-pp-tokens `>` pp-balanced-token-sequence ﻿(optional) `)` |  (5)  |  |

 
1) Searches for a resource identified uniquely by h-char-sequence and replaces the directive by a comma separated list of integers corresponding to the data of the resource. 
2) Searches for a resource identified by q-char-sequence and replaces the directive by a list of integers corresponding to the data of the resource. It may fallback to (1). 
3) If neither (1) nor (2) is matched, pp-tokens will undergo macro replacement. The directive after replacement will be tried to match with (1) or (2) again. 
4) Checks whether a resource is available for embedding, whether it is empty or not and whether the parameters passed are supported by the implementation. 
5) If (4) is not matched, h-pp-tokens and pp-balanced-token-sequence will undergo macro replacement. The directive after replacement will be tried to match with (4) again. 

|  |  |  |
| --- | --- | --- |
| new-line |  -  |  The new-line character  |
| h-char-sequence |  -  |  A sequence of one or more h-chars, where the appearance of any of the following causes undefined behavior: * the character `'`
* the character `"`
* the character `\`
* the character sequence `//`
* the character sequence `/*`
 |
| h-char |  -  |  Any member of the [source character set](../language/translation_phases#Phase_5 "c/language/translation phases") except new-line and `>` |
| q-char-sequence |  -  |  A sequence of one or more q-chars, where the appearance of any of the following causes undefined behavior: * the character `'`
* the character `\`
* the character sequence `//`
* the character sequence `/*`
 |
| q-char |  -  |  Any member of the [source character set](../language/translation_phases#Phase_5 "c/language/translation phases") except new-line and `"` |
| pp-tokens |  -  |  A sequence of one or more [preprocessing tokens](../language/translation_phases#Phase_3 "c/language/translation phases") |
| string-literal |  -  |  A [string literal](../language/string_literal "c/language/string literal") |
| h-pp-tokens |  -  |  A sequence of one or more [preprocessing tokens](../language/translation_phases#Phase_3 "c/language/translation phases") except `>` |
| embed-parameter-sequence |  -  |  A sequence of one or more pp-parameter ﻿s. Note that unlike an attribute-list, this sequence is not comma separated.  |
| pp-parameter |  -  |  An attribute-token (see: [attributes](../language/attributes "c/language/attributes")) but comprised of preprocessing tokens instead of tokens.  |
| pp-balanced-token-sequence |  -  |  A balanced-token-sequence (see: [attributes](../language/attributes "c/language/attributes")) but comprised of preprocessing tokens instead of tokens  |


 ###  Explanation

 
1) Searches for the resource identified by h-char-sequence in implementation-defined manner. 
2) Searches for the resource identified by q-char-sequence in implementation-defined manner. For (1,2), the implementations typically use a mechanism similar to, but distinct from, the implementation-defined search paths used for source file inclusion. The construct `__has_embed(__FILE__ ...` appears in one of the examples in the standard, suggesting, in case (2) at least, that the directory where the current file resides is expected to be searched. 
3) The preprocessing tokens after `embed` in the directive are processed just as in normal text (i.e., each identifier currently defined as a macro name is replaced by its replacement list of preprocessing tokens). The directive resulting after all replacements shall match one of the two previous forms. The method by which a sequence of preprocessing tokens between `<` and `>` preprocessing token pair or a pair of `"` characters is combined into a single header name preprocessing token is implementation-defined. 
```
#embed
```
 
5) This form is considered only if syntax (4) does not match, in which case the preprocessing tokens are processed just as in normal text. In the case the resource is not found or one of the parameters is not supported by the implementation, the program is ill-formed.


`__has_embed` can be expanded in the expression of  [`#if`](conditional "c/preprocessor/conditional") and  [`#elif`](conditional "c/preprocessor/conditional"). It is treated as a defined macro by  [`#ifdef`](conditional "c/preprocessor/conditional"),  [`#ifndef`](conditional "c/preprocessor/conditional"),  [`#elifdef`](conditional "c/preprocessor/conditional"),  [`#elifndef`](conditional "c/preprocessor/conditional") and [`defined`](conditional "c/preprocessor/conditional") but cannot be used anywhere else.


A resource has an *implementation resource width* which is the implementation-defined size in bits of the located resource. Its *resource width* is the implementation resource width unless modified by a `limit` parameter. If the resource width is 0, the resource is considered empty. The *embed element width* is equal to `[CHAR\_BIT](../types/limits "c/types/limits")` unless modified by an implementation defined parameter. The resource width must be divisible by the embed element width.


The expansion of a #embed directive is a token sequence formed from the list of integer [constant expressions](../language/constant_expression "c/language/constant expression") described below. The group of tokens for each integer constant expression in the list is separated in the token sequence from the group of tokens for the previous integer constant expression in the list by a comma. The sequence neither begins nor ends in a comma. If the list of integer constant expressions is empty, the token sequence is empty. The directive is replaced by its expansion and, with the presence of certain embed parameters, additional or replacement token sequences.


The values of the integer constant expressions in the expanded sequence are determined by an implementation-defined mapping of the resource’s data. Each integer constant expression’s value is in the range `[`0`,`2embed element width`)`. If:


1. The list of integer constant expressions is used to initialize an array of a type compatible with `unsigned char`, or compatible with `char` if `char` cannot hold negative values, and
2. The embed element width is equal to `[CHAR\_BIT](../types/limits "c/types/limits")`,

 then the contents of the initialized elements of the array are as-if the resource’s binary data is `[fread](../io/fread "c/io/fread")` into the array at translation time.


Implementations are encouraged to take into account translation-time bit and byte orders as well as execution-time bit and byte orders to more appropriately represent the resource’s binary data from the directive. This maximizes the chance that, if the resource referenced at translation time through the #embed directive is the same one accessed through execution-time means, the data that is e.g. `[fread](../io/fread "c/io/fread")` or similar into contiguous storage will compare bit-for-bit equal to an array of character type initialized from an #embed directive’s expanded contents.


###  Parameters

 The standard defines the parameters `limit`, `prefix`, `suffix` and `if_empty`. Any other parameter that appears in the directive must be implementation-defined, or the program is ill-formed. Implementation-defined embed parameters may change the semantics of the directive.


####  limit

 

|  |  |  |
| --- | --- | --- |
| `limit(` constant-expression `)` |  (1)  |  |
| `__limit__(` constant-expression `)` |  (2)  |  |

 The `limit` embed parameter can appear at most once in the embed parameter sequence. It must have an argument, which must be an integer (preprocessor) [constant expression](../language/constant_expression "c/language/constant expression") that evaluates to a non negative number and does not contain the token `defined`. The resource width is set to the minimum of the integer constant expression multiplied by the embed element width and the implementation resource width.


####  suffix

 

|  |  |  |
| --- | --- | --- |
| `suffix(` pp-balanced-token-sequence ﻿(optional) `)` |  (1)  |  |
| `__suffix__(` pp-balanced-token-sequence ﻿(optional) `)` |  (2)  |  |

 The `suffix` embed parameter can appear at most once in the embed parameter sequence. It must have a (possibly empty) preprocessor argument clause. If the resource is non empty, the contents of the parameter clause are placed immediately after the expansion of the directive. Otherwise, it has no effect.


####  prefix

 

|  |  |  |
| --- | --- | --- |
| `prefix(` pp-balanced-token-sequence ﻿(optional) `)` |  (1)  |  |
| `__prefix__(` pp-balanced-token-sequence ﻿(optional) `)` |  (2)  |  |

 The `prefix` embed parameter can appear at most once in the embed parameter sequence. It must have a (possibly empty) preprocessor argument clause. If the resource is non empty, the contents of the parameter clause are placed immediately before the expansion of the directive. Otherwise, it has no effect.


####  if\_empty

 

|  |  |  |
| --- | --- | --- |
| `if_empty(` pp-balanced-token-sequence ﻿(optional) `)` |  (1)  |  |
| `__if_empty__(` pp-balanced-token-sequence ﻿(optional) `)` |  (2)  |  |

 The `if_empty` embed parameter can appear at most once in the embed parameter sequence. It must have a (possibly empty) preprocessor argument clause. If the resource is empty, the contents of the parameter clause replace the directive. Otherwise, it has no effect.


###  Example

 ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 6.4.7 Header names (p: 69)
+ 6.10.1 Conditional inclusion (p: 165-169)
+ 6.10.2 Binary resource inclusion (p: 170-177)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/preprocessor/embed>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/if>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/for>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/do>

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(attribute specifier) |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/break "cpp/language/break") for `break` statement |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/break>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/goto>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/return>

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

 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`
+ results of all arithmetic, relational, logical, and bitwise operators
+ results of increment and decrement operators (note: pre-forms are lvalues in C++)
+ results of assignment operators (note: also lvalues in C++)
+ the conditional operator (note: is lvalue in C++ if both the second and third operands are lvalues of the same type)
+ the comma operator (note: is lvalue in C++ if the second operand is)
+ the address-of operator, even if neutralized by application to the result of 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/value_category>

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 <inttypes.h>
#include <stdio.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", -9223372036854775807ll - 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/integer_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 `char8_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-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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/character_constant>

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 <stdbool.h>
#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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/bool_constant>

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)`char8_t[N]` (since C23), where `N` is the size of the string in UTF-8 code units including the null terminator. Each `char` (until C23)`char8_t` (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 <inttypes.h>
#include <locale.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <uchar.h>
 
int main(void)
{
    char s1[] = "a猫🍌"; // or "a\u732B\U0001F34C"
#if __STDC_VERSION__ >= 202311L
    char8_t
#else
    char
#endif
    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(
#if __STDC_VERSION__ >= 202311L
    "u8\"%s\" is a char8_t[%zu] holding  { "
#else
    "u8\"%s\" is a char[%zu] holding     { "
#endif
, s2, sizeof s2 / sizeof *s2);
    for(size_t n = 0; n < sizeof s2 / sizeof *s2; ++n)
#if __STDC_VERSION__ >= 202311L
       printf("0x%02X ", s2[n]);
#else
       printf("0x%02X ", +(unsigned char)s2[n]);
#endif
    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%04" PRIXLEAST16" ", 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%08" PRIXLEAST32" ", 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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.4.5 String literals (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/string_literal>

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.


###  Keywords

 [`nullptr`](../keyword/nullptr "c/keyword/nullptr").


###  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*
```
  ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/nullptr>

Compound literals (since C99)
=============================

 Constructs an unnamed object of specified type (which may be struct, union, or even array type) in-place.


###  Syntax

 

|  |  |  |
| --- | --- | --- |
| `(` storage-class-specifiers ﻿(optional)(since C23) type `)` `{` initializer-list `}` |  | (since C99) |
| `(` storage-class-specifiers ﻿(optional)(since C23) type `)` `{` initializer-list `,` `}` |  | (since C99) |
| `(` storage-class-specifiers ﻿(optional) type `)` `{` `}` |  | (since C23) |

 where.




|  |  |  |
| --- | --- | --- |
| storage-class-specifiers |  -  | (since C23) A list of [storage class specifiers](storage_duration "c/language/storage duration") that can contain only `constexpr`, `static`, `register`, or `[thread\_local](http://en.cppreference.com/w/c/thread/thread_local)` |
| 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). | (until C23) |
| If the compound literal is evaluated outside the body of a function and outside of any parameter list, it is associated with file scope; otherwise, it is associated with the enclosing block. Depending on this association, the storage-class specifiers (possibly empty), type name, and initializer list, if any, shall be such that they are valid specifiers for an object definition in file scope or block scope, respectively, of the following form, 
```
   storage-class-specifiers typeof(type) ID = { initializer-list };

```
 where ID is an identifier that is unique for the whole program. A compound literal provides an unnamed object whose value, type, storage duration and other properties are as if given by the definition syntax above; if the storage duration is automatic, the lifetime of the instance of the unnamed object is the current execution of the enclosing block. If the storage-class specifiers contain other specifiers than `constexpr`, `static`, `register`, or `[thread\_local](http://en.cppreference.com/w/c/thread/thread_local)` the behavior is undefined. | (since C23) |

 ###  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, unspecified
```
 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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.5.2.5 Compound literals (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/compound_literal>

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 unless they are part of an operand to a sizeof, \_Alignof (since C11) or typeof/typeof\_unqual (since C23) operator.
* [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) |

 

|  |  |
| --- | --- |
| * named and compound literal constants that are of integer type or that are of arithmetic type and are the immediate operands of casts
 | (since C23) |

 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") or is declared with the `constexpr` storage-class specifier (since C23) must be either string literals or 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 unless they are part of an operand to a sizeof, \_Alignof (since C11) or typeof/typeof\_unqual (since C23) operator
* [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) |

 

|  |  |
| --- | --- |
| * named or compound literal constants of arithmetic type
 | (since C23) |


 
2) a null pointer constant (e.g. `[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) a *named constant* which is, an identifier that is * an enumeration constant
* a predefined constant (one of `true`, `false` or `nullptr`)
* declared with storage-class specifier `constexpr` and has an object type

 or a postfix expression that applies the `.` member access operator to a named constant of structure or union type, even recursively. 6) a *compound literal constant*, which is * a compound literal with storage-class specifier `constexpr`
* a postfix expression that applies the `.` member access operator to a compound literal constant of structure or union type, even recursively.

A *structure or union constant* is a named constant or compound literal constant with structure or union type, respectively. If the member-access operator `.` accesses a member of a union constant, the accessed member shall be the same as the member that is initialized by the union constant’s initializer. | (since C23) |

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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.6 Constant expressions (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/constant_expression>

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 a ? b : c sizeof` `_Alignof`(since C11). |

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_logical "cpp/language/operator logical") for Logical operators |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/operator_logical>

\_Alignof operator (since C11)
==============================

 Queries the alignment requirement of its operand type.


###  Syntax

 

|  |  |  |
| --- | --- | --- |
| `_Alignof(` type-name `)` |  | (since C11) |
| `alignof(` type-name `)` |  | (since C23) |

 

|  |  |
| --- | --- |
| This operator is typically used through the convenience macro [`alignof`](../types "c/types"), which is provided in the header [`<stdalign.h>`](../types "c/types") | (until C23) |

 ###  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` (until C23)`alignof` (since C23) with expressions is allowed by some C compilers as a non-standard extension.


###  Keywords

 [`alignof`](../keyword/alignof "c/keyword/alignof"), [`_Alignof`](../keyword/_alignof "c/keyword/ Alignof").


###  Example

  
```
#include <stdalign.h>
#include <stddef.h>
#include <stdio.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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.5.3.4 The sizeof and alignof operators (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/_Alignof>

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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.5.3.4 The sizeof and alignof operators (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 6.5.3.4 The sizeof and \_Alignof operators (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/sizeof>

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 old 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 <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    int a = 1;
    int b = 1;
 
    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);
    printf("\n");
 
    // Reset a and b.
    a = 1;
    b = 1;
 
    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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.5.2.4 Postfix increment and decrement operators (p: TBD)
+ 6.5.3.1 Prefix increment and decrement operators (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 6.5.2.4 Postfix increment and decrement operators (p: TBD)
+ 6.5.3.1 Prefix increment and decrement operators (p: TBD)

* 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 a ? b : c sizeof` `_Alignof`(since C11). |

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_incdec "cpp/language/operator incdec") for Increment/decrement operators |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/operator_incdec>

Other operators
===============

 A collection of operators that do not fit into any of the other major categories.




|  Operator  |  Operator name  |  Example  |  Description  |
| --- | --- | --- | --- |
| `(...)` | [function call](#Function_call) | `f(...)` |  call the function **f**(), with zero or more arguments  |
| `,` | [comma operator](#Comma_operator) | `a, b` |  evaluate expression **a**, disregard its return value and complete any side-effects, then evaluate expression **b**, returning the type and the result of this evaluation  |
| `(type)` | [type cast](cast "c/language/cast") | `(type)a` |  cast the type of **a** to **type** |
| `? :` | [conditional operator](#Conditional_operator) | `a ? b : c` |  if **a** is logically true (does not evaluate to zero) then evaluate expression **b**, otherwise evaluate expression **c** |
| `sizeof` | [sizeof operator](sizeof "c/language/sizeof") | `sizeof a` |  the size in bytes of **a** |
| `_Alignof`(since C11) | [\_Alignof operator](_alignof "c/language/ Alignof") | `_Alignof(type)` |  the alignment required of **type** |
| `typeof` | [typeof operators](typeof "c/language/typeof") | `typeof(a)` |  the type of **a** |

 ###  Function call

 The function call expression has the form.




|  |  |  |
| --- | --- | --- |
| expression `(` argument-list ﻿(optional) `)` |  |  |

 where.




|  |  |  |
| --- | --- | --- |
| expression |  -  |  any expression of pointer-to-function type (after [lvalue conversions](conversion#Lvalue_conversions "c/language/conversion"))  |
| argument-list |  -  |  comma-separated list of expressions (which cannot be comma operators) of any complete object type. May be omitted when calling functions that take no arguments.  |

 The behavior of the function call expression depends on whether the prototype of the function being called is [in scope](scope "c/language/scope") at the point of call.


####  Call to a function with a prototype

 
1) The number of parameters must equal the number of arguments (unless the ellipsis parameter is used). 
2) The type of each parameter must be a type such that [implicit conversion as if by assignment](conversion "c/language/conversion") exists that converts the unqualified type of the corresponding argument to the type of the parameter. 

|  |  |
| --- | --- |
|  Additionally, for every parameter of [array type](array "c/language/array") that uses the keyword `static` between `[` and `]`, the argument expression must designate a pointer to the element of an array with at least that many elements as specified in the size expression of the parameter.  | (since C99) |

 
3) The arguments are evaluated [in unspecified order and without sequencing](eval_order "c/language/eval order"). 
4) [Assignment](operator_assignment "c/language/operator assignment") is performed to copy the value of each argument to the corresponding function parameter, ignoring any type qualifiers on the parameter type and its possibly recursive elements or members, if any (note: the function can modify its parameters, and those changes do not affect the arguments; C function calls are only call-by-value). * if there is a [trailing ellipsis](variadic "c/language/variadic") parameter, [Default argument promotions](https://en.cppreference.com/mwiki/index.php?title=conversion&action=edit&redlink=1 "conversion (page does not exist)") are performed on the remaining arguments, which are made available to `va_list`.


 
5) Function is executed, and the value it returns becomes the value of the function call expression (if the function returns void, the function call expression is a void expression) 
```
void f(char* p, int x) {}
int main(void)
{
    f("abc", 3.14); // array to pointer and float to int conversions
}
```

 

|  |  |
| --- | --- |
|  Call to a function without a prototype 1) The arguments are evaluated [in unspecified order and without sequencing](eval_order "c/language/eval order"). 2) [Default argument promotions](conversion#Default_argument_promotions "c/language/conversion") are performed on every argument expression. 3) [Assignment](operator_assignment "c/language/operator assignment") is performed to copy the value of each argument to the corresponding function parameter, ignoring any type qualifiers on the parameter type and its possibly recursive elements or members, if any. 4) Function is executed, and the value it returns becomes the value of the function call expression (if the function returns void, the function call expression is a void expression) 
```
void f(); // no prototype
int main(void)
{
    f(1, 1.0f); // UB unless f is defined to take an int and a double
}
void f(int a, double c) {}
```
 The behavior of a function call to a function without a prototype is undefined if.* the number of arguments does not match the number of parameters.
* the promoted types of the arguments are not [compatible](type#Compatible_types "c/language/type") with the promoted types of the parameters except that
+ signed and unsigned versions of the same integer type are considered compatible if the value of the argument is representable by both types.
+ pointers to void and pointers to (possibly cvr-qualified) character types are considered compatible
 | (until C23) |

 ####  Notes

 The evaluations of expression that designates the function to be called and all arguments are [unsequenced](eval_order "c/language/eval order") with respect to each other (but there is a sequence point before the body of the function begins executing).



```
(*pf[f1()]) (f2(), f3() + f4()); // f1, f2, f3, f4 may be called in any order
```
 Although function call is only defined for pointers to functions, it works with function designators due to the [function-to-pointer implicit conversion](conversion#Function_to_pointer_conversion "c/language/conversion").



```
int f(void) { return 1; }
int (*pf)(void) = f;
 
int main(void)
{
    f();    // convert f to pointer, then call
    (&f)(); // create a pointer to function, then call
 
    pf();    // call the function
    (*pf)(); // obtain the function designator, convert to pointer, then calls
 
    (****f)(); // convert to pointer, obtain the function, repeat 4x, then call
    (****pf)(); // also OK
}
```
 Functions that ignore unused arguments, such as `[printf](../io/fprintf "c/io/fprintf")`, must be called with a prototype in scope (the prototype of such functions necessarily uses the [trailing ellipsis](variadic "c/language/variadic") parameter) to avoid invoking undefined behavior.


The current standard wording of the semantics of preparing function parameters is defective, because it specifies that parameters are assigned from arguments while calling, which incorrectly rejects const-qualified parameter or member types, and inappropriately applies the semantics of volatile which is unimplementable for function parameters on many platforms. A post-C11 defect report [DR427](https://open-std.org/JTC1/SC22/WG14/www/docs/n2396.htm#dr_427) proposed change of such semantics from assignment to initialization, but was closed as not-a-defect.




|  |  |
| --- | --- |
| A function call expression where expression consists entirely of an identifier and that identifier is undeclared acts as though the identifier is declared as.

```
extern int identifier(); // returns int and has no prototype
```
 So the following complete program is valid C89:

```
main()
{
    int n = atoi("123"); // implicitly declares atoi as int atoi()
}
```
 | (until C99) |

 ###  Comma operator

 The comma operator expression has the form.




|  |  |  |
| --- | --- | --- |
| lhs `,` rhs |  |  |

 where.




|  |  |  |
| --- | --- | --- |
| lhs |  -  |  any expression  |
| rhs |  -  |  any expression other than another comma operator (in other words, comma operator's [associativity](operator_precedence "c/language/operator precedence") is left-to-right)  |

 First, the left operand, lhs, is evaluated and its result value is discarded.


Then, a [sequence point](eval_order "c/language/eval order") takes place, so that all side effects of lhs are complete.


Then, the right operand, rhs, is evaluated and its result is returned by the comma operator as a [non-lvalue](value_category "c/language/value category").


###  Notes

 The type of the lhs may be `void` (that is, it may be a call to a function that returns `void`, or it can be an expression [cast](cast "c/language/cast") to `void`).


The comma operator may be lvalue in C++, but never in C.


The comma operator may return a struct (the only other expressions that return structs are compound literals, function calls, assignments, and the conditional operator).


In the following contexts, the comma operator cannot appear at the top level of an expression because the comma has a different meaning:


* argument list in a function call
* initializer expression or [initializer list](initialization "c/language/initialization")
* [generic selection](generic "c/language/generic")

 If the comma operator has to be used in such context, it must be parenthesized:



```
// int n = 2,3; // error, comma assumed to begin the next declarator
// int a[2] = {1,2,3}; // error: more initializers than elements
int n = (2,3), a[2] = {(1,2),3}; // OK
 
f(a, (t=3, t+2), c); // OK, first, stores 3 in t, then calls f with three arguments
```
 Top-level comma operator is also disallowed in array bounds.



```
// int a[2,3]; // error
int a[(2,3)]; // OK, VLA array of size 3 (VLA because (2,3) is not a constant expression)
```
 Comma operator is not allowed in [constant expressions](constant_expression "c/language/constant expression"), regardless of whether it's on the top level or not.



```
// static int n = (1,2); // Error: constant expression cannot call the comma operator
```
 ###  Cast operator

 See [cast operator](cast "c/language/cast").


###  Conditional operator

 The conditional operator expression has the form.




|  |  |  |
| --- | --- | --- |
| condition `?` expression-true `:` expression-false |  |  |

 where.




|  |  |  |
| --- | --- | --- |
| condition |  -  |  an expression of scalar type  |
| expression-true |  -  |  the expression that will be evaluated if condition compares unequal to zero  |
| expression-false |  -  |  the expression that will be evaluated if condition compares equal to zero  |

 Only the following expressions are allowed as expression-true and expression-false.


* two expressions of any [arithmetic type](arithmetic_types "c/language/arithmetic types")
* two expressions of the same [struct](struct "c/language/struct") or [union](union "c/language/union") type
* two expressions of void type
* two expressions of pointer type, pointing to types that are [compatible](type#Compatible_types "c/language/type"), ignoring cvr-qualifiers

 

|  |  |
| --- | --- |
| * two expressions of `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` type
 | (since C23) |

 * one expression is a pointer and the other is the 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)
* one expression is a pointer to object and the other is a pointer to void (possibly qualified)

 
1) First, evaluates condition. There is a [sequence point](eval_order "c/language/eval order") after this evaluation. 
2) If the result of condition compares unequal to zero, executes expression-true, otherwise executes expression-false
 
3) Performs a [conversion](conversion "c/language/conversion") from the result of the evaluation to the *common type*, defined as follows: 
1) if the expressions have arithmetic type, the common type is the type after [usual arithmetic conversions](conversion#Usual_arithmetic_conversions "c/language/conversion")
 
2) if the expressions have struct/union type, the common type is that struct/union type 
3) if the expressions are both void, the entire conditional operator expression is a void expression 
4) if one is a pointer and the other is a null pointer constantor a `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` value (since C23), the type is the type of that pointer 
5) if both are pointers, the result is the pointer to the type that combines cvr-qualifiers of both pointed-to types (that is, if one is `const int*` and the other is `volatile int*`, the result is `const volatile int*`), and if the types were different, the pointed-to type is the [composite type](types#Composite_type "c/language/types"). 
6) if one is a pointer to void, the result is a pointer to void with combined cvr-qualifiers 

|  |  |
| --- | --- |
| 7) if both have `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` type, the common type is also `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` | (since C23) |

 
```
#define ICE(x) (sizeof(*(1 ? ((void*)((x) * 0l)) : (int*)1)))
 
// if x is an Integer Constant Expression then macro expands to
 
sizeof(*(1 ? NULL : (int *) 1))  // (void *)((x)*0l)) -> NULL
 
// according to point (4) this further converts into
 
sizeof(int)
 
// if x is not an Integer Constant Expression then macro expands to
// according to point (6)
 
(sizeof(*(void *)(x))           // Error due incomplete type
```
 ####  Notes

 The conditional operator is never an [lvalue expression](value_category "c/language/value category"), although it may return objects of struct/union type. The only other expressions that may return structs are [assignment](operator_assignment "c/language/operator assignment"), [comma](#Comma_operator), [function call](#Function_call), and [compound literal](compound_literal "c/language/compound literal").


Note that in C++, it may be an lvalue expression.


See [operator precedence](operator_precedence "c/language/operator precedence") for the details on the relative precedence of this operator and assignment.


Conditional operator has right-to-left associativity, which allows chaining.


 
```
#include <assert.h>
 
enum vehicle { bus, airplane, train, car, horse, feet };
 
enum vehicle choose(char arg)
{
    return arg == 'B' ? bus      :
           arg == 'A' ? airplane :
           arg == 'T' ? train    :
           arg == 'C' ? car      :
           arg == 'H' ? horse    :
                        feet     ;
}
 
int main(void)
{
    assert(choose('H') == horse && choose('F') == feet);
}
```
  ###  `sizeof` operator

 See [sizeof operator](sizeof "c/language/sizeof").


###  `_Alignof` operator

 See [\_Alignof operator](_alignof "c/language/ Alignof").


###  `typeof` operators

 See [typeof operators](typeof "c/language/typeof").


###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 6.5.2.2 Function calls (p: TBD)
+ 6.5.3.4 The sizeof and \_Alignof operators (p: TBD)
+ 6.5.4 Cast operators (p: TBD)
+ 6.5.15 Conditional operator (p: TBD)
+ 6.5.17 Comma operator (p: TBD)
+ 6.7.3.5 Typeof specifiers (p: 115-118)

* C17 standard (ISO/IEC 9899:2018):
+ 6.5.2.2 Function calls (p: 58-59)
+ 6.5.3.4 The sizeof and \_Alignof operators (p: 64-65)
+ 6.5.4 Cast operators (p: 65-66)
+ 6.5.15 Conditional operator (p: 71-72)
+ 6.5.17 Comma operator (p: 75)

* C11 standard (ISO/IEC 9899:2011):
+ 6.5.2.2 Function calls (p: 81-82)
+ 6.5.3.4 The sizeof and \_Alignof operators (p: 90-91)
+ 6.5.4 Cast operators (p: 91)
+ 6.5.15 Conditional operator (p: 100)
+ 6.5.17 Comma operator (p: 105)

* C99 standard (ISO/IEC 9899:1999):
+ 6.5.2.2 Function calls (p: 71-72)
+ 6.5.3.4 The sizeof operator (p: 80-81)
+ 6.5.4 Cast operators (p: 81)
+ 6.5.15 Conditional operator (p: 90-91)
+ 6.5.17 Comma operator (p: 94)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.3.2.2 Function calls
+ 3.3.3.4 The sizeof operator
+ 3.3.4 Cast operators
+ 3.3.15 Conditional operator
+ 3.3.17 Comma 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](operator_logical "c/language/operator logical") |  [comparison](operator_comparison "c/language/operator comparison") |  [memberaccess](operator_member_access "c/language/operator member access") |  **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 a ? b : c sizeof` `_Alignof`(since C11). |

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_other "cpp/language/operator other") for Other operators |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/operator_other>

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 or function
+ 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 a ? b : c sizeof` `_Alignof`(since C11). |

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_comparison "cpp/language/operator comparison") for Comparison operators |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/operator_comparison>

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 arithmetic 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)
{
    uint32_t a = 0x12345678;
    uint16_t mask = 0x00f0;
 
    printf("Promoted mask:\t%#010x\n"
           "Value:\t\t%#x\n"
           "Setting bits:\t%#x\n"
           "Clearing bits:\t%#x\n"
           "Selecting bits:\t%#010x\n"
           , mask
           , a
           , a | mask
           , a & ~mask
           , a & mask
    );
}
```
 Possible output:



```
Promoted mask:  0x000000f0
Value:          0x12345678
Setting bits:   0x123456f8
Clearing bits:  0x12345608
Selecting bits: 0x00000070
```
  ###  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 a ? b : c sizeof` `_Alignof`(since C11). |

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_arithmetic "cpp/language/operator arithmetic") for Arithmetic operators |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/operator_arithmetic>

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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.5.4 Cast operators (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/cast>

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 a ? b : c sizeof` `_Alignof`(since C11). |

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_precedence "cpp/language/operator precedence") for C++ operator precedence |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/operator_precedence>

Generic selection (since C11)
=============================

 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>`](../numeric/tgmath "c/numeric/tgmath"), 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 <math.h>
#include <stdio.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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.5.1.1 Generic selection (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/generic>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/switch>

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++)) // double parentheses (that are not strictly necessary)
                         // used to suppress warnings, ensuring that this is an
                         // assignment (as opposed to a comparison) by intention,
                         // whose result is used as a truth value
        ; // 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/while>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/continue>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/array_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)  | (until C99) |
| `=` `{` designator(optional) 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/struct_initialization>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/pointer>

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 operand of [`typeof`](typeof "c/language/typeof") and [`typeof_unqual`](https://en.cppreference.com/mwiki/index.php?title=c/language/typeof_unqual&action=edit&redlink=1 "c/language/typeof unqual (page does not exist)") (since C23)
* 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 dimensionif 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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.7.6.2 Array declarators (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/array>

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` (until C23)`thread_local` (since C23) - 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` (until C23)`thread_local` (since C23) 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` (until C23)`thread_local` (since C23)) (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` (until C23)`thread_local` (since C23) 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 (until C23)
* ***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` (until C23)`thread_local` (since C23) (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` (until C23)`thread_local` (since C23) 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") [`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>`](../thread "c/thread"). | (until C23) |

 The [`typedef`](typedef "c/language/typedef") and [`constexpr`](https://en.cppreference.com/mwiki/index.php?title=c/language/constexpr&action=edit&redlink=1 "c/language/constexpr (page does not exist)") (since C23) specifiers are formally listed as storage-class specifiers in the C language grammar, but do not specify storage.




|  |  |
| --- | --- |
| The auto specifier is also used for type inference. | (since C23) |

 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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.2.2 Linkages of identifiers (p: 35-36)
+ 6.2.4 Storage durations of objects (p: 36-37)
+ 6.7.1 Storage-class specifiers (p: 97-100)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/storage_duration>

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.


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

 
```
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
```
 If a function type is declared with the const type qualifier (through the use of [typedef](typedef "c/language/typedef")), the behavior is undefined.




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

 

|  |  |
| --- | --- |
| 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 a non-const type can be implicitly converted to a pointer to const-qualified version of the same or [compatible](compatible_type "c/language/compatible type") type. The reverse conversion requires 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)
```
 ###  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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/const>

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

 
```
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
```
 If a function type is declared with the volatile type qualified (through the use of [`typedef`](typedef "c/language/typedef")), the behavior is undefined.




|  |  |
| --- | --- |
| 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](compatible_type "c/language/compatible type") type. The reverse conversion requires 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 micro-benchmarks. 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/volatile>

restrict type qualifier (since C99)
===================================

 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`](https://gcc.gnu.org/onlinedocs/gcc/Common-Type-Attributes.html#index-g_t_0040code_007bmay_005falias_007d-type-attribute-3667) (gcc),


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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.7.3.1 Formal definition of restrict (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/restrict>

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, keeping their structure layout. 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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.7.2.1 Structure and union specifiers (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/struct>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/eval_order>

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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.4.4.2 Floating constants (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/floating_constant>

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 `}` |  (1)  |  |
| `enum` attr-spec-seq ﻿(optional) identifier ﻿(optional) `:` type `{` enumerator-list `}` |  (2)  | (since C23) |

 
1) Declares an enumeration without a fixed underlying type. 
2) Declares an enumeration of fixed underlying type type. 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 (until C23). If the enumeration has a fixed underlying type, representable as a value of type (since C23) |
| 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 (until C23) 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).




|  |  |
| --- | --- |
| During the processing of each enumeration constant in the enumerator list, the type of the enumeration constant shall be:* the previously declared type, if it is a redeclaration of the same enumeration constant; or,
* the enumerated type, for an enumeration with fixed underlying type; or,
* int, if there are no previous enumeration constants in the enumerator list and no explicit = with a defining integer constant expression; or,
* int, if given explicitly with = and the value of the integer constant expression is representable by an int; or,
* the type of the integer constant expression, if given explicitly with = and if the value of the integer constant expression is not representable by int; or,
* the type of the value from last enumeration constant with 1 added to it. If such an integer constant expression would overflow or wraparound the value of the previous enumeration constant from the addition of 1, the type takes on either:
	+ a suitably sized signed integer type (excluding the bit-precise signed integer types) capable of representing the value of the previous enumeration constant plus 1; or,
	+ a suitably sized unsigned integer type (excluding the bit-precise unsigned integer types) capable of representing the value of the previous enumeration constant plus 1.

A signed integer type is chosen if the previous enumeration constant being added is of signed integer type. An unsigned integer type is chosen if the previous enumeration constant is of unsigned integer type. If there is no suitably sized integer type described previous which can represent the new value, then the enumeration has no type which is capable of representing all of its values. | (since C23) |

 
```
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 without a fixed underlying type (since C23) is [compatible](type#Compatible_types "c/language/type") with one of: char, a signed integer type, or an unsigned integer type (excluding the bit-precise integer types) (since C23). 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. For all enumerations with a fixed underlying type, the enumerated type is compatible with the underlying type of the enumeration. (since C23).




|  |  |
| --- | --- |
| The enumeration member type for an enumerated type without fixed underlying type upon completion is:* int if all the values of the enumeration are representable as an int; or,
* the enumerated type.
 | (since C23) |

 

|  |  |
| --- | --- |
| All enumerations have an underlying type. The underlying type can be explicitly specified using an enum-type-specifier and is its fixed underlying type. If it is not explicitly specified, the underlying type is the enumeration’s compatible type, which is either a signed or unsigned integer type, or char. | (since C23) |

   
 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
```
 In C23 [constexpr](https://en.cppreference.com/mwiki/index.php?title=c/language/constexpr&action=edit&redlink=1 "c/language/constexpr (page does not exist)") can be used for the same purpose:



```
constexpr int 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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.2.5/21 Types (p: 39)
+ 6.7.2.2 Enumeration specifiers (p: 107-112)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/enum>

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](bit_field "c/language/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 keeping their union layout. 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 <assert.h>
#include <stdint.h>
#include <stdio.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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.7.2.1 Structure and union specifiers (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/union>

\_Alignas (since C11), alignas (since C23)
==========================================

 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` `(` expression `)` |  (2)  | (since C23) |
| `_Alignas` `(` type `)` |  (3)  | (since C11) |
| `alignas` `(` type `)` |  (4)  | (since C23) |

 

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

 

|  |  |
| --- | --- |
| The keyword `_Alignas` is also available as convenience macro [`alignas`](../types "c/types"), available in the header [`<stdalign.h>`](../types "c/types"). | (until C23) |

 ###  Explanation

 The `_Alignas` (until C23)`alignas` (since C23) specifier can only be used when declaring objects that are not [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,2) the result of the expression, unless it is zero 
3,4) the alignment requirement of type, that is, to `_Alignof(type)` (until C23)`alignof(type)` (since C23)
 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` (until C23)`alignas` (since C23) specifiers appear in the same declaration, the strictest one is used.


`_Alignas` (until C23)`alignas` (since C23) specifier only needs to appear on the [definition](declarations#Definitions "c/language/declarations") of an object, but if any declaration uses `_Alignas` (until C23)`alignas` (since C23), it must specify the same alignment as the `_Alignas` (until C23)`alignas` (since C23) 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` (until C23)`alignas` (since C23) in a member declaration.


###  Keywords

 [`alignas`](../keyword/alignas "c/keyword/alignas"), [`_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
    (void)d; // suppresses "maybe unused" warning
}
```
 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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.7.5 Alignment specifier (p: TBD)
+ 6.2.8 Alignment of objects (p: TBD)
+ 7.15 Alignment <stdalign.h> (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/_Alignas>

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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.7.8 Type definitions (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 6.7.8 Type definitions (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/typedef>

Attribute specifier sequence(since C23)
=======================================

 Introduces implementation-defined attributes for types, objects, expressions, etc.


###  Syntax

 `[[`attr ﻿`]]` `[[`attr1, attr2, attr3`(`args`)``]]` `[[`attribute-prefix`::`attr ﻿`(`args`)``]]` Formally, the syntax is.




|  |  |  |
| --- | --- | --- |
| `[[` attribute-list `]]` |  | (since C23) |

 where attribute-list is a comma-separated sequence of zero or more attribute-token ﻿s.




|  |  |  |
| --- | --- | --- |
| standard-attribute |  (1)  |  |
| attribute-prefix `::` identifier |  (2)  |  |
| standard-attribute `(` argument-list ﻿(optional) `)` |  (3)  |  |
| attribute-prefix `::` identifier `(` argument-list ﻿(optional) `)` |  (4)  |  |

 where attribute-prefix is an identifier and argument-list is a sequence of tokens where parentheses, brackets and braces are balanced (balanced-token-sequence).



1) standard attribute, such as [[fallthrough]]
 
2) attribute with a namespace, such as [[gnu::unused]]
 
3) standard attribute with arguments, such as [[deprecated("reason")]]
 
4) attribute with both a namespace and an argument list, such as [[gnu::nonnull(1)]]
 ###  Explanation

 Attributes provide the unified standard syntax for implementation-defined language extensions, such as the GNU and IBM language extensions `__attribute__((...))`, Microsoft extension `__declspec()`, etc.


An attribute can be used almost everywhere in the C program, and can be applied to almost everything: to types, to variables, to functions, to names, to code blocks, to entire translation units, although each particular attribute is only valid where it is permitted by the implementation: `[[expect_true]]` could be an attribute that can only be used with an `if`, and not with a class declaration. `[[omp::parallel()]]` could be an attribute that applies to a code block or to a `for` loop, but not to the type `int`, etc. (note these two attributes are fictional examples, see below for the standard and some non-standard attributes).


In declarations, attributes may appear both before the whole declaration and directly after the name of the entity that is declared, in which case they are combined. In most other situations, attributes apply to the directly preceding entity.


Two consecutive left square bracket tokens (`[[`) may only appear when introducing an attribute-specifier or inside an attribute argument.


Besides the standard attributes listed below, implementations may support arbitrary non-standard attributes with implementation-defined behavior. All attributes unknown to an implementation are ignored without causing an error.


Every standard-attribute is reserved for standardization. That is, every non-standard attribute is prefixed by a attribute-prefix provided by the implementation, e.g. `[[gnu::may_alias]]` and `[[clang::no_sanitize]]`.


###  Standard attributes

 Only the following attributes are defined by the C standard. Every standard attribute whose name is of form `attr` can be also spelled as `__attr__` and its meaning is not changed.




|  |  |
| --- | --- |
| `[[[deprecated](attributes/deprecated "c/language/attributes/deprecated")]]`(C23)`[[[deprecated](attributes/deprecated "c/language/attributes/deprecated")("*reason*")]]`(C23) |  indicates that the use of the name or entity declared with this attribute is allowed, but discouraged for some reason(attribute specifier) |
| `[[[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(attribute specifier) |
| `[[[nodiscard](attributes/nodiscard "c/language/attributes/nodiscard")]]`(C23)`[[[nodiscard](attributes/nodiscard "c/language/attributes/nodiscard")("*reason*")]]`(C23) |  encourages the compiler to issue a warning if the return value is discarded(attribute specifier) |
| `[[[maybe\_unused](attributes/maybe_unused "c/language/attributes/maybe unused")]]`(C23) |  suppresses compiler warnings on unused entities, if any(attribute specifier) |
| `[[[noreturn](attributes/noreturn "c/language/attributes/noreturn")]]`(C23)`[[[\_Noreturn](attributes/noreturn "c/language/attributes/noreturn")]]`(C23)(deprecated) |  indicates that the function does not return(attribute specifier) |
| `[[[unsequenced](https://en.cppreference.com/mwiki/index.php?title=c/language/attributes/unsequenced&action=edit&redlink=1 "c/language/attributes/unsequenced (page does not exist)")]]`(C23) |  indicates that a function is stateless, effectless, idempotent and independent(attribute specifier) |
| `[[[reproducible](https://en.cppreference.com/mwiki/index.php?title=c/language/attributes/reproducible&action=edit&redlink=1 "c/language/attributes/reproducible (page does not exist)")]]`(C23) |  indicates that a function is effectless and idempotent(attribute specifier) |

 ###  Attribute testing

 

|  |  |  |
| --- | --- | --- |
| `__has_c_attribute(` attribute-token `)` |  |  |

 Checks for the presence of an attribute token named by attribute-token.


For standard attributes, it will expand to the year and month in which the attribute was added to the working draft (see table below), the presence of vendor-specific attributes is determined by a non-zero integer constant.


`__has_c_attribute` can be expanded in the expression of  [`#if`](../preprocessor/conditional "c/preprocessor/conditional") and  [`#elif`](../preprocessor/conditional "c/preprocessor/conditional"). It is treated as a defined macro by  [`#ifdef`](../preprocessor/conditional "c/preprocessor/conditional"),  [`#ifndef`](../preprocessor/conditional "c/preprocessor/conditional") and [`defined`](../preprocessor/conditional "c/preprocessor/conditional") but cannot be used anywhere else.




| attribute-token |  Attribute  |  Value  | Standard |
| --- | --- | --- | --- |
| `deprecated` | `[[[deprecated](attributes/deprecated "c/language/attributes/deprecated")]]` | `201904L` | (C23) |
| `fallthrough` | `[[[fallthrough](attributes/fallthrough "c/language/attributes/fallthrough")]]` | `201904L` | (C23) |
| `maybe_unused` | `[[[maybe\_unused](attributes/maybe_unused "c/language/attributes/maybe unused")]]` | `201904L` | (C23) |
| `nodiscard` | `[[[nodiscard](attributes/nodiscard "c/language/attributes/nodiscard")]]` | `202003L` | (C23) |
| `noreturn``_Noreturn` | `[[[noreturn](attributes/noreturn "c/language/attributes/noreturn")]]``[[[\_Noreturn](attributes/noreturn "c/language/attributes/noreturn")]]` | `202202L` | (C23) |
| `unsequenced` | `[[[unsequenced](https://en.cppreference.com/mwiki/index.php?title=c/language/attributes/unsequenced&action=edit&redlink=1 "c/language/attributes/unsequenced (page does not exist)")]]` | `202207L` | (C23) |
| `reproducible` | `[[[reproducible](https://en.cppreference.com/mwiki/index.php?title=c/language/attributes/reproducible&action=edit&redlink=1 "c/language/attributes/reproducible (page does not exist)")]]` | `202207L` | (C23) |

 ###  Example

  
```
[[gnu::always_inline]] [[gnu::hot]] [[gnu::const]] [[nodiscard]]
int f(void); // declare f with four attributes
 
[[gnu::always_inline, gnu::const, gnu::hot, nodiscard]]
int f(void); // same as above, but uses a single attr specifier that contains four attributes
 
int f(void) { return 0; }
 
int main(void)
{
}
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/attributes "cpp/language/attributes") for Attribute specifier sequence |

 ###  External links

 

|  |  |
| --- | --- |
| 1.  | [Attributes in GCC](https://gcc.gnu.org/onlinedocs/gcc/Attribute-Syntax.html#Attribute-Syntax) |
| 2.  | [Attributes in Clang](https://clang.llvm.org/docs/AttributeReference.html) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/attributes>

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 (until C23). A new style function declaration 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, block 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 `, ...` or be `...` (since C23), 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++, 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
```
 | (until C23) |

 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/function_declaration>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/function_definition>

Implicit conversions
====================

 When an expression is used in the context where a value of a different type is expected, *conversion* may occur:



```
int n = 1L; // expression 1L has type long, int is expected
n = 2.1; // expression 2.1 has type double, int is expected
char *p = malloc(10); // expression malloc(10) has type void*, char* is expected
```
 Conversions take place in the following situations:


###  Conversion as if by assignment

 * In the [assignment](operator_assignment "c/language/operator assignment") operator, the value of the right-hand operand is converted to the unqualified type of the left-hand operand.
* In [scalar initialization](scalar_initialization "c/language/scalar initialization"), the value of the initializer expression is converted to the unqualified type of the object being initialized
* In a [function-call expression](operator_other "c/language/operator other"), to a function that has a prototype, the value of each argument expression is converted to the type of the unqualified declared types of the corresponding parameter
* In a [return statement](return "c/language/return"), the value of the operand of `return` is converted to an object having the return type of the function

 Note that actual assignment, in addition to the conversion, also removes extra range and precision from floating-point types and prohibits overlaps; those characteristics do not apply to conversion as if by assignment.


###  Default argument promotions

 In a [function call expression](operator_other#Function_call "c/language/operator other") when the call is made to.



1) a [function without a prototype](function_declaration "c/language/function declaration")
 
2) a [variadic function](variadic "c/language/variadic"), where the argument expression is one of the trailing arguments that are matched against the ellipsis parameter Each argument of integer type undergoes *integer promotion* (see below), and each argument of type `float` is implicitly converted to the type `double`.



```
int add_nums(int count, ...);
int sum = add_nums(2, 'c', true); // add_nums is called with three ints: (2, 99, 1)
```
 

|  |  |
| --- | --- |
| Note that `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)` and `float [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)` are not promoted to `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)` and `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)` in this context. | (since C99) |

 ###  Usual arithmetic conversions

 The arguments of the following arithmetic operators undergo implicit conversions for the purpose of obtaining the *common real type*, which is the type in which the calculation is performed:


* [binary arithmetic](operator_arithmetic "c/language/operator arithmetic") \*, /, %, +, -
* [relational operators](operator_comparison "c/language/operator comparison") <, >, <=, >=, ==, !=
* [binary bitwise arithmetic](operator_arithmetic "c/language/operator arithmetic") &, ^, |,
* the [conditional operator](operator_other "c/language/operator other") ?:

 
1) If one operand is `long double`, `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)`  (since C99), the other operand is implicitly converted as follows: * integer or real floating type to `long double`

 

|  |  |
| --- | --- |
| * complex type to `long double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`
* imaginary type to `long double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`
 | (since C99) |


 
2) Otherwise, if one operand is `double`, `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, or `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`  (since C99), the other operand is implicitly converted as follows: * integer or real floating type to `double`

 

|  |  |
| --- | --- |
| * complex type to `double [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`
* imaginary type to `double [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`
 | (since C99) |


 
3) Otherwise, if one operand is `float`, `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`, or `float [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`  (since C99), the other operand is implicitly converted as follows: * integer type to `float` (the only real type possible is float, which remains as-is)

 

|  |  |
| --- | --- |
| * complex type remains `float [complex](http://en.cppreference.com/w/c/numeric/complex/complex)`
* imaginary type remains `float [imaginary](http://en.cppreference.com/w/c/numeric/complex/imaginary)`
 | (since C99) |


 
4) Otherwise, both operands are integers. Both operands undergo *integer promotions* (see below); then, after integer promotion, one of the following cases applies: * If the types are the same, that type is the common type.
* Else, the types are different:
	+ If the types have the same signedness (both signed or both unsigned), the operand whose type has the lesser *conversion rank*1 is implicitly converted2 to the other type.
	+ Else, the operands have different signedness:
		- If the unsigned type has *conversion rank* greater than or equal to the rank of the signed type, then the operand with the signed type is implicitly converted to the unsigned type.
		- Else, the unsigned type has *conversion rank* less than the signed type:
			* If the signed type can represent all values of the unsigned type, then the operand with the unsigned type is implicitly converted to the signed type.
			* Else, both operands undergo implicit conversion to the unsigned type counterpart of the signed operand's type.


 

---

 
1. Refer to "integer promotions" below for the rules on ranking. 
2. Refer to "integer conversions" under "implicit conversion semantics" below. 
 
```
1.f + 20000001; // int is converted to float, giving 20000000.00
                // addition and then rounding to float gives 20000000.00
 
(char)'a' + 1L; // first, char 'a', which is 97, is promoted to int
                // different types: int and long
                // same signedness: both signed
                // different rank: long is of greater rank than int
                // therefore, int 97 is converted to long 97
                // the result is 97 + 1 = 98 of type signed long
 
2u - 10; // different types: unsigned int and signed int
         // different signedness
         // same rank
         // therefore, signed int 10 is converted to unsigned int 10
         // since the arithmetic operation is performed for unsigned integers
         // (see "Arithmetic operators" topic), the calculation performed is (2 - 10)
         // modulo (2 raised to n), where n is the number of value bits of unsigned int
         // if unsigned int is 32-bit long and there is no padding bits in its object
         // representation, then the result is (-8) modulo (2 raised to 32) = 4294967288
         // of type unsigned int
 
5UL - 2ULL; // different types: unsigned long and unsigned long long
            // same signedness
            // different rank: rank of unsigned long long is greater
            // therefore, unsigned long 5 is converted to unsigned long long 5
            // since the arithmetic operation is performed for unsigned integers
            // (see "Arithmetic operators" topic),
            // if unsigned long long is 64-bit long, then
            // the result is (5 - 2) modulo (2 raised to 64) = 3 of type
            // unsigned long long
 
0UL - 1LL; // different types: unsigned long and signed long long
           // different signedness
           // different rank: rank of signed long long is greater.
           // if ULONG_MAX > LLONG_MAX, then signed long long cannot represent all
           // unsigned long therefore, this is the last case: both operands are converted
           // to unsigned long long unsigned long 0 is converted to unsigned long long 0
           // long long 1 is converted to unsigned long long 1 since the arithmetic
           // operation is performed for unsigned integers
           // (see "Arithmetic operators" topic),
           // if unsigned long long is 64-bit long, then  
           // the calculation is (0 - 1) modulo (2 raised to 64)
           // thus, the result is 18446744073709551615 (ULLONG_MAX) of type
           // unsigned long long
```
 

|  |  |
| --- | --- |
| The result type is determined as follows:* if both operands are complex, the result type is complex
* if both operands are imaginary, the result type is imaginary
* if both operands are real, the result type is real
* if the two floating-point operands have different type domains (complex vs. real, complex vs imaginary, or imaginary vs. real), the result type is complex


```
double complex z = 1 + 2*I;
double f = 3.0;
z + f; // z remains as-is, f is converted to double, the result is double complex
```
 | (since C99) |

 As always, the result of a floating-point operator may have greater range and precision than is indicated by its type (see `[FLT\_EVAL\_METHOD](../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")`).




|  |  |
| --- | --- |
| Note: real and imaginary operands are not implicitly converted to complex because doing so would require extra computation, while producing undesirable results in certain cases involving infinities, NaNs and signed zeros. For example, if reals were converted to complex, 2.0×(3.0+i∞) would evaluate as (2.0+i0.0)×(3.0+i∞) ⇒ (2.0×3.0–0.0×∞) + i(2.0×∞+0.0×3.0) ⇒ NaN+i∞ rather than the correct 6.0+i∞. If imaginaries were converted to complex, i2.0×(∞+i3.0) would evaluate as (0.0+i2.0) × (∞+i3.0) ⇒ (0.0×∞ – 2.0×3.0) + i(0.0×3.0 + 2.0×∞) ⇒ NaN + i∞ instead of –6.0 + i∞. | (since C99) |

 Note: regardless of usual arithmetic conversions, the calculation may always be performed in a narrower type than specified by these rules under the [as-if rule](as_if "c/language/as if").


###  Value transformations

 ####  Lvalue conversion

 Any [lvalue expression](value_category "c/language/value category") of any non-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") (if allowed)
* 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.
* as the operand of [sizeof](sizeof "c/language/sizeof")

 undergoes *lvalue conversion*: the type remains the same, but loses [const](const "c/language/const")/[volatile](volatile "c/language/volatile")/[restrict](restrict "c/language/restrict")-qualifiers and [atomic](atomic "c/language/atomic") properties, if any. The value remains the same, but loses its lvalue properties (the address may no longer be taken).


If the lvalue has incomplete type, the behavior is undefined.


If the lvalue designates an object of automatic storage duration whose address was never taken and if that object was uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.


This conversion models the memory load of the value of the object from its location.



```
volatile int n = 1;
int x = n;            // lvalue conversion on n reads the value of n
volatile int* p = &n; // no lvalue conversion: does not read the value of n
```
 ####  Array to pointer conversion

 Any [lvalue expression](value_category "c/language/value category") of [array type](array "c/language/array"), 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 operand of [typeof](typeof "c/language/typeof") and [typeof\_unqual](https://en.cppreference.com/mwiki/index.php?title=c/language/typeof_unqual&action=edit&redlink=1 "c/language/typeof unqual (page does not exist)") (since C23)
* as the string literal used for [array initialization](array_initialization "c/language/array initialization")

 undergoes a conversion to the non-lvalue pointer to its first element.


If the array was declared [register](storage_duration "c/language/storage duration"), the behavior is undefined.



```
int a[3], b[3][4];
int* p = a;      // conversion to &a[0]
int (*q)[4] = b; // conversion to &b[0]
```
 ####  Function to pointer conversion

 Any function designator expression, 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 operand of [typeof](typeof "c/language/typeof") and [typeof\_unqual](https://en.cppreference.com/mwiki/index.php?title=c/language/typeof_unqual&action=edit&redlink=1 "c/language/typeof unqual (page does not exist)") (since C23)

 undergoes a conversion to the non-lvalue pointer to the function designated by the expression.



```
int f(int);
int (*p)(int) = f; // conversion to &f
(***p)(1); // repeated dereference to f and conversion back to &f
```
 ###  Implicit conversion semantics

 Implicit conversion, whether *as if by assignment* or a *usual arithmetic conversion*, consists of two stages:



1) value transformation (if applicable) 
2) one of the conversions listed below (if it can produce the target type) ####  Compatible types

 Conversion of a value of any type to any [compatible type](types#Compatible_types "c/language/types") is always a no-op and does not change the representation.



```
uint8_t (*a)[10];         // if uint8_t is a typedef to unsigned char
unsigned char (*b)[] = a; // then these pointer types are compatible
```
 ####  Integer promotions

 Integer promotion is the implicit conversion of a value of any integer type with *rank* less or equal to *rank* of int or of a [bit-field](bit_field "c/language/bit field") of type `_Bool` (until C23)`bool` (since C23), `int`, `signed int`, `unsigned int`, to the value of type `int` or `unsigned int`.


If `int` can represent the entire range of values of the original type (or the range of values of the original bit-field), the value is converted to type `int`. Otherwise the value is converted to `unsigned int`.


Integer promotions preserve the value, including the sign:



```
int main(void)
{
    void f(); // old-style function declaration
    char x = 'a'; // integer conversion from int to char
    f(x); // integer promotion from char back to int
}
 
void f(x) int x; {} // the function expects int
```
 *rank* above is a property of every [integer type](type "c/language/type") and is defined as follows:



1) the ranks of all signed integer types are different and increase with their precision: rank of `signed char` < rank of `short` < rank of `int` < rank of `long int` < rank of `long long int`
 
2) the ranks of all signed integer types equal the ranks of the corresponding unsigned integer types 
3) the rank of any standard integer type is greater than the rank of any extended integer type of the same size (that is, rank of `__int64` < rank of `long long int`, but rank of `long long` < rank of `__int128` due to the rule (1)) 
4) rank of `char` equals rank of `signed char` and rank of `unsigned char`
 
5) the rank of `_Bool` (until C23)`bool` (since C23) is less than the rank of any other standard integer type 
6) the rank of any enumerated type equals the rank of its compatible integer type 
7) ranking is transitive: if rank of T1 < rank of T2 and rank of T2 < rank of T3 then rank of T1 < rank of T3 
8) any aspects of relative ranking of extended integer types not covered above are implementation defined. Note: integer promotions are applied only.


* as part of *usual arithmetic conversions* (see above)
* as part of *default argument promotions* (see above)
* to the operand of the unary arithmetic operators `+` and `-`
* to the operand of the unary bitwise operator `~`
* to both operands of the shift operators `<<` and `>>`

 

|  |  |
| --- | --- |
|  Boolean conversion A value of any scalar type can be implicitly converted to `_Bool` (until C23)`bool` (since C23). The values that compare equal to an integer constant expression of value zero (until C23)are a zero (for arithmetic types), null (for pointer types) or have a type of `[nullptr\_t](../types/nullptr_t "c/types/nullptr t")` (since C23) are converted to `​0​` (until C23)`false` (since C23), all other values are converted to `1` (until C23)`true` (since C23).

```
bool b1 = 0.5;              // b1 == 1 (0.5 converted to int would be zero)
bool b2 = 2.0*_Imaginary_I; // b2 == 1 (but converted to int would be zero)
bool b3 = 0.0 + 3.0*I;      // b3 == 1 (but converted to int would be zero)
bool b4 = 0.0/0.0;          // b4 == 1 (NaN does not compare equal to zero)
bool b5 = nullptr;          // b5 == 0 (since C23: nullptr is converted to false)
```
 | (since C99) |

 ####  Integer conversions

 A value of any integer type can be implicitly converted to any other integer type. Except where covered by promotions and boolean conversions above, the rules are:


* if the target type can represent the value, the value is unchanged
* otherwise, if the target type is unsigned, the value 2b  
, where b is the number of value bits in the target type, is repeatedly subtracted or added to the source value until the result fits in the target type. In other words, unsigned integers implement modulo arithmetic.
* otherwise, if the target type is signed, the behavior is implementation-defined (which may include raising a signal)

 
```
char x = 'a'; // int -> char, result unchanged
unsigned char n = -123456; // target is unsigned, result is 192 (that is, -123456+483*256)
signed char m = 123456;    // target is signed, result is implementation-defined
assert(sizeof(int) > -1);  // assert fails:
                           // operator > requests conversion of -1 to size_t,
                           // target is unsigned, result is SIZE_MAX
```
 ####  Real floating-integer conversions

 A finite value of any real floating type can be implicitly converted to any integer type. Except where covered by boolean conversion above, the rules are:


* The fractional part is discarded (truncated towards zero).
+ If the resulting value can be represented by the target type, that value is used
+ otherwise, the behavior is undefined

 
```
int n = 3.14; // n == 3
int x = 1e10; // undefined behavior for 32-bit int
```
 A value of any integer type can be implicitly converted to any real floating type.


* if the value can be represented exactly by the target type, it is unchanged
* if the value can be represented, but cannot be represented exactly, the result is an implementation-defined choice of either the nearest higher or nearest lower value, although if IEEE arithmetic is supported, rounding is to nearest. It is unspecified whether `[FE\_INEXACT](../numeric/fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised in this case.
* if the value cannot be represented, the behavior is undefined, although if IEEE arithmetic is supported, `[FE\_INVALID](../numeric/fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is raised and the result value is unspecified.

 The result of this conversion may have greater range and precision than its target type indicates (see `[FLT\_EVAL\_METHOD](../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")`).


If control over `[FE\_INEXACT](../numeric/fenv/fe_exceptions "c/numeric/fenv/FE exceptions")` is needed in floating-to-integer conversions, `[rint](../numeric/math/rint "c/numeric/math/rint")` and `[nearbyint](../numeric/math/nearbyint "c/numeric/math/nearbyint")` may be used.



```
double d = 10; // d = 10.00
float f = 20000001; // f = 20000000.00 (FE_INEXACT)
float x = 1+(long long)FLT_MAX; // undefined behavior
```
 ####  Real floating point conversions

 A value of any real floating type can be implicitly converted to any other real floating type.


* If the value can be represented by the target type exactly, it is unchanged
* if the value can be represented, but cannot be represented exactly, the result is the nearest higher or the nearest lower value (in other words, rounding direction is implementation-defined), although if IEEE arithmetic is supported, rounding is to nearest
* if the value cannot be represented, the behavior is undefined

 The result of this conversion may have greater range and precision than its target type indicates (see `[FLT\_EVAL\_METHOD](../types/limits/flt_eval_method "c/types/limits/FLT EVAL METHOD")`).



```
double d = 0.1; // d = 0.1000000000000000055511151231257827021181583404541015625
float f = d;    // f = 0.100000001490116119384765625
float x = 2*(double)FLT_MAX; // undefined
```
 

|  |  |
| --- | --- |
|  Complex type conversions A value of any complex type can be implicitly converted to any other complex type. The real part and the imaginary part individually follow the conversion rules for the real floating types.

```
double complex d = 0.1 + 0.1*I;
float complex f = d; // f is (0.100000001490116119384765625, 0.100000001490116119384765625)
```
  Imaginary type conversions A value of any imaginary type can be implicitly converted to any other imaginary type. The imaginary part follows the conversion rules for the real floating types.

```
double imaginary d = 0.1*_Imaginary_I;
float imaginary f = d; // f is 0.100000001490116119384765625*I
```
  Real-complex conversions A value of any real floating type can be implicitly converted to any complex type.* The real part of the result is determined by the conversion rules for the real floating types
* The imaginary part of the result is positive zero (or unsigned zero on non-IEEE systems)

A value of any complex type can be implicitly converted to any real floating type.* The real part is converted following the rules for the real floating types
* The imaginary part is discarded

Note: in complex-to-real conversion, a NaN in the imaginary part will not propagate to the real result.

```
double complex z = 0.5 + 3*I;
float f = z;  // the imaginary part is discarded, f is set to 0.5
z = f;        // sets z to 0.5 + 0*I
```
  Real-imaginary conversions A value of any imaginary type can be implicitly converted to any real type (integer or floating-point). The result is always a positive (or unsigned) zero, except when the target type is `_Bool` (until C23)`bool` (since C23), in which case boolean conversion rules apply.
A value of any real type can be implicitly converted to any imaginary type. The result is always a positive imaginary zero.

```
double imaginary z = 3*I;
bool b = z;  // Boolean conversion: sets b to true 
float f = z; // Real-imaginary conversion: sets f to 0.0 
z = 3.14;    // Imaginary-real conversion: sets z to 0*_Imaginary_I
```
  Complex-imaginary conversions A value of any imaginary type can be implicitly converted to any complex type.* The real part of the result is the positive zero
* The imaginary part of the result follows the conversion rules for the corresponding real types

A value of any complex type can be implicitly converted to any imaginary type.* The real part is discarded
* The imaginary part of the result follows the conversion rules for the corresponding real types


```
double imaginary z = I * (3*I); // the complex result -3.0+0i loses real part
                                // sets z to 0*_Imaginary_I
```
 | (since C99) |

 ####  Pointer conversions

 A pointer to `void` can be implicitly converted to and from any pointer to object type with the following semantics:


* If a pointer to object is converted to a pointer to void and back, its value compares equal to the original pointer.
* No other guarantees are offered

 
```
int* p = malloc(10 * sizeof(int)); // malloc returns void*
```
 A pointer to an unqualified type may be implicitly converted to the pointer to qualified version of that type (in other words, [const](const "c/language/const"), [volatile](volatile "c/language/volatile"), and [restrict](restrict "c/language/restrict") qualifiers can be added). The original pointer and the result compare equal.



```
int n;
const int* p = &n; // &n has type int*
```
 Any integer [constant expression](constant_expression "c/language/constant expression") with value `​0​` as well as integer pointer expression with value zero cast to the type `void*` can be implicitly converted to any pointer type (both pointer to object and pointer to function). The result is the null pointer value of its type, guaranteed to compare unequal to any non-null pointer value of that type. This integer or void\* expression is known as *null pointer constant* and the standard library provides one definition of this constant as the macro `[NULL](../types/null "c/types/NULL")`.



```
int* p = 0;
double* q = NULL;
```
 ###  Notes

 Although signed integer overflow in any arithmetic operator is undefined behavior, overflowing a signed integer type in an integer conversion is merely unspecified behavior.


On the other hand, although unsigned integer overflow in any arithmetic operator (and in integer conversion) is a well-defined operation and follows the rules of modulo arithmetic, overflowing an unsigned integer in a floating-to-integer conversion is undefined behavior: the values of real floating type that can be converted to unsigned integer are the values from the open interval (-1; Unnn\_MAX+1).



```
unsigned int n = -1.0; // undefined behavior
```
 Conversions between pointers and integers (except from pointer to `_Bool` (until C23)`bool` (since C23) and  (since C99)from integer constant expression with the value zero to pointer), between pointers to objects (except where either to or from is a pointer to void) and conversions between pointers to functions (except when the functions have compatible types) are never implicit and require a [cast operator](cast "c/language/cast").


There are no conversions (implicit or explicit) between pointers to functions and pointers to objects (including void\*) or integers.


###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 6.3 Conversions (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 6.3 Conversions (p: 37-41)

* C11 standard (ISO/IEC 9899:2011):
+ 6.3 Conversions (p: 50-56)

* C99 standard (ISO/IEC 9899:1999):
+ 6.3 Conversions (p: 42-48)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 3.2 Conversions

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/implicit_cast "cpp/language/implicit cast") for Implicit conversions |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/conversion>

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_DFP__`, then
	+ [`<math.h>`](../numeric/math "c/numeric/math") and [`<fenv.h>`](../numeric/fenv "c/numeric/fenv") are fully freestanding headers, and
	+ [`<stdlib.h>`](../program "c/program") 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_DFP__` are predefined, in [`<stdlib.h>`](../program "c/program"), 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>`](../types/limits#Limits_of_floating_point_types "c/types/limits") | [Limits of floating-point types](../types/limits#Limits_of_floating_point_types "c/types/limits") |
| [`<iso646.h>`](operator_alternative "c/language/operator alternative") (since C95) | [Alternative operator spellings](operator_alternative "c/language/operator alternative") |
| [`<limits.h>`](../types/limits "c/types/limits") | [Ranges of integer types](../types/limits "c/types/limits") |
| [`<stdalign.h>`](../types "c/types") (since C11) | [`alignas` and `alignof`](../types "c/types") convenience macros  |
| [`<stdarg.h>`](../variadic "c/variadic") | [Variable arguments](../variadic "c/variadic") |
| [`<stdbool.h>`](../types "c/types") (since C99) | [Macros for boolean type](../types "c/types") |
| [`<stddef.h>`](../types "c/types") | [Common macro definitions](../types "c/types") |
| [`<stdint.h>`](../types/integer "c/types/integer") (since C99) | [Fixed-width integer types](../types/integer "c/types/integer") |
| [`<stdnoreturn.h>`](_noreturn "c/language/ Noreturn") (since C11) | [`noreturn`](../types "c/types") convenience macro  |
| `<stdbit.h>` (since C23) |  Macros to work with the byte and bit representations of types  |
|  Partially freestanding standard library headers  |
| [`<string.h>`](../string/byte "c/string/byte") (since C23) | [String handling](../string/byte "c/string/byte") |
|  Conditionally fully freestanding standard library headers  |
| [`<fenv.h>`](../numeric/fenv "c/numeric/fenv") (since C23) | [Floating-point environment](../numeric/fenv "c/numeric/fenv") |
| [`<math.h>`](../numeric/math "c/numeric/math") (since C23) | [Common mathematics functions](../numeric/math "c/numeric/math") |
|  Conditionally partially freestanding standard library headers  |
| [`<stdlib.h>`](../program "c/program") (since 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/conformance>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/fabs>

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 a ? b : c 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/operator_member_access>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/inline>

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)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/analyzability>

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​` except `true` which evaluates to `1` (since C23).


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. In this context, `__has_include`, `__has_embed` and `__has_c_attribute` are treated as if they were the name of defined macros. (since C23) 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](https://open-std.org/JTC1/SC22/WG14/www/docs/dr_412.htm), `#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](https://open-std.org/JTC1/SC22/WG14/www/docs/dr_412.htm), `#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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.10.1 Conditional inclusion (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/preprocessor/conditional>

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 except that `auto` can be used for type inference (since C23). 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 [empty-initializes](initialization#Empty_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"), [`_Alignof`](_alignof "c/language/ Alignof") (since C11), or [`typeof`](typeof "c/language/typeof") (since C23), 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"), [`_Alignof`](_alignof "c/language/ Alignof") (since C11), or [`typeof`](typeof "c/language/typeof") (since C23), 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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/extern>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/remainder>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/scalar_initialization>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/variadic>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/remquo>

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 a ? b : c sizeof` `_Alignof`(since C11). |

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/operator_assignment "cpp/language/operator assignment") for Assignment operators |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/operator_assignment>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/fma>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/fdim>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/nan>

Inline assembly
===============

 Inline assembly (typically introduced by the `asm` keyword) gives the ability to embed assembly language source code within a C program.


Unlike in C++, inline assembly is treated as an extension in C. It is conditionally supported and implementation defined, meaning that it may not be present and, even when provided by the implementation, it does not have a fixed meaning.


###  Syntax

 

|  |  |  |
| --- | --- | --- |
| `asm (` string\_literal `)` `;` |  |  |

 ###  Explanation

 This kind of inline assembly syntax is accepted by the C++ standard and called *asm-declaration* in C++. The string\_literal is typically a short program written in assembly language, which is executed whenever this declaration is executed. Different C compilers have wildly varying rules for asm-declarations, and different conventions for the interaction with the surrounding C code.


asm-declaration can appear inside a block (a function body or another compound statement), and, as all other declarations, this declaration can also appear outside a block.


###  Notes

 MSVC does not support inline assembly on the ARM and x64 processors, and only support the form introduced by `__asm` on x86 processors.


When compiling in ISO C mode by GCC or Clang (e.g. with option `-std=c11`), `__asm__` must be used instead of `asm`.


###  Examples

 
Demonstrates two kinds of inline assembly syntax offered by the GCC compiler. This program will only work correctly on x86-64 platform under Linux. Note that the "standard inline assembly" is also treated as an extension in the C standard.



```
#include <stdio.h>
 
extern int func(void);
// the definition of func is written in assembly language
__asm__(".globl func\n\t"
        ".type func, @function\n\t"
        "func:\n\t"
        ".cfi_startproc\n\t"
        "movl $7, %eax\n\t"
        "ret\n\t"
        ".cfi_endproc");
 
int main(void)
{
    int n = func();
    // gcc's extended inline assembly
    __asm__ ("leal (%0,%0,4),%0"
           : "=r" (n)
           : "0" (n));
    printf("7*5 = %d\n", n);
    fflush(stdout); // flush is intentional
 
    // standard inline assembly in C++
    __asm__ ("movq $60, %rax\n\t" // the exit syscall number on Linux
             "movq $2,  %rdi\n\t" // this program returns 2
             "syscall");
}
```
 Output:



```
7*5 = 35
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ J.5.10 The asm keyword (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ J.5.10 The asm keyword (p: 422)

* C11 standard (ISO/IEC 9899:2011):
+ J.5.10 The asm keyword (p: 580)

* C99 standard (ISO/IEC 9899:1999):
+ J.5.10 The asm keyword (p: 512)

* C89/C90 standard (ISO/IEC 9899:1990):
+ G.5.10 The asm keyword

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/asm "cpp/language/asm") for `asm` declaration |

 ###  External links

 

|  |  |
| --- | --- |
| 1.  | [GCC Inline Assembly HOWTO](https://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html) |
| 2.  | [IBM XL C/C++ Inline Assembly](https://pic.dhe.ibm.com/infocenter/comphelp/v121v141/topic/com.ibm.xlcpp121.aix.doc/language_ref/asm.html) |
| 3.  | [Intel C++ Inline Assembly](https://software.intel.com/en-us/cpp-compiler-developer-guide-and-reference-inline-assembly) |
| 4.  | [Visual Studio Inline Assembler](https://learn.microsoft.com/en-us/cpp/assembler/inline/inline-assembler.aspx) |
| 5.  | [Sun Studio 12 Asm Statements](https://blogs.oracle.com/x86be/entry/gcc_style_asm_inlining_support) |
| 6.  | [Inline assembly for Itanium-based HP-UX](https://h21007.www2.hp.com/portal/site/dspp/menuitem.863c3e4cbcdc3f3515b49c108973a801?ciid=4308e2f5bde02110e2f5bde02110275d6e10RCRD) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/asm>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/abs>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/fmod>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/log2>

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](../thread "c/thread") for `thread (Concurrency support library)` |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic/atomic "cpp/atomic/atomic") for `atomic` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/atomic>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/exp2>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/expm1>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/log>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/log10>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/log1p>

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 correctly rounded from the infinitely precise result. In particular, the exact result is produced if it can be represented in the floating-point type. The only other operations which require this are the [arithmetic operators](../../language/operator_arithmetic "c/language/operator arithmetic") and the function `[fma](fma "c/numeric/math/fma")`. 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 cube 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/sqrt>

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 cube 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/hypot>

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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.12.7.5 The pow functions
+ 7.27 Type-generic math <tgmath.h>
+ F.10.4.5 The pow functions (p: 524-525)

* C17 standard (ISO/IEC 9899:2018):
+ 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)

* 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 cube 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/pow>

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 |  -  |  a 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 three (until C99) – four (since C99) 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 (but the extra bits are padding bits), and bit-fields of type `int` are always signed.


###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 6.7.2.1 Structure and union specifiers

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/bit_field>

Static assertion (since C11)
============================

 ###  Syntax

 

|  |  |  |
| --- | --- | --- |
| `_Static_assert` `(` expression `,` message `)` |  | (since C11)(deprecated in C23) |
| `static_assert` `(` expression `,` message `)` |  | (since C23) |
| `_Static_assert` `(` expression `)` |  | (since C23)(deprecated in C23) |
| `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>`](../error "c/error"). | (until C23) |
| Both of `static_assert` and `_Static_assert` have the same effects. `_Static_assert` is a deprecated spelling that is kept for compatibility.
An implementation may also define `static_assert` and/or `_Static_assert` as predefined macros, and `static_assert` is no longer provided by [`<assert.h>`](../error "c/error"). | (since C23) |

 ###  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 as part of the error message (except that characters not in [basic character set](charset "c/language/charset") are not required to be displayed) (until C23)should display message (if provided) as part of the error message (since C23).


Otherwise, if expression does not equal zero, nothing happens; no code is emitted.


###  Keywords

 [`_Static_assert`](../keyword/_static_assert "c/keyword/ Static assert"), [`static_assert`](../keyword/static_assert "c/keyword/static assert").


###  Example

  
```
#include <assert.h> // no longer needed since C23
 
int main(void)
{
    // Test if math works.
    static_assert((2 + 2) % 3 == 1, // or _Static_assert(...
                  "Whoa dude, you knew!");
 
    // This will produce an error at compile time.
    static_assert(sizeof(int) < sizeof(char),
                 "this program requires that int is less than char");
}
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 6.7.11 Static assertions (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/_Static_assert>

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`, `[intmax\_t](http://en.cppreference.com/w/c/types/integer)`, 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") |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/div>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/cbrt>

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) |
| 
```
_Decimal32  sind32( _Decimal32 arg );
```
 |  (4)  | (since C23) |
| 
```
_Decimal64  sind64( _Decimal64 arg );
```
 |  (5)  | (since C23) |
| 
```
_Decimal128 sind128( _Decimal128 arg );
```
 |  (6)  | (since C23) |
|  Defined in header `<tgmath.h>` |  |  |
| 
```
#define sin( arg )
```
 |  (7)  | (since C99) |

 
1-3) Computes the sine of `arg` (measured in radians). 
7) Type-generic macro: If the argument has type `long double`, (3) (`sinl`) is called. Otherwise, if the argument has integer type or the type `double`, (2) (`sin`) is called. Otherwise, (1) (`sinf`) is called. If the argument is complex, then the macro invokes the corresponding complex function (`[csinl](../complex/csin "c/numeric/complex/csin")`, `[csin](../complex/csin "c/numeric/complex/csin")`, `[csinf](../complex/csin "c/numeric/complex/csin")`). 

|  |  |
| --- | --- |
| The functions (4-6) are declared if and only if the implementation predefines `__STDC_IEC_60559_DFP__` (i.e. the implementation supports decimal floating-point numbers). | (since C23) |

 ###  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](https://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](../../types/limits "c/types/limits")`, `[FLT\_MIN](../../types/limits "c/types/limits")`, and `[LDBL\_MIN](../../types/limits "c/types/limits")` is returned.


###  Example

  
```
#include <errno.h>
#include <fenv.h>
#include <math.h>
#include <stdio.h>
 
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
 
int main(void)
{
    const 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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.12.4.6 The sin functions (p: TBD)
+ 7.27 Type-generic math <tgmath.h> (p: TBD)
+ F.10.1.6 The sin functions (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.12.4.6 The sin functions (p: 175)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.1.6 The sin functions (p: 378)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/sin>

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) |
| 
```
_Decimal32  cosd32( _Decimal32 arg );
```
 |  (4)  | (since C23) |
| 
```
_Decimal64  cosd64( _Decimal64 arg );
```
 |  (5)  | (since C23) |
| 
```
_Decimal128 cosd128( _Decimal128 arg );
```
 |  (6)  | (since C23) |
|  Defined in header `<tgmath.h>` |  |  |
| 
```
#define cos( arg )
```
 |  (7)  | (since C99) |

 
1-6) Computes the cosine of `arg` (measured in radians). 
7) Type-generic macro: If the argument has type `long double`, (3) (`cosl`) is called. Otherwise, if the argument has integer type or the type `double`, (2) (`cos`) is called. Otherwise, (1) (`cosf`) is called. If the argument is complex, then the macro invokes the corresponding complex function (`[ccosf](../complex/ccos "c/numeric/complex/ccos")`, `[ccos](../complex/ccos "c/numeric/complex/ccos")`, `[ccosl](../complex/ccos "c/numeric/complex/ccos")`). 

|  |  |
| --- | --- |
| The functions (4-6) are declared if and only if the implementation predefines `__STDC_IEC_60559_DFP__` (i.e. the implementation supports decimal floating-point numbers). | (since C23) |

 ###  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](https://pubs.opengroup.org/onlinepubs/9699919799/functions/cos.html).


###  Example

  
```
#include <errno.h>
#include <fenv.h>
#include <math.h>
#include <stdio.h>
 
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
 
int main(void)
{
    const 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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.12.4.5 The cos functions (p: TBD)
+ 7.25 Type-generic math <tgmath.h> (p: TBD)
+ F.10.1.5 The cos functions (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.12.4.5 The cos functions (p: 174)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.1.5 The cos functions (p: 378)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/cos>

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) |
| 
```
_Decimal32  tand32( _Decimal32 arg );
```
 |  (4)  | (since C23) |
| 
```
_Decimal64  tand64( _Decimal64 arg );
```
 |  (5)  | (since C23) |
| 
```
_Decimal128 tand128( _Decimal128 arg );
```
 |  (6)  | (since C23) |
|  Defined in header `<tgmath.h>` |  |  |
| 
```
#define tan( arg )
```
 |  (7)  | (since C99) |

 
1-6) Computes the tangent of `arg` (measured in radians). 
7) Type-generic macro: If the argument has type `long double`, (3) (`tanl`) is called. Otherwise, if the argument has integer type or the type `double`, (2) (`tan`) is called. Otherwise, (1) (`tanf`) is called. If the argument is complex, then the macro invokes the corresponding complex function (`[ctanf](../complex/ctan "c/numeric/complex/ctan")`, `[ctan](../complex/ctan "c/numeric/complex/ctan")`, `[ctanl](../complex/ctan "c/numeric/complex/ctan")`). 

|  |  |
| --- | --- |
| The functions (4-6) are declared if and only if the implementation predefines `__STDC_IEC_60559_DFP__` (i.e. the implementation supports decimal floating-point numbers). | (since C23) |

 ###  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](https://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 <errno.h>
#include <fenv.h>
#include <math.h>
#include <stdio.h>
 
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
 
int main(void)
{
    const double pi = acos(-1);
 
    // typical usage
    printf("tan(pi*1/4) = %+f\n", tan(pi * 1 / 4)); //   45 deg
    printf("tan(pi*3/4) = %+f\n", tan(pi * 3 / 4)); //  135 deg
    printf("tan(pi*5/4) = %+f\n", tan(pi * 5 / 4)); // -135 deg
    printf("tan(pi*7/4) = %+f\n", tan(pi * 7 / 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*1/4) = +1.000000
tan(pi*3/4) = -1.000000
tan(pi*5/4) = +1.000000
tan(pi*7/4) = -1.000000
tan(+0) = 0.000000
tan(-0) = -0.000000
tan(INFINITY) = -nan
    FE_INVALID raised
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.12.4.7 The tan functions (p: TBD)
+ 7.25 Type-generic math <tgmath.h> (p: TBD)
+ F.10.1.7 The tan functions (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.12.4.7 The tan functions (p: 175)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.1.7 The tan functions (p: 378)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/tan>

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) |
| 
```
_Decimal32  asind32( _Decimal32 arg );
```
 |  (4)  | (since C23) |
| 
```
_Decimal64  asind64( _Decimal64 arg );
```
 |  (5)  | (since C23) |
| 
```
_Decimal128 asind128( _Decimal128 arg );
```
 |  (6)  | (since C23) |
|  Defined in header `<tgmath.h>` |  |  |
| 
```
#define asin( arg )
```
 |  (7)  | (since C99) |

 
1-6) Computes the principal values of the arc sine of `arg`. 
7) Type-generic macro: If the argument has type `long double`, (3) (`asinl`) is called. Otherwise, if the argument has integer type or the type `double`, (2) (`asin`) is called. Otherwise, (1) (`asinf`) is called. If the argument is complex, then the macro invokes the corresponding complex function (`[casinf](../complex/casin "c/numeric/complex/casin")`, `[casin](../complex/casin "c/numeric/complex/casin")`, `[casinl](../complex/casin "c/numeric/complex/casin")`). 

|  |  |
| --- | --- |
| The functions (4-6) are declared if and only if the implementation predefines `__STDC_IEC_60559_DFP__` (i.e. the implementation supports decimal floating-point numbers). | (since C23) |

 ###  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 <errno.h>
#include <fenv.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
 
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
 
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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.12.4.2 The asin functions (p: TBD)
+ 7.25 Type-generic math <tgmath.h> (p: TBD)
+ F.10.1.2 The asin functions (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.12.4.2 The asin functions (p: 174)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.1.2 The asin functions (p: 378)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/asin>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/exp>

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) |
| 
```
_Decimal32  acosd32( _Decimal32 arg );
```
 |  (4)  | (since C23) |
| 
```
_Decimal64  acosd64( _Decimal64 arg );
```
 |  (5)  | (since C23) |
| 
```
_Decimal128 acosd128( _Decimal128 arg );
```
 |  (6)  | (since C23) |
|  Defined in header `<tgmath.h>` |  |  |
| 
```
#define acos( arg )
```
 |  (7)  | (since C99) |

 
1-6) Computes the principal value of the arc cosine of `arg`. 
7) Type-generic macro: If the argument has type `long double`, (3) (`acosl`) is called. Otherwise, if the argument has integer type or the type `double`, (2) (`acos`) is called. Otherwise, (1) (`acosf`) is called. If the argument is complex, then the macro invokes the corresponding complex function (`[cacosf](../complex/cacos "c/numeric/complex/cacos")`, `[cacos](../complex/cacos "c/numeric/complex/cacos")`, `[cacosl](../complex/cacos "c/numeric/complex/cacos")`). 

|  |  |
| --- | --- |
| The functions (4-6) are declared if and only if the implementation predefines `__STDC_IEC_60559_DFP__` (i.e. the implementation supports decimal floating-point numbers). | (since C23) |

 ###  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 <errno.h>
#include <fenv.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
 
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
 
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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.12.4.1 The acos functions (p: TBD)
+ 7.25 Type-generic math <tgmath.h> (p: TBD)
+ F.10.1.1 The acos functions (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.12.4.1 The acos functions (p: 173)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.1.1 The acos functions (p: 378)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/acos>

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) |
| 
```
_Decimal32  atan2d32( _Decimal32 y, _Decimal32 x );
```
 |  (4)  | (since C23) |
| 
```
_Decimal64  atan2d64( _Decimal64 y, _Decimal64 x );
```
 |  (5)  | (since C23) |
| 
```
_Decimal128 atan2d128( _Decimal128 y, _Decimal128 x );
```
 |  (6)  | (since C23) |
|  Defined in header `<tgmath.h>` |  |  |
| 
```
#define atan2( y, x )
```
 |  (7)  | (since C99) |

 
1-6) Computes the arc tangent of `y / x` using the signs of arguments to determine the correct quadrant. 
7) Type-generic macro: If any argument has type `long double`, (3) (`atan2l`) is called. Otherwise, if any argument has integer type or has type `double`, (2) (`atan2`) is called. Otherwise, (1) (`atan2f`) is called. 

|  |  |
| --- | --- |
| The functions (4-6) are declared if and only if the implementation predefines `__STDC_IEC_60559_DFP__` (i.e. the implementation supports decimal floating-point numbers). | (since C23) |

 ###  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] 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`](math_errhandling "c/numeric/math/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](https://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](../../types/limits "c/types/limits")`, `[FLT\_MIN](../../types/limits "c/types/limits")`, and `[LDBL\_MIN](../../types/limits "c/types/limits")` is returned.


###  Example

  
```
#include <math.h>
#include <stdio.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.12.4.4 The atan2 functions (p: TBD)
+ 7.25 Type-generic math <tgmath.h> (p: TBD)
+ F.10.1.4 The atan2 functions (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/atan2>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/fmax>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/fmin>

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) |
| 
```
_Decimal32  atand32( _Decimal32 arg );
```
 |  (4)  | (since C23) |
| 
```
_Decimal64  atand64( _Decimal64 arg );
```
 |  (5)  | (since C23) |
| 
```
_Decimal128 atand128( _Decimal128 arg );
```
 |  (6)  | (since C23) |
|  Defined in header `<tgmath.h>` |  |  |
| 
```
#define atan( arg )
```
 |  (7)  | (since C99) |

 
1-6) Computes the principal value of the arc tangent of `arg`. 
7) Type-generic macro: If the argument has type `long double`, (3) (atanl) is called. Otherwise, if the argument has integer type or the type `double`, (2) (`atan`) is called. Otherwise, (1) (`atanf`) is called. If the argument is complex, then the macro invokes the corresponding complex function (`[catanf](../complex/catan "c/numeric/complex/catan")`, `[catan](../complex/catan "c/numeric/complex/catan")`, `[catanl](../complex/catan "c/numeric/complex/catan")`). 

|  |  |
| --- | --- |
| The functions (4-6) are declared if and only if the implementation predefines `__STDC_IEC_60559_DFP__` (i.e. the implementation supports decimal floating-point numbers). | (since C23) |

 ###  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](https://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](../../types/limits "c/types/limits")`, `[FLT\_MIN](../../types/limits "c/types/limits")`, and `[LDBL\_MIN](../../types/limits "c/types/limits")` is returned.


###  Example

  
```
#include <math.h>
#include <stdio.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.12.4.3 The atan functions (p: TBD)
+ 7.25 Type-generic math <tgmath.h> (p: TBD)
+ F.10.1.3 The atan functions (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.12.4.3 The atan functions (p: 174)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.1.3 The atan functions (p: 378)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/atan>

sinpi, sinpif, sinpil, sinpid32, sinpid64, sinpid128
====================================================

 

|  Defined in header `<math.h>` |  |  |
| --- | --- | --- |
| 
```
float       sinpif( float arg );
```
 |  (1)  | (since C23) |
| 
```
double      sinpi( double arg );
```
 |  (2)  | (since C23) |
| 
```
long double sinpil( long double arg );
```
 |  (3)  | (since C23) |
| 
```
_Decimal32  sinpid32( _Decimal32 arg );
```
 |  (4)  | (since C23) |
| 
```
_Decimal64  sinpid64( _Decimal64 arg );
```
 |  (5)  | (since C23) |
| 
```
_Decimal128 sinpid128( _Decimal128 arg );
```
 |  (6)  | (since C23) |
|  Defined in header `<tgmath.h>` |  |  |
| 
```
#define sinpi( arg )
```
 |  (7)  | (since C23) |

 
1-6) Computes the sine of `π·arg` measured in radians, thus regarding `arg` as a measurement in half-revolutions. 
7) Type-generic macro: calls the correct function based on the type of `arg`. If the argument has integer type, (2) is called. 

|  |  |
| --- | --- |
| The functions (4-6) are declared if and only if the implementation predefines `__STDC_IEC_60559_DFP__` (i.e. the implementation supports decimal floating-point numbers). | (since C23) |

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  arg  |  -  |  floating-point value whose product with `π` represents an angle in radians  |

 ###  Return value

 If no errors occur, the sine of `π·arg` (sin(π×arg)) in the range [-1, +1], 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.

 ###  Example

  
```
#include <errno.h>
#include <fenv.h>
#include <math.h>
#include <stdio.h>
 
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
 
#if __STDC_VERSION__ < 202311L
// A naive implementation of a subset of sinpi family
double sinpi(double arg)
{
    return sin(arg * (double)3.1415926535897932384626433);
}
#endif
 
int main(void)
{
    const double pi = acos(-1);
 
    // typical usage
    printf("sinpi(1) = %f, sin(pi) = %f\n", sinpi(1), sin(pi));
    printf("sinpi(0.5) = %f, sin(pi/2) = %f\n", sinpi(0.5), sin(pi / 2));
    printf("sinpi(-0.75) = %f, sin(-3*pi/4) = %f\n", sinpi(-0.75), sin(-3 * pi / 4));
 
    // special values
    printf("sinpi(+0) = %f\n", sinpi(0.0));
    printf("sinpi(-0) = %f\n", sinpi(-0.0));
 
    // error handling
    feclearexcept(FE_ALL_EXCEPT);
    printf("sinpi(INFINITY) = %f\n", sinpi(INFINITY));
    if (fetestexcept(FE_INVALID))
        puts("    FE_INVALID raised");
}
```
 Possible output:



```
sinpi(1) = 0.000000, sin(pi) = 0.000000
sinpi(0.5) = 1.000000, sin(pi/2) = 1.000000
sinpi(-0.75) = -0.707107, sin(-3*pi/4) = -0.707107
sinpi(+0) = 0.000000
sinpi(-0) = -0.000000
sinpi(INFINITY) = -nan
    FE_INVALID raised
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.12.4.13 The sinpi functions (p: 247-248)
+ 7.27 Type generic math <tgmath.h> (p: 387)

 ###  See also

 

|  |  |
| --- | --- |
|  [sinsinfsinl](sin "c/numeric/math/sin")
(C99)(C99) |  computes sine (\({\small\sin{x} }\)sin(x))  (function) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/sinpi>

cospi, cospif, cospil, cospid32, cospid64, cospid128
====================================================

 

|  Defined in header `<math.h>` |  |  |
| --- | --- | --- |
| 
```
float       cospif( float arg );
```
 |  (1)  | (since C23) |
| 
```
double      cospi( double arg );
```
 |  (2)  | (since C23) |
| 
```
long double cospil( long double arg );
```
 |  (3)  | (since C23) |
| 
```
_Decimal32  cospid32( _Decimal32 arg );
```
 |  (4)  | (since C23) |
| 
```
_Decimal64  cospid64( _Decimal64 arg );
```
 |  (5)  | (since C23) |
| 
```
_Decimal128 cospid128( _Decimal128 arg );
```
 |  (6)  | (since C23) |
|  Defined in header `<tgmath.h>` |  |  |
| 
```
#define cospi( arg )
```
 |  (7)  | (since C23) |

 
1-6) Computes the cosine of `π·arg` measured in radians, thus regarding `arg` as a measurement in half-revolutions. 
7) Type-generic macro: calls the correct function based on the type of `arg`. If the argument has integer type, (2) (`cospi`) is called. 

|  |  |
| --- | --- |
| The functions (4-6) are declared if and only if the implementation predefines `__STDC_IEC_60559_DFP__` (i.e. the implementation supports decimal floating-point numbers). | (since C23) |

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  arg  |  -  |  floating-point value whose product with `π` represents an angle in radians  |

 ###  Return value

 If no errors occur, the cosine of `π·arg` (cos(π×arg)) in the range [-1, +1], 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.

 ###  Example

  
```
#include <errno.h>
#include <fenv.h>
#include <math.h>
#include <stdio.h>
 
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
 
#if __STDC_VERSION__ < 202311L
// A naive implementation of a subset of cospi family
double cospi(double arg)
{
    return cos(arg * (double)3.1415926535897932384626433);
}
#endif
 
int main(void)
{
    const double pi = acos(-1);
 
    // typical usage
    printf("cospi(1) = %f, cos(pi) = %f\n", cospi(1), cos(pi));
    printf("cospi(0.5) = %f, cos(pi/2) = %f\n", cospi(0.5), cos(pi / 2));
    printf("cospi(-0.75) = %f, cos(-3*pi/4) = %f\n", cospi(-0.75), cos(-3 * pi / 4));
 
    // special values
    printf("cospi(+0) = %f\n", cospi(0.0));
    printf("cospi(-0) = %f\n", cospi(-0.0));
 
    // error handling
    feclearexcept(FE_ALL_EXCEPT);
    printf("cospi(INFINITY) = %f\n", cospi(INFINITY));
    if (fetestexcept(FE_INVALID))
        puts("    FE_INVALID raised");
}
```
 Possible output:



```
cospi(1) = -1.000000, cos(pi) = -1.000000
cospi(0.5) = 0.000000, cos(pi/2) = 0.000000
cospi(-0.75) = -0.707107, cos(-3*pi/4) = -0.707107
cospi(+0) = 1.000000
cospi(-0) = 1.000000
cospi(INFINITY) = -nan
    FE_INVALID raised
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.12.4.12 The cospi functions (p: 247)
+ 7.27 Type generic math <tgmath.h> (p: 387)

 ###  See also

 

|  |  |
| --- | --- |
|  [coscosfcosl](cos "c/numeric/math/cos")
(C99)(C99) |  computes cosine (\({\small\cos{x} }\)cos(x))  (function) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/cospi>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/sinh>

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."](https://mathworld.wolfram.com/InverseHyperbolicSine.html) From MathWorld — A Wolfram Web Resource.  |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/asinh>

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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.12.5.1 The acosh functions (p: TBD)
+ 7.27 Type-generic math <tgmath.h> (p: TBD)
+ F.10.2.1 The acosh functions (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.12.5.1 The acosh functions (p: 175)
+ 7.25 Type-generic math <tgmath.h> (p: 272-273)
+ F.10.2.1 The acosh functions (p: 379)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/acosh>

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](https://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](../../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 <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

 * C17 standard (ISO/IEC 9899:2018):
+ 7.12.5.3 The atanh functions (p: TBD)
+ 7.25 Type-generic math <tgmath.h> (p: TBD)
+ F.10.2.3 The atanh functions (p: TBD)

* 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."](https://mathworld.wolfram.com/InverseHyperbolicTangent.html) From MathWorld — A Wolfram Web Resource.  |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/atanh>

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](http://en.cppreference.com/w/c/numeric/math/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));
 
    printf("special values:\n"
           "erfc(-Inf) = %f\n"
           "erfc(Inf) = %f\n",
           erfc(-INFINITY),
           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."](https://mathworld.wolfram.com/Erfc.html) From MathWorld — A Wolfram Web Resource.  |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/erfc>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/tanh>

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 {{enwiki}Error function|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 <math.h>
#include <stdio.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."](https://mathworld.wolfram.com/Erf.html) From MathWorld — A Wolfram Web Resource.  |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/erf>

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`](https://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));
    const 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."](https://mathworld.wolfram.com/LogGammaFunction.html) From MathWorld — A Wolfram Web Resource.  |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/lgamma>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/ceil>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/round>

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](http://en.cppreference.com/w/c/types/limits)` or if `x > 171.7`.


[POSIX requires](https://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."](https://mathworld.wolfram.com/GammaFunction.html) From MathWorld — A Wolfram Web Resource.  |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/tgamma>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/floor>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/roundeven>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/trunc>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/nearbyint>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/rint>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/ilogb>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/logb>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/nextafter>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/cosh>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/ldexp>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/frexp>

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](http://en.cppreference.com/w/c/numeric/math/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](http://en.cppreference.com/w/c/numeric/math/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](http://en.cppreference.com/w/c/numeric/math/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`.


###  Example

  
```
#include <errno.h>
#include <fenv.h>
#include <float.h>
#include <math.h>
#include <stdio.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.12.6.13 The scalbn functions (p: TBD)
+ 7.25 Type-generic math <tgmath.h> (p: TBD)
+ F.10.3.13 The scalbn functions (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.12.6.13 The scalbn functions (p: TBD)
+ 7.25 Type-generic math <tgmath.h> (p: TBD)
+ F.10.3.13 The scalbn functions (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/scalbn>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/modf>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/copysign>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/fpclassify>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/isinf>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/isnan>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/isnormal>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/isless>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/isfinite>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/signbit>

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

 * C17 standard (ISO/IEC 9899:2018):
+ 7.12.14.1 The isgreater macro (p: 189)
+ F.10.11 Comparison macros (p: 386-387)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/isgreater>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/float_t>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/FP_categories>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/math_errhandling>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/error/errno_macros>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/error/set_constraint_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) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/error/ignore_handler_s>

gets, gets\_s
=============

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
char *gets( char *str );
```
 |  (1)  | (removed in C11) |
| 
```
char *gets_s( char *str, rsize_t n );
```
 |  (2)  | (since C11) |

 
1) Reads `[stdin](std_streams "c/io/std streams")` into the character array pointed to by `str` until a newline character is found or end-of-file occurs. A null character is written immediately after the last character read into the array. The newline character is discarded but not stored in the buffer. 
2) Reads characters from `[stdin](std_streams "c/io/std streams")` until a newline is found or end-of-file occurs. Writes only at most `n-1` characters into the array pointed to by `str`, and always writes the terminating null character (unless str is a null pointer). The newline character, if found, is discarded and does not count toward the number of characters written to the buffer. 
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: * `n` is zero
* `n` is greater than `RSIZE_MAX`
* `str` is a null pointer
* endline or eof not encountered after storing `n-1` characters to the buffer.

 
In any case, `gets_s` first finishes reading and discarding the characters from `[stdin](std_streams "c/io/std streams")` until new-line character, end-of-file condition, or read error before calling the constraint handler. 
As with all bounds-checked functions, `gets_s` 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>`](../io "c/io").

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  str  |  -  |  character string to be written  |

 ###  Return value

 `str` on success, a null pointer on failure.


If the failure has been caused by end of file condition, additionally sets the *eof* indicator (see `[feof()](feof "c/io/feof")`) on `[stdin](std_streams "c/io/std streams")`. If the failure has been caused by some other error, sets the *error* indicator (see `[ferror()](ferror "c/io/ferror")`) on `[stdin](std_streams "c/io/std streams")`.


###  Notes

 The `gets()` function does not perform bounds checking, therefore this function is extremely vulnerable to buffer-overflow attacks. It cannot be used safely (unless the program runs in an environment which restricts what can appear on `stdin`). For this reason, the function has been deprecated in the third corrigendum to the C99 standard and removed altogether in the C11 standard. `[fgets()](fgets "c/io/fgets")` and `gets_s()` are the recommended replacements.


**Never use `gets()`.**


###  References

 * C11 standard (ISO/IEC 9899:2011):
+ K.3.5.4.1 The gets\_s function (p: 602-603)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.7.7 The gets function (p: 298)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.7.7 The gets function

 ###  See also

 

|  |  |
| --- | --- |
|  [scanffscanfsscanfscanf\_sfscanf\_ssscanf\_s](fscanf "c/io/fscanf")
(C11)(C11)(C11) |  reads formatted input from `[stdin](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [fgets](fgets "c/io/fgets") |  gets a character string from a file stream  (function) |
|  [fputs](fputs "c/io/fputs") |  writes a character string to a file stream  (function) |
|  [getlinegetwlinegetdelimgetwdelim](https://en.cppreference.com/w/c/experimental/dynamic/getline "c/experimental/dynamic/getline")
(dynamic memory TR) |  read from a stream into an automatically resized buffer until delimiter/end of line  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/gets "cpp/io/c/gets") for `gets` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/gets>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/islessgreater>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/INFINITY>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/isunordered>

fopen, fopen\_s
===============

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
|  | (1) |  |
| 
```
FILE *fopen( const char *filename, const char *mode );
```
 | (until C99) |
| 
```
FILE *fopen( const char *restrict filename, const char *restrict mode );
```
 | (since C99) |
| 
```
errno_t fopen_s( FILE *restrict *restrict streamptr,
                 const char *restrict filename,
                 const char *restrict mode );
```
 |  (2)  | (since C11) |

 
1) Opens a file indicated by `filename` and returns a pointer to the file stream associated with that file. `mode` is used to determine the file access mode.  
2) Same as (1), except that the pointer to the file stream is written to `streamptr` 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: * `streamptr` is a null pointer
* `filename` is a null pointer
* `mode` is a null pointer

 As with all bounds-checked functions, `fopen_s` 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>`](../io "c/io"). ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  filename  |  -  |  file name to associate the file stream to  |
|  mode  |  -  |  null-terminated character string determining [file access mode](#File_access_flags) |
|  streamptr  |  -  |  pointer to a pointer where the function stores the result (an out-parameter)  |

 ###  File access flags

 

|  File access mode string  |  Meaning  |  Explanation  |  Action if file  already exists  |  Action if file  does not exist  |
| --- | --- | --- | --- | --- |
| `"r"` |  read  |  Open a file for reading  |  read from start  |  failure to open  |
| `"w"` |  write  |  Create a file for writing  |  destroy contents  |  create new  |
| `"a"` |  append  |  Append to a file  |  write to end  |  create new  |
| `"r+"` |  read extended  |  Open a file for read/write  |  read from start  |  error  |
| `"w+"` |  write extended  |  Create a file for read/write  |  destroy contents  |  create new  |
| `"a+"` |  append extended  |  Open a file for read/write  |  write to end  |  create new  |
|  File access mode flag `"b"` can optionally be specified to open a file in binary mode. This flag has no effect on POSIX systems, but on Windows it disables special handling of `'\n'` and `'\x1A'`.  On the append file access modes, data is written to the end of the file regardless of the current position of the file position indicator.  |
|  The behavior is undefined if the mode is not one of the strings listed above. Some implementations define additional supported modes (e.g. [Windows](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfopen)).  |
|  In update mode (`'+'`), both input and output may be performed, but output cannot be followed by input without an intervening call to `[fflush](fflush "c/io/fflush")`, `[fseek](fseek "c/io/fseek")`, `[fsetpos](fsetpos "c/io/fsetpos")` or `[rewind](rewind "c/io/rewind")`, and input cannot be followed by output without an intervening call to `[fseek](fseek "c/io/fseek")`, `[fsetpos](fsetpos "c/io/fsetpos")` or `[rewind](rewind "c/io/rewind")`, unless the input operation encountered end of file. In update mode, implementations are permitted to use binary mode even when text mode is specified.  |
|  File access mode flag `"x"` can optionally be appended to `"w"` or `"w+"` specifiers. This flag forces the function to fail if the file exists, instead of overwriting it. (C11) |
|  When using `fopen_s` or `freopen_s`, file access permissions for any file created with `"w"` or `"a"` prevents other users from accessing it. File access mode flag `"u"` can optionally be prepended to any specifier that begins with `"w"` or `"a"`, to enable the default `fopen` permissions. (C11) |

 ###  Return value

 
1) If successful, returns a pointer to the new file stream. The stream is fully buffered unless `filename` refers to an interactive device. On error, returns a null pointer. [POSIX requires](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html) that `[errno](../error/errno "c/error/errno")` be set in this case. 
2) If successful, returns zero and a pointer to the new file stream is written to `*streamptr`. On error, returns a non-zero error code and writes the null pointer to `*streamptr` (unless `streamptr` is a null pointer itself). ###  Notes

 The format of `filename` is implementation-defined, and does not necessarily refer to a file (e.g. it may be the console or another device accessible though filesystem API). On platforms that support them, `filename` may include absolute or relative filesystem path.


###  Example

  
```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    const char* fname = "/tmp/unique_name.txt"; // or tmpnam(NULL);
    int is_ok = EXIT_FAILURE;
 
    FILE* fp = fopen(fname, "w+");
    if (!fp) {
        perror("File opening failed");
        return is_ok;
    }
    fputs("Hello, world!\n", fp);
    rewind(fp);
 
    int c; // note: int, not char, required to handle EOF
    while ((c = fgetc(fp)) != EOF) // standard C I/O file reading loop
        putchar(c);
 
    if (ferror(fp))
        puts("I/O error when reading");
    else if (feof(fp)) {
        puts("End of file is reached successfully");
        is_ok = EXIT_SUCCESS;
    }
 
    fclose(fp);
    remove(fname);
    return is_ok;
}
```
 Possible output:



```
Hello, world!
End of file is reached successfully
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.5.3 The fopen function (p: 223-224)
+ K.3.5.2.1 The fopen\_s function (p: 428-429)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.5.3 The fopen function (p: 305-306)
+ K.3.5.2.1 The fopen\_s function (p: 588-590)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.5.3 The fopen function (p: 271-272)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.5.3 The fopen function

 ###  See also

 

|  |  |
| --- | --- |
|  [fclose](fclose "c/io/fclose") |  closes a file  (function) |
|  [fflush](fflush "c/io/fflush") |  synchronizes an output stream with the actual file  (function) |
|  [freopenfreopen\_s](freopen "c/io/freopen")
(C11) |  open an existing stream with a different name  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fopen "cpp/io/c/fopen") for `fopen` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fopen>

printf, fprintf, sprintf, snprintf, printf\_s, fprintf\_s, sprintf\_s, snprintf\_s
==================================================================================

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
|  | (1) |  |
| 
```
int printf( const char          *format, ... );
```
 | (until C99) |
| 
```
int printf( const char *restrict format, ... );
```
 | (since C99) |
|  | (2) |  |
| 
```
int fprintf( FILE          *stream, const char          *format, ... );
```
 | (until C99) |
| 
```
int fprintf( FILE *restrict stream, const char *restrict format, ... );
```
 | (since C99) |
|  | (3) |  |
| 
```
int sprintf( char          *buffer, const char          *format, ... );
```
 | (until C99) |
| 
```
int sprintf( char *restrict buffer, const char *restrict format, ... );
```
 | (since C99) |
| 
```
int snprintf( char *restrict buffer, size_t bufsz, 
              const char *restrict format, ... );
```
 |  (4)  | (since C99) |
| 
```
int printf_s( const char *restrict format, ... );
```
 |  (5)  | (since C11) |
| 
```
int fprintf_s( FILE *restrict stream, const char *restrict format, ... );
```
 |  (6)  | (since C11) |
| 
```
int sprintf_s( char *restrict buffer, rsize_t bufsz,
               const char *restrict format, ... );
```
 |  (7)  | (since C11) |
| 
```
int snprintf_s( char *restrict buffer, rsize_t bufsz,
                const char *restrict format, ... );
```
 |  (8)  | (since C11) |

 Loads the data from the given locations, converts them to character string equivalents and writes the results to a variety of sinks/streams:



1) Writes the results to the output stream `[stdout](std_streams "c/io/std streams")`. 
2) Writes the results to the output stream `stream`. 
3) Writes the results to a character string `buffer`. The behavior is undefined if the string to be written (plus the terminating null character) exceeds the size of the array pointed to by `buffer`. 
4) Writes the results to a character string `buffer`. At most `bufsz` - 1 characters are written. The resulting character string will be terminated with a null character, unless `bufsz` is zero. If `bufsz` is zero, nothing is written and `buffer` may be a null pointer, however the return value (number of bytes that would be written not including the null terminator) is still calculated and returned. 
5-8) Same as (1-4), 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: 

* the conversion specifier `%n` is present in `format`
* any of the arguments corresponding to `%s` is a null pointer
* `stream` or `format` or `buffer` is a null pointer
* `bufsz` is zero or greater than `RSIZE_MAX`
* encoding errors occur in any of string and character conversion specifiers
* (for `sprintf_s` only), the string to be stored in `buffer` (including the trailing null) would be exceed `bufsz`

 
As with all bounds-checked functions, `printf_s` , `fprintf_s`, `sprintf_s`, and `snprintf_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 [`<stdio.h>`](../io "c/io").

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  output file stream to write to  |
|  buffer  |  -  |  pointer to a character string to write to  |
|  bufsz  |  -  |  up to bufsz - 1 characters may be written, plus the null terminator  |
|  format  |  -  |  pointer to a null-terminated byte string specifying how to interpret the data  |
|  ...  |  -  |  arguments specifying data to print. If any argument after [default argument promotions](../language/conversion#Default_argument_promotions "c/language/conversion") is not the type expected by the corresponding conversion specifier, or if there are fewer arguments than required by `format`, the behavior is undefined. If there are more arguments than required by `format`, the extraneous arguments are evaluated and ignored.  |

   
 The **format** string consists of ordinary byte characters (except `%`), which are copied unchanged into the output stream, and conversion specifications. Each conversion specification has the following format:


* introductory `%` character
* (optional) one or more flags that modify the behavior of the conversion:
+ `-`: the result of the conversion is left-justified within the field (by default it is right-justified)
+ `+`: the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative)
+ *space*: if the result of a signed conversion does not start with a sign character, or is empty, space is prepended to the result. It is ignored if `+` flag is present.
+ `#` : *alternative form* of the conversion is performed. See the table below for exact effects otherwise the behavior is undefined.
+ `0` : for integer and floating point number conversions, leading zeros are used to pad the field instead of *space* characters. For integer numbers it is ignored if the precision is explicitly specified. For other conversions using this flag results in undefined behavior. It is ignored if `-` flag is present.

* (optional) integer value or `*` that specifies minimum field width. The result is padded with *space* characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when `*` is used, the width is specified by an additional argument of type `int`, which appears before the argument to be converted and the argument supplying precision if one is supplied. If the value of the argument is negative, it results with the `-` flag specified and positive field width. (Note: This is the minimum width: The value is never truncated.)
+ (optional) `.` followed by integer number or `*`, or neither that specifies *precision* of the conversion. In the case when `*` is used, the *precision* is specified by an additional argument of type `int`, which appears before the argument to be converted, but after the argument supplying minimum field width if one is supplied. If the value of this argument is negative, it is ignored. If neither a number nor `*` is used, the precision is taken as zero. See the table below for exact effects of *precision*.
+ (optional) *length modifier* that specifies the size of the argument (in combination with the conversion format specifier, it specifies the type of the corresponding argument)
+ conversion format specifier

 The following format specifiers are available:




|  ConversionSpecifier  |  Explanation  |  ExpectedArgument Type  |
| --- | --- | --- |
| **LengthModifier****→** | `hh` (C99). | `h` |  (none)  | `l` | `ll` (C99). | `j` (C99). | `z` (C99). | `t` (C99). | `L` |
| `%` |  writes literal `%`. The full conversion specification must be `%%`.  | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A |
| `c` |  writes a **single character**. The argument is first converted to `unsigned char`. If the **l** modifier is used, the argument is first converted to a character string as if by **%ls** with a `wchar_t[2]` argument. | N/A | N/A | `int` | `wint_t` | N/A | N/A | N/A | N/A | N/A |
| `s` |  writes a **character string** The argument must be a pointer to the initial element of an array of characters. *Precision* specifies the maximum number of bytes to be written. If *Precision* is not specified, writes every byte up to and not including the first null terminator. If the **l** specifier is used, the argument must be a pointer to the initial element of an array of `wchar_t`, which is converted to char array as if by a call to `[wcrtomb](../string/multibyte/wcrtomb "c/string/multibyte/wcrtomb")` with zero-initialized conversion state. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A |
| `d` `i` |  converts a **signed integer** into decimal representation *[-]dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | `signed char` | `short` | `int` | `long` | `long long` | `[intmax\_t](http://en.cppreference.com/w/c/types/integer)` | signed `[size\_t](http://en.cppreference.com/w/c/types/size_t)`
 | `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)` | N/A |
| `o` |  converts an **unsigned integer** into octal representation *oooo*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* precision is increased if necessary, to write one leading zero. In that case if both the converted value and the precision are `​0​`, single `​0​` is written. | `unsigned char` | `unsigned short` | `unsigned int` | `unsigned long` | `unsigned long long` | `[uintmax\_t](http://en.cppreference.com/w/c/types/integer)` | `[size\_t](http://en.cppreference.com/w/c/types/size_t)` | unsigned version of `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)`
 | N/A |
| `x` `X` |  converts an **unsigned integer** into hexadecimal representation *hhhh*. For the `x` conversion letters `abcdef` are used. For the `X` conversion letters `ABCDEF` are used. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* `0x` or `0X` is prefixed to results if the converted value is nonzero. | N/A |
| `u` |  converts an **unsigned integer** into decimal representation *dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | N/A |
| `f` `F` |  converts **floating-point number** to the decimal notation in the style *[-]ddd.ddd*. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | `double` | 
`double` (C99)
 | N/A | N/A | N/A | N/A | `long double` |
| `e` `E` |  converts **floating-point number** to the decimal exponent notation. For the `e` conversion style *[-]d.ddd*`e`*±dd* is used. For the `E` conversion style *[-]d.ddd*`E`*±dd* is used. The exponent contains at least two digits, more digits are used only if necessary. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A |
| `a` `A` (C99). |  converts **floating-point number** to the hexadecimal exponent notation. For the `a` conversion style *[-]*`0x`*h.hhh*`p`*±d* is used. For the `A` conversion style *[-]*`0X`*h.hhh*`P`*±d* is used. The first hexadecimal digit is not `0` if the argument is a normalized floating point value. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the hexadecimal point character. The default precision is sufficient for exact representation of the value. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A |
| `g` `G` |  converts **floating-point number** to decimal or decimal exponent notation depending on the value and the *precision*. For the `g` conversion style conversion with style `e` or `f` will be performed. For the `G` conversion style conversion with style `E` or `F` will be performed. Let `P` equal the precision if nonzero, `6` if the precision is not specified, or `1` if the precision is `​0​`. Then, if a conversion with style `E` would have an exponent of `X`:* if *P > X ≥ −4*, the conversion is with style `f` or `F` and precision *P − 1 − X*.
* otherwise, the conversion is with style `e` or `E` and precision *P − 1*.

Unless *alternative representation* is requested the trailing zeros are removed, also the decimal point character is removed if no fractional part is left. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A |
| `n` |  returns the **number of characters written** so far by this call to the function. The result is *written* to the value pointed to by the argument. The specification may not contain any *flag*, *field width*, or *precision*.  | `signed char*` | `short*` | `int*` | `long*` | `long long*` | `[intmax\_t](http://en.cppreference.com/w/c/types/integer)\*` | signed `[size\_t](http://en.cppreference.com/w/c/types/size_t)\*`
 | `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)\*` | N/A |
| `p` |  writes an implementation defined character sequence defining a **pointer**.  | N/A | N/A | `void*` | N/A | N/A | N/A | N/A | N/A | N/A |

 The floating point conversion functions convert infinity to `inf` or `infinity`. Which one is used is implementation defined.


Not-a-number is converted to `nan` or `nan(*char\_sequence*)`. Which one is used is implementation defined.


The conversions `F`, `E`, `G`, `A` output `INF`, `INFINITY`, `NAN` instead.


Even though `%c` expects `int` argument, it is safe to pass a `char` because of the integer promotion that takes place when a variadic function is called.


The correct conversion specifications for the fixed-width character types (`[int8\_t](../types/integer "c/types/integer")`, etc) are defined in the header [`<inttypes.h>`](../types/integer "c/types/integer") (although `[PRIdMAX](../types/integer "c/types/integer")`, `[PRIuMAX](../types/integer "c/types/integer")`, etc is synonymous with `%jd`, `%ju`, etc).


The memory-writing conversion specifier `%n` is a common target of security exploits where format strings depend on user input and is not supported by the bounds-checked `printf_s` family of functions.


There is a [sequence point](../language/eval_order "c/language/eval order") after the action of each conversion specifier; this permits storing multiple `%n` results in the same variable or, as an edge case, printing a string modified by an earlier `%n` within the same call.


If a conversion specification is invalid, the behavior is undefined.


###  Return value

 
1,2) number of characters transmitted to the output stream or negative value if an output error or an encoding error (for string and character conversion specifiers) occurred 
3) number of characters written to `buffer` (not counting the terminating null character), or a negative value if an encoding error (for string and character conversion specifiers) occurred 
4) number of characters (not including the terminating null character) which would have been written to `buffer` if `bufsz` was ignored, or a negative value if an encoding error (for string and character conversion specifiers) occurred 
5,6) number of characters transmitted to the output stream or negative value if an output error, a runtime constraints violation error, or an encoding error occurred. 
7) number of characters written to `buffer`, not counting the null character (which is always written as long as `buffer` is not a null pointer and `bufsz` is not zero and not greater than `RSIZE_MAX`), or zero on runtime constraint violations, and negative value on encoding errors 
8) number of characters not including the terminating null character (which is always written as long as `buffer` is not a null pointer and `bufsz` is not zero and not greater than `RSIZE_MAX`), which would have been written to `buffer` if `bufsz` was ignored, or a negative value if a runtime constraints violation or an encoding error occurred ###  Notes

 The C standard and [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html) specify that the behavior of `sprintf` and its variants is undefined when an argument overlaps with the destination buffer. Example:



```
sprintf(dst, "%s and %s", dst, t); // <- broken: undefined behavior
```
 [POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html) that `[errno](../error/errno "c/error/errno")` is set on error. It also specifies additional conversion specifications, most notably support for argument reordering (`n$` immediately after `%` indicates `n`'th argument).


Calling `snprintf` with zero `bufsz` and null pointer for `buffer` is useful to determine the necessary buffer size to contain the output:



```
const char fmt[] = "sqrt(2) = %f";
int sz = snprintf(NULL, 0, fmt, sqrt(2));
char buf[sz + 1]; // note +1 for terminating null byte
snprintf(buf, sizeof buf, fmt, sqrt(2));
```
 `snprintf_s`, just like `snprintf`, but unlike `sprintf_s`, will truncate the output to fit in `bufsz-1`.


###  Example

  
```
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
 
int main(void)
{
    const char* s = "Hello";
    printf("Strings:\n"); // same as puts("Strings");
    printf(" padding:\n");
    printf("\t[%10s]\n", s);
    printf("\t[%-10s]\n", s);
    printf("\t[%*s]\n", 10, s);
    printf(" truncating:\n");
    printf("\t%.4s\n", s);
    printf("\t%.*s\n", 3, s);
 
    printf("Characters:\t%c %%\n", 'A');
 
    printf("Integers:\n");
    printf("\tDecimal:\t%i %d %.6i %i %.0i %+i %i\n",
                         1, 2,   3, 0,   0,  4,-4);
    printf("\tHexadecimal:\t%x %x %X %#x\n", 5, 10, 10, 6);
    printf("\tOctal:\t\t%o %#o %#o\n", 10, 10, 4);
 
    printf("Floating point:\n");
    printf("\tRounding:\t%f %.0f %.32f\n", 1.5, 1.5, 1.3);
    printf("\tPadding:\t%05.2f %.2f %5.2f\n", 1.5, 1.5, 1.5);
    printf("\tScientific:\t%E %e\n", 1.5, 1.5);
    printf("\tHexadecimal:\t%a %A\n", 1.5, 1.5);
    printf("\tSpecial values:\t0/0=%g 1/0=%g\n", 0.0/0.0, 1.0/0.0);
 
    printf("Fixed-width types:\n");
    printf("\tLargest 32-bit value is %" PRIu32 " or %#" PRIx32 "\n",
                                     UINT32_MAX,     UINT32_MAX );
}
```
 Possible output:



```
Strings:
 padding:
        [     Hello]
        [Hello     ]
        [     Hello]
 truncating:
        Hell
        Hel
Characters:        A %
Integers:
        Decimal:        1 2 000003 0  +4 -4
        Hexadecimal:        5 a A 0x6
        Octal:                12 012 04
Floating point:
        Rounding:        1.500000 2 1.30000000000000004440892098500626
        Padding:        01.50 1.50  1.50
        Scientific:        1.500000E+00 1.500000e+00
        Hexadecimal:        0x1.8p+0 0X1.8P+0
        Special values:        0/0=-nan 1/0=inf
Fixed-width types:
        Largest 32-bit value is 4294967295 or 0xffffffff
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.6.1 The fprintf function (p: 225-230)
+ 7.21.6.3 The printf function (p: 236)
+ 7.21.6.5 The snprintf function (p: 237)
+ 7.21.6.6 The sprintf function (p: 237)
+ K.3.5.3.1 The fprintf\_s function (p: 430)
+ K.3.5.3.3 The printf\_s function (p: 432)
+ K.3.5.3.5 The snprintf\_s function (p: 432-433)
+ K.3.5.3.6 The sprintf\_s function (p: 433)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.6.1 The fprintf function (p: 309-316)
+ 7.21.6.3 The printf function (p: 324)
+ 7.21.6.5 The snprintf function (p: 325)
+ 7.21.6.6 The sprintf function (p: 325-326)
+ K.3.5.3.1 The fprintf\_s function (p: 591)
+ K.3.5.3.3 The printf\_s function (p: 593-594)
+ K.3.5.3.5 The snprintf\_s function (p: 594-595)
+ K.3.5.3.6 The sprintf\_s function (p: 595-596)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.6.1 The fprintf function (p: 274-282)
+ 7.19.6.3 The printf function (p: 290)
+ 7.19.6.5 The snprintf function (p: 290-291)
+ 7.19.6.6 The sprintf function (p: 291)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.6.1 The fprintf function
+ 4.9.6.3 The printf function
+ 4.9.6.5 The sprintf function

 ###  See also

 

|  |  |
| --- | --- |
|  [wprintffwprintfswprintfwprintf\_sfwprintf\_sswprintf\_ssnwprintf\_s](fwprintf "c/io/fwprintf")
(C95)(C95)(C95)(C11)(C11)(C11)(C11) |  prints formatted wide character output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [vprintfvfprintfvsprintfvsnprintfvprintf\_svfprintf\_svsprintf\_svsnprintf\_s](vfprintf "c/io/vfprintf")
(C99)(C11)(C11)(C11)(C11) |  prints formatted output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer using variable argument list  (function) |
|  [fputs](fputs "c/io/fputs") |  writes a character string to a file stream  (function) |
|  [scanffscanfsscanfscanf\_sfscanf\_ssscanf\_s](fscanf "c/io/fscanf")
(C11)(C11)(C11) |  reads formatted input from `[stdin](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fprintf "cpp/io/c/fprintf") for `printf, fprintf, sprintf, snprintf` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fprintf>

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` 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>`](../../program "c/program").

 ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/mbstowcs>

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` 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>`](../program "c/program").

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/algorithm/qsort>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/isgreaterequal>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/islessequal>

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` 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>`](../byte "c/string/byte"). ###  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 accommodate 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strcpy>

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` 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>`](../program "c/program").

 ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/getenv>

size\_t
=======

 

|  Defined in header `<stddef.h>` |  |  |
| --- | --- | --- |
|  Defined in header `<stdio.h>` |  |  |
|  Defined in header `<stdlib.h>` |  |  |
|  Defined in header `<string.h>` |  |  |
|  Defined in header `<time.h>` |  |  |
|  Defined in header `<uchar.h>` |  | (since C11) |
|  Defined in header `<wchar.h>` |  | (since C95) |
| 
```
typedef /*implementation-defined*/ size_t;
```
 |  |  |

 `size_t` is the unsigned integer type of the result of [`sizeof`](../language/sizeof "c/language/sizeof") , [`_Alignof`](../language/_alignof "c/language/ Alignof") (since C11) and `[offsetof](offsetof "c/types/offsetof")`, depending on the [data model](../language/arithmetic_types#Data_models "c/language/arithmetic types").




|  |  |
| --- | --- |
| The bit width of `size_t` is not less than 16. | (since C99) |

 ###  Notes

 `size_t` can store the maximum size of a theoretically possible object of any type (including array).


`size_t` is commonly used for array indexing and loop counting. Programs that use other types, such as `unsigned int`, for array indexing may fail on, e.g. 64-bit systems when the index exceeds `[UINT\_MAX](limits "c/types/limits")` or if it relies on 32-bit modular arithmetic.


###  Example

  
```
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
 
int main(void)
{
    const size_t N = 100;
    int numbers[N];
    for (size_t ndx = 0; ndx < N; ++ndx)
        numbers[ndx] = ndx;
    printf("SIZE_MAX = %zu\n", SIZE_MAX);
    size_t size = sizeof numbers;
    printf("size = %zu\n", size);
}
```
 Possible output:



```
SIZE_MAX = 18446744073709551615
size = 400
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.19 Common definitions <stddef.h> (p: 211)
+ 7.20.3 Limits of other integer types (p: 215)

* C11 standard (ISO/IEC 9899:2011):
+ 7.19 Common definitions <stddef.h> (p: 288)
+ 7.20.3 Limits of other integer types (p: 293)

* C99 standard (ISO/IEC 9899:1999):
+ 7.17 Common definitions <stddef.h> (p: 253)
+ 7.18.3 Limits of other integer types (p: 258)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.1.6 Common definitions <stddef.h>

 ###  See also

 

|  |  |
| --- | --- |
|  [ptrdiff\_t](ptrdiff_t "c/types/ptrdiff t") |  signed integer type returned when subtracting two pointers  (typedef) |
|  [offsetof](offsetof "c/types/offsetof") |  byte offset from the beginning of a struct type to specified member  (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/types/size_t "cpp/types/size t") for `size_t` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/types/size_t>

nullptr\_t
==========

 

|  Defined in header `<stddef.h>` |  |  |
| --- | --- | --- |
| 
```
typedef typeof(nullptr) nullptr_t;
```
 |  | (since C23) |

 `nullptr_t` is the type of the predefined null pointer constant, [`nullptr`](../language/nullptr "c/language/nullptr"). It is a distinct type that is not itself a pointer type. It can be [implicitly converted](../language/conversion "c/language/conversion") to any pointer type or `bool`, and the result is the null pointer value of that type or `false` respectively. No type other than `nullptr_t` itself can be converted or explicitly cast to `nullptr_t`.


`sizeof(nullptr_t)` and `alignof(nullptr_t)` are equal to `sizeof(void*)` and `alignof(void*)` respectively.


`nullptr_t` has only one valid value, i.e., `nullptr`. The object representation of `nullptr` is same as that of `(void*)0`. If a program produces a `nullptr_t` value with a different object representation, the behavior is undefined.


###  Example

 
Demonstrate that `nullptr_t` is a distinct type.



```
#include <stddef.h>
#include <stdio.h>
 
#define DETECT_NULL_POINTER_CONSTANT(e) \
    _Generic(e,                         \
        void* : puts("void*"),          \
        nullptr_t : puts("nullptr_t"),  \
        default : puts("other")       \
    )
 
int main()
{
    DETECT_NULL_POINTER_CONSTANT(((void*)0));
    DETECT_NULL_POINTER_CONSTANT(0);
    DETECT_NULL_POINTER_CONSTANT(nullptr);
}
```
 Output:



```
void*
other
nullptr_t
```
  ###  See also

 

|  |  |
| --- | --- |
|  [NULL](null "c/types/NULL") |  implementation-defined null pointer constant  (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/types/nullptr_t "cpp/types/nullptr t") for `nullptr_t` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/types/nullptr_t>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/math/HUGE_VAL>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/error/abort_handler_s>

ptrdiff\_t
==========

 

|  Defined in header `<stddef.h>` |  |  |
| --- | --- | --- |
| 
```
typedef /*implementation-defined*/ ptrdiff_t;
```
 |  |  |

 `ptrdiff_t` is the signed integer type of the result of [subtracting two pointers](../language/operator_arithmetic#Pointer_arithmetic "c/language/operator arithmetic").




|  |  |
| --- | --- |
| The bit width of `ptrdiff_t` is not less than 17. | (since C99)(until C23) |
| The bit width of `ptrdiff_t` is not less than 16. | (since C23) |

 ###  Notes

 `ptrdiff_t` is used for pointer arithmetic and array indexing, if negative values are possible. Programs that use other types, such as `int`, may fail on, e.g. 64-bit systems when the index exceeds `[INT\_MAX](limits "c/types/limits")` or if it relies on 32-bit modular arithmetic.


Only pointers to elements of the same array (including the pointer one past the end of the array) may be subtracted from each other.


If an array is so large (greater than `[PTRDIFF\_MAX](limits "c/types/limits")` elements, but equal to or less than `[SIZE\_MAX](limits "c/types/limits")` bytes), that the difference between two pointers may not be representable as `ptrdiff_t`, the result of subtracting two such pointers is undefined.


For char arrays shorter than `[PTRDIFF\_MAX](limits "c/types/limits")`, `ptrdiff_t` acts as the signed counterpart of `[size\_t](size_t "c/types/size t")`: it can store the size of the array of any type and is, on most platforms, synonymous with `intptr_t`).


###  Example

  
```
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
 
int main(void)
{
    const size_t N = 100;
    int numbers[N];
 
    printf("PTRDIFF_MAX = %ld\n", PTRDIFF_MAX);
    int *p1 = &numbers[18], *p2 = &numbers[23];
    ptrdiff_t diff = p2 - p1;
    printf("p2-p1 = %td\n", diff);
}
```
 Possible output:



```
PTRDIFF_MAX = 9223372036854775807
p2-p1 = 5
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.19 Common definitions <stddef.h> (p: 211)
+ 7.20.3 Limits of other integer types (p: 215)

* C11 standard (ISO/IEC 9899:2011):
+ 7.19 Common definitions <stddef.h> (p: 288)
+ 7.20.3 Limits of other integer types (p: 293)

* C99 standard (ISO/IEC 9899:1999):
+ 7.17 Common definitions <stddef.h> (p: 253)
+ 7.18.3 Limits of other integer types (p: 258)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.1.6 Common definitions <stddef.h>

 ###  See also

 

|  |  |
| --- | --- |
|  [size\_t](size_t "c/types/size t") |  unsigned integer type returned by the [`sizeof`](../language/sizeof "c/language/sizeof") operator  (typedef) |
|  [offsetof](offsetof "c/types/offsetof") |  byte offset from the beginning of a struct type to specified member  (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/types/ptrdiff_t "cpp/types/ptrdiff t") for `ptrdiff_t` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/types/ptrdiff_t>

NULL
====

 

|  Defined in header `<stddef.h>` |  |  |
| --- | --- | --- |
|  Defined in header `<string.h>` |  |  |
|  Defined in header `<wchar.h>` |  |  |
|  Defined in header `<time.h>` |  |  |
|  Defined in header `<locale.h>` |  |  |
|  Defined in header `<stdio.h>` |  |  |
|  Defined in header `<stdlib.h>` |  |  |
| 
```
#define NULL /*implementation-defined*/
```
 |  |  |

 The macro `NULL` is an implementation-defined null pointer constant, which may be.


* an integer [constant expression](../language/constant_expression#Integer_constant_expression "c/language/constant expression") with the value `​0​`
* an integer constant expression with the value 0 [cast to the type](../language/conversion#Pointer_conversions "c/language/conversion") `void*`

 

|  |  |
| --- | --- |
| * predefined constant [`nullptr`](../language/nullptr "c/language/nullptr")
 | (since C23) |

 A null pointer constant may be [converted](../language/conversion#Pointer_conversions "c/language/conversion") to any pointer type; such conversion results in the null pointer value of that type.


###  Possible implementation

 

|  |
| --- |
| 
```
// C++ compatible:
#define NULL 0
// C++ incompatible:
#define NULL (10*2 - 20)
#define NULL ((void*)0)
// since C23 (compatible with C++11 and later)
#define NULL nullptr
```
 |

 ###  Example

  
```
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main(void)
{    
    // any kind of pointer can be set to NULL
    int* p = NULL;
    struct S *s = NULL;
    void(*f)(int, double) = NULL;
    printf("%p %p %p\n", (void*)p, (void*)s, (void*)(long)f);
 
    // many pointer-returning functions use null pointers to indicate error
    char *ptr = malloc(0xFULL);
    if (ptr == NULL)
        printf("Out of memory");
    else
        printf("ptr = %#" PRIxPTR"\n", (uintptr_t)ptr);
    free(ptr);
}
```
 Possible output:



```
(nil) (nil) (nil)
ptr = 0xc001cafe
```
  ###  See also

 

|  |  |
| --- | --- |
|  [nullptr\_t](nullptr_t "c/types/nullptr t")
(C23) |  the type of the predefined null pointer constant [`nullptr`](../language/nullptr "c/language/nullptr")  (typedef) |
| [C++ documentation](https://en.cppreference.com/w/cpp/types/NULL "cpp/types/NULL") for `NULL` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/types/NULL>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/error/errno>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/error/assert>

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` 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>`](../wide "c/string/wide").

 ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcscpy>

max\_align\_t
=============

 

|  Defined in header `<stddef.h>` |  |  |
| --- | --- | --- |
| 
```
typedef /*implementation-defined*/ max_align_t;
```
 |  | (since C11) |

 `max_align_t` is a type whose alignment requirement is at least as strict (as large) as that of every scalar type.


###  Notes

 Pointers returned by allocation functions such as `[malloc](../memory/malloc "c/memory/malloc")` are suitably aligned for any object, which means they are aligned at least as strictly as `max_align_t`.


`max_align_t` is usually synonymous with the largest scalar type, which is `long double` on most platforms, and its alignment requirement is either 8 or 16.


###  Example

  
```
#include <stdio.h>
#include <stddef.h>
#include <stdalign.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
 
int main(void)
{
    size_t a = alignof(max_align_t);
    printf("Alignment of max_align_t is %zu (%#zx)\n", a, a);
 
    void *p = malloc(123);
    printf("The address obtained from malloc(123) is %#" PRIxPTR"\n",
            (uintptr_t)p);
    free(p);
}
```
 Possible output:



```
Alignment of max_align_t is 16 (0x10)
The address obtained from malloc(123) is 0x1fa67010
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.19 Common definitions <stddef.h> (p: 211)

* C11 standard (ISO/IEC 9899:2011):
+ 7.19 Common definitions <stddef.h> (p: 288)

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/types/max_align_t "cpp/types/max align t") for `max_align_t` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/types/max_align_t>

offsetof
========

 

|  Defined in header `<stddef.h>` |  |  |
| --- | --- | --- |
| 
```
#define offsetof(type, member) /*implementation-defined*/
```
 |  |  |

 The macro `offsetof` expands to an [integer constant expression](../language/constant_expression#Integer_constant_expression "c/language/constant expression") of type `[size\_t](size_t "c/types/size t")`, the value of which is the offset, in bytes, from the beginning of an object of specified type to its specified subobject, including padding if any.


Given an object `o` of type `type` with static storage duration, `&(o.member)` shall be an address constant expression and point to a subobject of `o`. Otherwise, the behavior is undefined.




|  |  |
| --- | --- |
| If a new type is defined in `type`, the behavior is undefined. | (since C23) |

 ###  Notes

 If `offsetof` is applied to a bit-field member, the behavior is undefined, because the address of a bit-field cannot be taken.


`member` is not restricted to a direct member. It can denote a subobject of a given member, such as an element of an array member.


Even though it is specified in C23 that defining a new type in `offsetof` is undefined behavior, such usage is only partially supported by implementations even in earlier modes: `offsetof(struct Foo { int a; }, a)` is usually supported, but `offsetof(struct Foo { int a, b; }, a)` is not because of the comma in the definition of `struct Foo`.


###  Example

  
```
#include <stdio.h>
#include <stddef.h>
 
struct S {
    char c;
    double d;
};
 
int main(void)
{
    printf("the first element is at offset %zu\n", offsetof(struct S, c));
    printf("the double is at offset %zu\n", offsetof(struct S, d));
}
```
 Possible output:



```
the first element is at offset 0
the double is at offset 8
```
  ###  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 496](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2396.htm#dr_496) |  C89  |  only structs and struct members were mentioned  |  unions and other subobjects are also supported  |

 ###  See also

 

|  |  |
| --- | --- |
|  [size\_t](size_t "c/types/size t") |  unsigned integer type returned by the [`sizeof`](../language/sizeof "c/language/sizeof") operator  (typedef) |
| [C++ documentation](https://en.cppreference.com/w/cpp/types/offsetof "cpp/types/offsetof") for `offsetof` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/types/offsetof>

C keywords: \_Bool (since C99)
==============================

 ###  Usage

 * [boolean type](../language/arithmetic_types#Boolean_type "c/language/arithmetic types"): as the declaration of the type (since C99)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Bool>

C keywords: \_Alignas (since C11)
=================================

 ###  Usage

 * [`_Alignas`](../language/_alignas "c/language/ Alignas") alignment specifier. (since C11)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Alignas>

C keywords: \_Alignof (since C11)
=================================

 ###  Usage

 * [`_Alignof` operator](../language/_alignof "c/language/ Alignof") (since C11)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Alignof>

static\_assert
==============

 

|  Defined in header `<assert.h>` |  |  |
| --- | --- | --- |
| 
```
#define static_assert _Static_assert
```
 |  | (since C11) (removed in C23) |

 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),   // compile-time error
                  "this program requires that int is less than char");
}
```
  ###  Notes

 Since C23, [`static_assert`](../language/_static_assert "c/language/ Static assert") is itself a keyword, which may also be a predefined macro, so [`<assert.h>`](../error "c/error") no longer provides it.


###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.2/3 Diagnostics <assert.h> (p: 135)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/error/static_assert>

abort
=====

 

|  Defined in header `<stdlib.h>` |  |  |
| --- | --- | --- |
| 
```
void abort(void);
```
 |  | (until C11) |
| 
```
_Noreturn void abort(void);
```
 |  | (since C11) (until C23) |
| 
```
[[noreturn]] void abort(void);
```
 |  | (since C23) |

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/abort>

exit
====

 

|  Defined in header `<stdlib.h>` |  |  |
| --- | --- | --- |
| 
```
void exit( int exit_code );
```
 |  | (until C11) |
| 
```
_Noreturn void exit( int exit_code );
```
 |  | (since C11) (until C23) |
| 
```
[[noreturn]] void exit( int exit_code );
```
 |  | (since C23) |

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/exit>

\_Exit
======

 

|  Defined in header `<stdlib.h>` |  |  |
| --- | --- | --- |
| 
```
void _Exit( int exit_code );
```
 |  | (since C99) (until C11) |
| 
```
_Noreturn void _Exit( int exit_code );
```
 |  | (since C11) (until C23) |
| 
```
[[noreturn]] void _Exit( int exit_code );
```
 |  | (since C23) |

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/_Exit>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/atexit>

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

 Constructing a complete object type such that the number of bytes in its object representation is not representable in the type `[size\_t](../types/size_t "c/types/size t")` (i.e. the result type of [`sizeof`](sizeof "c/language/sizeof") operator), including forming such a VLA type at runtime, (since C99) is undefined behavior.


###  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](bit_field "c/language/bit field") 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
 | (until C23) |

 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, a program necessitating the composite type of both types has undefined behavior.
* 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.

 The element type of the composite type is the composite type of the two element types. 

|  |  |
| --- | --- |
| * 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.
 | (until C23) |

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

 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 (*)[]); // C23: Error: conflicting types for 'f'
// 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/types>

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

 

|  |  |
| --- | --- |
| 1.  | [GCC docs: `__builtin_unreachable`](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-_005f_005fbuiltin_005funreachable) |
| 2.  | [Clang docs: `__builtin_unreachable`](https://clang.llvm.org/docs/LanguageExtensions.html#builtin-unreachable) |
| 3.  | [MSVC docs: `__assume`](https://docs.microsoft.com/en-us/cpp/intrinsics/assume) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/unreachable>

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 is guaranteed to support the registration of at least 32 functions. The exact limit is implementation-defined.


The registered functions will not be called on [normal program termination](exit "c/program/exit"). If a function need to be called in that case, `[atexit](atexit "c/program/atexit")` must be used.


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

 

|  |  |
| --- | --- |
|  [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) |
|  [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/at_quick_exit "cpp/utility/program/at quick exit") for `at_quick_exit` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/at_quick_exit>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/EXIT_status>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/raise>

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:


1. 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)) { // ...
```
2. 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) { // ...
```
3. 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)) { // ...
```
4. 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`](../language/volatile "c/language/volatile") 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 status) 
{
    printf("foo(%d) called\n", status);
    longjmp(my_jump_buffer, status + 1); // will return status+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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/setjmp>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/sig_atomic_t>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/SIG_ERR>

clock
=====

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
clock_t clock(void);
```
 |  |  |

 Returns the approximate processor time used by the process since the beginning of an implementation-defined era related to the program's execution. To convert result value to seconds, divide it by `[CLOCKS\_PER\_SEC](clocks_per_sec "c/chrono/CLOCKS PER SEC")`.


Only the difference between two values returned by different calls to `clock` is meaningful, as the beginning of the `clock` era does not have to coincide with the start of the program. `clock` time may advance faster or slower than the wall clock, depending on the execution resources given to the program by the operating system. For example, if the CPU is shared by other processes, `clock` time may advance slower than wall clock. On the other hand, if the current process is multithreaded and more than one execution core is available, `clock` time may advance faster than wall clock.


###  Parameters

 (none).


###  Return value

 Processor time used by the program so far or `([clock\_t](http://en.cppreference.com/w/c/chrono/clock_t))(-1)` if that information is unavailable or its value cannot be represented.


###  Notes

 On POSIX-compatible systems, [`clock_gettime`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html) with clock id `CLOCK_PROCESS_CPUTIME_ID` offers better resolution.


The value returned by `clock()` may wrap around on some non-conforming implementations. For example, on such an implementation, if `[clock\_t](clock_t "c/chrono/clock t")` is a signed 32-bit integer and `[CLOCKS\_PER\_SEC](clocks_per_sec "c/chrono/CLOCKS PER SEC")` is 1000000, it will wrap after about 2147 seconds (about 36 minutes).


###  Example

 
This example demonstrates the difference between `clock()` time and real time.



```
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <threads.h> // pthread.h in POSIX
 
// the function f() does some time-consuming work
int f(void* thr_data) // return void* in POSIX
{
    volatile double d = 0;
    for (int n=0; n<10000; ++n)
       for (int m=0; m<10000; ++m)
           d += d*n*m;
    return 0;
}
 
int main(void)
{
    struct timespec ts1, tw1; // both C11 and POSIX
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts1); // POSIX
    clock_gettime(CLOCK_MONOTONIC, &tw1); // POSIX; use timespec_get in C11
    clock_t t1 = clock();
 
    thrd_t thr1, thr2;  // C11; use pthread_t in POSIX
    thrd_create(&thr1, f, NULL); // C11; use pthread_create in POSIX
    thrd_create(&thr2, f, NULL);
    thrd_join(thr1, NULL); // C11; use pthread_join in POSIX
    thrd_join(thr2, NULL);
 
    struct timespec ts2, tw2;
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts2);
    clock_gettime(CLOCK_MONOTONIC, &tw2);
    clock_t t2 = clock();
 
    double dur = 1000.0*(t2-t1)/CLOCKS_PER_SEC;
    double posix_dur = 1000.0*ts2.tv_sec + 1e-6*ts2.tv_nsec
                       - (1000.0*ts1.tv_sec + 1e-6*ts1.tv_nsec);
    double posix_wall = 1000.0*tw2.tv_sec + 1e-6*tw2.tv_nsec
                       - (1000.0*tw1.tv_sec + 1e-6*tw1.tv_nsec);
 
    printf("CPU time used (per clock()): %.2f ms\n", dur);
    printf("CPU time used (per clock_gettime()): %.2f ms\n", posix_dur);
    printf("Wall time passed: %.2f ms\n", posix_wall);
}
```
 Possible output:



```
CPU time used (per clock()): 1580.00 ms
CPU time used (per clock_gettime()): 1582.76 ms
Wall time passed: 792.13 ms
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.2.1 The clock function (p: 285)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.2.1 The clock function (p: 389)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.2.1 The clock function (p: 339)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12.2.1 The clock function

 ###  See also

 

|  |  |
| --- | --- |
|  [ctimectime\_s](ctime "c/chrono/ctime")
(deprecated in C23)(C11) |  converts a `[time\_t](time_t "c/chrono/time t")` object to a textual representation  (function) |
|  [time](time "c/chrono/time") |  returns the current calendar time of the system as time since epoch  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/clock "cpp/chrono/c/clock") for `clock` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/clock>

difftime
========

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
double difftime( time_t time_end, time_t time_beg );
```
 |  |  |

 Computes difference between two calendar times as `[time\_t](time_t "c/chrono/time t")` objects (`time_end - time_beg`) in seconds. If `time_end` refers to time point before `time_beg` then the result is negative.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  time\_beg, time\_end  |  -  |  times to compare  |

 ###  Return value

 Difference between two times in seconds.


###  Notes

 On POSIX systems, `[time\_t](time_t "c/chrono/time t")` is measured in seconds, and `difftime` is equivalent to arithmetic subtraction, but C and C++ allow fractional units for `[time\_t](time_t "c/chrono/time t")`.


###  Example

 
The following program computes the number of seconds that have passed since the beginning of the month.



```
#include <stdio.h>
#include <time.h>
 
int main(void)
{
    time_t now = time(0);
 
    struct tm beg = *localtime(&now);
 
    // set beg to the beginning of the month
    beg.tm_hour = 0,
    beg.tm_min = 0,
    beg.tm_sec = 0,
    beg.tm_mday = 1;
 
    double seconds = difftime(now, mktime(&beg));
 
    printf("%.f seconds have passed since the beginning of the month.\n", seconds);
 
    return 0;
}
```
 Output:



```
1937968 seconds have passed since the beginning of the month.
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.2.2 The difftime function (p: 285)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.2.2 The difftime function (p: 390)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.2.2 The difftime function (p: 338)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 7.12.2.2 The difftime function (p: 171)

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/difftime "cpp/chrono/c/difftime") for `difftime` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/difftime>

time
====

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
time_t time( time_t *arg );
```
 |  |  |

 Returns the current calendar time encoded as a `[time\_t](time_t "c/chrono/time t")` object, and also stores it in the `[time\_t](time_t "c/chrono/time t")` object pointed to by `arg` (unless `arg` is a null pointer).


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  arg  |  -  |  pointer to a `[time\_t](time_t "c/chrono/time t")` object where the time will be stored, or a null pointer  |

 ###  Return value

 Current calendar time encoded as `[time\_t](time_t "c/chrono/time t")` object on success, `([time\_t](http://en.cppreference.com/w/c/chrono/time_t))(-1)` on error. If `arg` is not a null pointer, the return value is also stored in the object pointed to by `arg`.


###  Notes

 The encoding of calendar time in `[time\_t](time_t "c/chrono/time t")` is unspecified, but most systems conform to [POSIX specification](http://pubs.opengroup.org/onlinepubs/9699919799/functions/time.html) and return a value of integral type holding the number of seconds since [the Epoch](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_15). Implementations in which `[time\_t](time_t "c/chrono/time t")` is a 32-bit signed integer (many historical implementations) fail in the year [2038](http://en.wikipedia.org/wiki/Year_2038_problem).


###  Example

  
```
#include <stdio.h>
#include <time.h>
#include <stdint.h>
 
int main(void)
{
    time_t result = time(NULL);
    if(result != (time_t)(-1))
        printf("The current time is %s(%jd seconds since the Epoch)\n",
               asctime(gmtime(&result)), (intmax_t)result);
}
```
 Possible output:



```
The current time is Fri Apr 24 15:05:25 2015
(1429887925 seconds since the Epoch)
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.2.4 The time function (p: 286)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.2.4 The time function (p: 391)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.2.4 The time function (p: 341)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12.2.4 The time function

 ###  See also

 

|  |  |
| --- | --- |
|  [localtimelocaltime\_rlocaltime\_s](localtime "c/chrono/localtime")
(C23)(C11) |  converts time since epoch to calendar time expressed as local time  (function) |
|  [gmtimegmtime\_rgmtime\_s](gmtime "c/chrono/gmtime")
(C23)(C11) |  converts time since epoch to calendar time expressed as Coordinated Universal Time (UTC)  (function) |
|  [timespec\_get](timespec_get "c/chrono/timespec get")
(C11) |  returns the calendar time in seconds and nanoseconds based on a given time base  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/time "cpp/chrono/c/time") for `time` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/time>

timespec\_get
=============

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
int timespec_get( struct timespec *ts, int base );
```
 |  (1)  | (since C11) |
| 
```
#define TIME_UTC /* implementation-defined */
```
 |  (2)  | (since C11) |

 
1) Modifies the `timespec` object pointed to by `ts` to hold the current calendar time in the time base `base`. 
2) Expands to a value suitable for use as the `base` argument of `timespec_get`
 Other macro constants beginning with `TIME_` may be provided by the implementation to indicate additional time bases.


If `base` is `TIME_UTC`, then.


* `ts->tv_sec` is set to the number of seconds since an implementation defined epoch, truncated to a whole value
* `ts->tv_nsec` member is set to the integral number of nanoseconds, rounded to the resolution of the system clock

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ts  |  -  |  pointer to an object of type `struct timespec` |
|  base  |  -  | `TIME_UTC` or another nonzero integer value indicating the time base  |

 ###  Return value

 The value of `base` if successful, zero otherwise.


###  Notes

 The POSIX function [`clock_gettime(CLOCK_REALTIME, ts)`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html) may also be used to populate a `timespec` with the time since the Epoch.


###  Example

  
```
#include <stdio.h>
#include <time.h>
 
int main(void)
{
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    char buff[100];
    strftime(buff, sizeof buff, "%D %T", gmtime(&ts.tv_sec));
    printf("Current time: %s.%09ld UTC\n", buff, ts.tv_nsec);
}
```
 Possible output:



```
Current time: 02/18/15 14:34:03.048508855 UTC
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.2.5 The timespec\_get function (p: 286)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.2.5 The timespec\_get function (p: 390)

 ###  See also

 

|  |  |
| --- | --- |
|  [timespec](timespec "c/chrono/timespec")
(C11) |  time in seconds and nanoseconds  (struct) |
|  [timespec\_getres](timespec_getres "c/chrono/timespec getres")
(C23) |  returns the resolution of calendar time based on a given time base  (function) |
|  [time](time "c/chrono/time") |  returns the current calendar time of the system as time since epoch  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/timespec_get "cpp/chrono/c/timespec get") for `timespec_get` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/timespec_get>

ctime, ctime\_s
===============

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
|  | (1) |  |
| 
```
char*                ctime( const time_t* timer );
```
 | (until C23) |
| 
```
[[deprecated]] char* ctime( const time_t* timer );
```
 | (since C23) |
| 
```
errno_t ctime_s( char *buf, rsize_t bufsz, const time_t* timer );
```
 |  (2)  | (since C11) |

 
1) Converts given time since epoch to a calendar local time and then to a textual representation, as if by calling `[asctime](http://en.cppreference.com/w/c/chrono/asctime)([localtime](http://en.cppreference.com/w/c/chrono/localtime)(timer))` or `[asctime](http://en.cppreference.com/w/c/chrono/asctime)(localtime_r(timer, &(struct [tm](http://en.cppreference.com/w/c/chrono/tm)){0}))` (since C23). This function is deprecated and should not be used in new code. (since C23)
 
2) Same as (1), except that the function is equivalent to `asctime_s(buf, bufsz, localtime_s(timer, &(struct [tm](http://en.cppreference.com/w/c/chrono/tm)){0}))`, 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: 

* `buf` or `timer` is a null pointer
* `bufsz` is less than `26` or greater than `RSIZE_MAX`

 
As with all bounds-checked functions, `ctime_s` 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 [`<time.h>`](../chrono "c/chrono").

 The resulting string has the following format:



```
Www Mmm dd hh:mm:ss yyyy\n
```
 * `Www` - the day of the week (one of `Mon`, `Tue`, `Wed`, `Thu`, `Fri`, `Sat`, `Sun`).
* `Mmm` - the month (one of `Jan`, `Feb`, `Mar`, `Apr`, `May`, `Jun`, `Jul`, `Aug`, `Sep`, `Oct`, `Nov`, `Dec`).
* `dd` - the day of the month
* `hh` - hours
* `mm` - minutes
* `ss` - seconds
* `yyyy` - years

 The function does not support localization.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  timer  |  -  |  pointer to a `[time\_t](time_t "c/chrono/time t")` object specifying the time to print  |
|  buf  |  -  |  pointer to the first element of a char array of size at least `bufsz` |
|  bufsz  |  -  |  max number of bytes to output, typically the size of the buffer pointed to by `buf` |

 ###  Return value

 
1) pointer to a static null-terminated character string holding the textual representation of date and time. The string may be shared between `[asctime](asctime "c/chrono/asctime")` and `ctime`, and may be overwritten on each invocation of any of those functions. 
2) zero on success (in which case the string representation of time has been written out to the array pointed to by `buf`), or non-zero on failure (in which case, the terminating null character is always written to `buf[0]` unless `buf` is a null pointer or `bufsz` is zero or greater than `RSIZE_MAX`. ###  Notes

 `ctime` returns a pointer to static data and is not thread-safe. In addition, it modifies the static `[tm](tm "c/chrono/tm")` object which may be shared with `[gmtime](gmtime "c/chrono/gmtime")` and `[localtime](localtime "c/chrono/localtime")`. POSIX marks this function obsolete and recommends `[strftime](strftime "c/chrono/strftime")` instead. The C standard also recommends `[strftime](strftime "c/chrono/strftime")` instead of `ctime` and `ctime_s` because `strftime` is more flexible and locale-sensitive.


The behavior of `ctime` is undefined for the values of `[time\_t](time_t "c/chrono/time t")` that result in the string longer than 25 characters (e.g. year 10000).


###  Example

  
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <time.h>
#include <stdio.h>
 
int main(void)
{
    time_t result = time(NULL);
    printf("%s", ctime(&result));
 
#ifdef __STDC_LIB_EXT1__
    char str[26];
    ctime_s(str,sizeof str,&result);
    printf("%s", str);
#endif
}
```
 Possible output:



```
Tue May 26 21:51:03 2015
Tue May 26 21:51:03 2015
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.3.2 The ctime function (p: 287-288)
+ K.3.8.2.2 The ctime\_s function (p: 454)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.3.2 The ctime function (p: 393)
+ K.3.8.2.2 The ctime\_s function (p: 626)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.3.2 The ctime function (p: 342)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12.3.2 The ctime function

 ###  See also

 

|  |  |
| --- | --- |
|  [asctimeasctime\_s](asctime "c/chrono/asctime")
(deprecated in C23)(C11) |  converts a `[tm](tm "c/chrono/tm")` object to a textual representation  (function) |
|  [strftime](strftime "c/chrono/strftime") |  converts a `[tm](tm "c/chrono/tm")` object to custom textual representation  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/ctime "cpp/chrono/c/ctime") for `ctime` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/ctime>

wcsftime
========

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
size_t wcsftime( wchar_t* str, size_t count, const wchar_t* format, tm* time );
```
 |  | (since C95) |

 Converts the date and time information from a given calendar time `time` to a null-terminated wide character string `str` according to [format string](#Format_string) `format`. Up to `count` bytes are written.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  str  |  -  |  pointer to the first element of the wchar\_t array for output  |
|  count  |  -  |  maximum number of wide characters to write  |
|  format  |  -  |  pointer to a null-terminated wide character string specifying the [format of conversion](#Format_string) |

 ###  Format string

 The format string consists of zero or more conversion specifiers and ordinary characters (except `%`). All ordinary characters, including the terminating null character, are copied to the output string without modification. Each conversion specification begins with `%` character, optionally followed by `E` or `O` modifier (ignored if unsupported by the locale), followed by the character that determines the behavior of the specifier. The following format specifiers are available:




|  Conversion specifier  |  Explanation  |  Used fields  |
| --- | --- | --- |
| `%` |  writes literal `%`. The full conversion specification must be `%%`.  |  |
| `n`(C99) |  writes newline character  |  |
| `t`(C99) |  writes horizontal tab character  |  |
|  Year  |
| `Y` |  writes **year** as a decimal number, e.g. 2017  | `tm_year` |
| `EY`(C99) |  writes **year** in the alternative representation, e.g.平成23年 (year Heisei 23) instead of 2011年 (year 2011) in ja\_JP locale  | `tm_year` |
| `y` |  writes last 2 digits of **year** as a decimal number (range `[00,99]`)  | `tm_year` |
| `Oy`(C99) |  writes last 2 digits of **year** using the alternative numeric system, e.g. 十一 instead of 11 in ja\_JP locale  | `tm_year` |
| `Ey`(C99) |  writes **year** as offset from locale's alternative calendar period `%EC` (locale-dependent)  | `tm_year` |
| `C`(C99) |  writes first 2 digits of **year** as a decimal number (range `[00,99]`)  | `tm_year` |
| `EC`(C99) |  writes name of the **base year (period)** in the locale's alternative representation, e.g. 平成 (Heisei era) in ja\_JP  | `tm_year` |
| `G`(C99) |  writes **ISO 8601 week-based year**, i.e. the year that contains the specified week. In ISO 8601 weeks begin with Monday and the first week of the year must satisfy the following requirements:* Includes January 4
* Includes first Thursday of the year
 | `tm_year`, `tm_wday`, `tm_yday` |
| `g`(C99) |  writes last 2 digits of **ISO 8601 week-based year**, i.e. the year that contains the specified week (range `[00,99]`). In ISO 8601 weeks begin with Monday and the first week of the year must satisfy the following requirements:* Includes January 4
* Includes first Thursday of the year
 | `tm_year`, `tm_wday`, `tm_yday` |
|  Month  |
| `b` |  writes **abbreviated month** name, e.g. `Oct` (locale dependent)  | `tm_mon` |
| `Ob`(C23) |  writes **abbreviated month** name in the locale's alternative representation  | `tm_mon` |
| `h`(C99) |  synonym of `b` | `tm_mon` |
| `B` |  writes **full month** name, e.g. `October` (locale dependent)  | `tm_mon` |
| `OB`(C23) |  writes appropriate **full month** name in the locale's alternative representation  | `tm_mon` |
| `m` |  writes **month** as a decimal number (range `[01,12]`)  | `tm_mon` |
| `Om`(C99) |  writes **month** using the alternative numeric system, e.g. 十二 instead of 12 in ja\_JP locale  | `tm_mon` |
|  Week  |
| `U` |  writes **week of the year** as a decimal number (Sunday is the first day of the week) (range `[00,53]`)  | `tm_year`, `tm_wday`, `tm_yday` |
| `OU`(C99) |  writes **week of the year**, as by `%U`, using the alternative numeric system, e.g. 五十二 instead of 52 in ja\_JP locale  | `tm_year`, `tm_wday`, `tm_yday` |
| `W` |  writes **week of the year** as a decimal number (Monday is the first day of the week) (range `[00,53]`)  | `tm_year`, `tm_wday`, `tm_yday` |
| `OW`(C99) |  writes **week of the year**, as by `%W`, using the alternative numeric system, e.g. 五十二 instead of 52 in ja\_JP locale  | `tm_year`, `tm_wday`, `tm_yday` |
| `V`(C99) |  writes **ISO 8601 week of the year** (range `[01,53]`). In ISO 8601 weeks begin with Monday and the first week of the year must satisfy the following requirements:* Includes January 4
* Includes first Thursday of the year
 | `tm_year`, `tm_wday`, `tm_yday` |
| `OV`(C99) |  writes **week of the year**, as by `%V`, using the alternative numeric system, e.g. 五十二 instead of 52 in ja\_JP locale  | `tm_year`, `tm_wday`, `tm_yday` |
|  Day of the year/month  |
| `j` |  writes **day of the year** as a decimal number (range `[001,366]`)  | `tm_yday` |
| `d` |  writes **day of the month** as a decimal number (range `[01,31]`)  | `tm_mday` |
| `Od`(C99) |  writes zero-based **day of the month** using the alternative numeric system, e.g. 二十七 instead of 27 in ja\_JP locale Single character is preceded by a space. | `tm_mday` |
| `e`(C99) |  writes **day of the month** as a decimal number (range `[1,31]`). Single digit is preceded by a space. | `tm_mday` |
| `Oe`(C99) |  writes one-based **day of the month** using the alternative numeric system, e.g. 二十七 instead of 27 in ja\_JP locale Single character is preceded by a space. | `tm_mday` |
|  Day of the week  |
| `a` |  writes **abbreviated weekday** name, e.g. `Fri` (locale dependent)  | `tm_wday` |
| `A` |  writes **full weekday** name, e.g. `Friday` (locale dependent)  | `tm_wday` |
| `w` |  writes **weekday** as a decimal number, where Sunday is `0` (range `[0-6]`)  | `tm_wday` |
| `Ow`(C99) |  writes **weekday**, where Sunday is `0`, using the alternative numeric system, e.g. 二 instead of 2 in ja\_JP locale  | `tm_wday` |
| `u`(C99) |  writes **weekday** as a decimal number, where Monday is `1` (ISO 8601 format) (range `[1-7]`)  | `tm_wday` |
| `Ou`(C99) |  writes **weekday**, where Monday is `1`, using the alternative numeric system, e.g. 二 instead of 2 in ja\_JP locale  | `tm_wday` |
|  Hour, minute, second  |
| `H` |  writes **hour** as a decimal number, 24 hour clock (range `[00-23]`)  | `tm_hour` |
| `OH`(C99) |  writes **hour** from 24-hour clock using the alternative numeric system, e.g. 十八 instead of 18 in ja\_JP locale  | `tm_hour` |
| `I` |  writes **hour** as a decimal number, 12 hour clock (range `[01,12]`)  | `tm_hour` |
| `OI`(C99) |  writes **hour** from 12-hour clock using the alternative numeric system, e.g. 六 instead of 06 in ja\_JP locale  | `tm_hour` |
| `M` |  writes **minute** as a decimal number (range `[00,59]`)  | `tm_min` |
| `OM`(C99) |  writes **minute** using the alternative numeric system, e.g. 二十五 instead of 25 in ja\_JP locale  | `tm_min` |
| `S` |  writes **second** as a decimal number (range `[00,60]`)  | `tm_sec` |
| `OS`(C99) |  writes **second** using the alternative numeric system, e.g. 二十四 instead of 24 in ja\_JP locale  | `tm_sec` |
|  Other  |
| `c` |  writes **standard date and time string**, e.g. `Sun Oct 17 04:41:13 2010` (locale dependent)  |  all  |
| `Ec`(C99) |  writes **alternative date and time string**, e.g. using 平成23年 (year Heisei 23) instead of 2011年 (year 2011) in ja\_JP locale  |  all  |
| `x` |  writes localized **date representation** (locale dependent)  |  all  |
| `Ex`(C99) |  writes **alternative date representation**, e.g. using 平成23年 (year Heisei 23) instead of 2011年 (year 2011) in ja\_JP locale  |  all  |
| `X` |  writes localized **time representation**, e.g. 18:40:20 or 6:40:20 PM (locale dependent)  |  all  |
| `EX`(C99) |  writes **alternative time representation** (locale dependent)  |  all  |
| `D`(C99) |  equivalent to **"%m/%d/%y"** | `tm_mon`, `tm_mday`, `tm_year` |
| `F`(C99) |  equivalent to **"%Y-%m-%d"** (the ISO 8601 date format)  | `tm_mon`, `tm_mday`, `tm_year` |
| `r`(C99) |  writes localized **12-hour clock** time (locale dependent)  | `tm_hour`, `tm_min`, `tm_sec` |
| `R`(C99) |  equivalent to **"%H:%M"** | `tm_hour`, `tm_min` |
| `T`(C99) |  equivalent to **"%H:%M:%S"** (the ISO 8601 time format)  | `tm_hour`, `tm_min`, `tm_sec` |
| `p` |  writes localized **a.m. or p.m.** (locale dependent)  | `tm_hour` |
| `z`(C99) |  writes **offset from UTC** in the ISO 8601 format (e.g. `-0430`), or no characters if the time zone information is not available  | `tm_isdst` |
| `Z` |  writes locale-dependent **time zone name or abbreviation**, or no characters if the time zone information is not available  | `tm_isdst` |

 ###  Return value

 number of wide characters written into the wide character array pointed to by `str` not including the terminating `L'\0'` on success. If `count` was reached before the entire string could be stored, `​0​` is returned and the contents are undefined.


###  Example

  
```
#include <stdio.h>
#include <time.h>
#include <wchar.h>
#include <locale.h>
 
int main(void)
{
    wchar_t buff[40];
    struct tm my_time = { .tm_year=112, // = year 2012
                          .tm_mon=9,    // = 10th month
                          .tm_mday=9,   // = 9th day
                          .tm_hour=8,   // = 8 hours
                          .tm_min=10,   // = 10 minutes
                          .tm_sec=20    // = 20 secs
    };
 
    if (wcsftime(buff, sizeof buff, L"%A %c", &my_time)) {
        printf("%ls\n", buff);
    } else {
        puts("wcsftime failed");
    }
 
    setlocale(LC_ALL, "ja_JP.utf8");
 
    if (wcsftime(buff, sizeof buff, L"%A %c", &my_time)) {
        printf("%ls\n", buff);
    } else {
        puts("wcsftime failed");
    }
}
```
 Output:



```
Sunday Sun Oct  9 08:10:20 2012
日曜日 2012年10月09日 08時10分20秒
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.29.5.1 The wcsftime function (p: 230-231)

* C11 standard (ISO/IEC 9899:2011):
+ 7.29.5.1 The wcsftime function (p: 439-440)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.5.1 The wcsftime function (p: 385-386)

 ###  See also

 

|  |  |
| --- | --- |
|  [strftime](strftime "c/chrono/strftime") |  converts a `[tm](tm "c/chrono/tm")` object to custom textual representation  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/wcsftime "cpp/chrono/c/wcsftime") for `wcsftime` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/wcsftime>

gmtime, gmtime\_r, gmtime\_s
============================

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
struct tm *gmtime  ( const time_t *timer );
```
 |  (1)  |  |
| 
```
struct tm *gmtime_r( const time_t *timer, struct tm *buf );
```
 |  (2)  | (since C23) |
| 
```
struct tm *gmtime_s( const time_t *restrict timer, struct tm *restrict buf );
```
 |  (3)  | (since C11) |

 
1) Converts given time since epoch (a `[time\_t](time_t "c/chrono/time t")` value pointed to by `timer`) into calendar time, expressed in Coordinated Universal Time (UTC) in the [`struct tm`](tm "c/chrono/tm") format. The result is stored in static storage and a pointer to that static storage is returned. 
2) Same as (1), except that the function uses user-provided storage `buf` for the result. 
3) Same as (1), except that the function uses user-provided storage `buf` for the result 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: 

* `timer` or `buf` is a null pointer

 
As with all bounds-checked functions, `gmtime_s` 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 [`<time.h>`](../chrono "c/chrono").

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  timer  |  -  |  pointer to a `[time\_t](time_t "c/chrono/time t")` object to convert  |
|  buf  |  -  |  pointer to a `struct [tm](http://en.cppreference.com/w/c/chrono/tm)` object to store the result  |

 ###  Return value

 
1) pointer to a static internal `[tm](tm "c/chrono/tm")` object on success, or null pointer otherwise. The structure may be shared between `gmtime`, `[localtime](localtime "c/chrono/localtime")`, and `[ctime](ctime "c/chrono/ctime")` and may be overwritten on each invocation. 
2-3) copy of the `buf` pointer, or null pointer on error (which may be a runtime constraint violation or a failure to convert the specified time to UTC) ###  Notes

 `gmtime` may not be thread-safe.


POSIX requires that `gmtime` and `gmtime_r` set `[errno](../error/errno "c/error/errno")` to `[EOVERFLOW](../error/errno_macros "c/error/errno macros")` if they fail because the argument is too large.


The implementation of `gmtime_s` in [Microsoft CRT](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/gmtime-s-gmtime32-s-gmtime64-s?view=vs-2019) is incompatible with the C standard since it has reversed parameter order.


###  Example

  
```
#define __STDC_WANT_LIB_EXT1__ 1
#define _XOPEN_SOURCE // for putenv
#include <time.h>
#include <stdio.h>
#include <stdlib.h>   // for putenv
 
int main(void)
{
    time_t t = time(NULL);
    printf("UTC:       %s", asctime(gmtime(&t)));
    printf("local:     %s", asctime(localtime(&t)));
    // POSIX-specific
    putenv("TZ=Asia/Singapore");
    printf("Singapore: %s", asctime(localtime(&t)));
 
#ifdef __STDC_LIB_EXT1__
    struct tm buf;
    char str[26];
    asctime_s(str,sizeof str,gmtime_s(&t, &buf));
    printf("UTC:       %s", str);
    asctime_s(str,sizeof str,localtime_s(&t, &buf));
    printf("local:     %s", str);
#endif
}
```
 Possible output:



```
UTC:       Fri Sep 15 14:22:05 2017
local:     Fri Sep 15 14:22:05 2017
Singapore: Fri Sep 15 22:22:05 2017
UTC:       Fri Sep 15 14:22:05 2017
local:     Fri Sep 15 14:22:05 2017
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.3.3 The gmtime function (p: 288)
+ K.3.8.2.3 The gmtime\_s function (p: 454-455)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.3.3 The gmtime function (p: 393-394)
+ K.3.8.2.3 The gmtime\_s function (p: 626-627)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.3.3 The gmtime function (p: 343)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12.3.3 The gmtime function

 ###  See also

 

|  |  |
| --- | --- |
|  [localtimelocaltime\_rlocaltime\_s](localtime "c/chrono/localtime")
(C23)(C11) |  converts time since epoch to calendar time expressed as local time  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/gmtime "cpp/chrono/c/gmtime") for `gmtime` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/gmtime>

localtime, localtime\_r, localtime\_s
=====================================

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
struct tm *localtime  ( const time_t *timer );
```
 |  (1)  |  |
| 
```
struct tm *localtime_r( const time_t *timer, struct tm *buf );
```
 |  (2)  | (since C23) |
| 
```
struct tm *localtime_s( const time_t *restrict timer, struct tm *restrict buf );
```
 |  (3)  | (since C11) |

 
1) Converts given time since epoch (a `[time\_t](time_t "c/chrono/time t")` value pointed to by `timer`) into calendar time, expressed in local time, in the [`struct tm`](tm "c/chrono/tm") format. The result is stored in static storage and a pointer to that static storage is returned. 
2) Same as (1), except that the function uses user-provided storage `buf` for the result. 
3) Same as (1), except that the function uses user-provided storage `buf` for the result 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: 

* `timer` or `buf` is a null pointer

 
As with all bounds-checked functions, `localtime_s` 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 [`<time.h>`](../chrono "c/chrono").

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  timer  |  -  |  pointer to a `[time\_t](time_t "c/chrono/time t")` object to convert  |
|  buf  |  -  |  pointer to a `struct [tm](http://en.cppreference.com/w/c/chrono/tm)` object to store the result  |

 ###  Return value

 
1) pointer to a static internal `[tm](tm "c/chrono/tm")` object on success, or null pointer otherwise. The structure may be shared between `[gmtime](gmtime "c/chrono/gmtime")`, `localtime`, and `[ctime](ctime "c/chrono/ctime")` and may be overwritten on each invocation. 
2-3) copy of the `buf` pointer, or null pointer on error (which may be a runtime constraint violation or a failure to convert the specified time to local calendar time) ###  Notes

 The function `localtime` may not be thread-safe.


POSIX requires that `localtime` and `localtime_r` set `[errno](../error/errno "c/error/errno")` to `[EOVERFLOW](../error/errno_macros "c/error/errno macros")` if it fails because the argument is too large.


[POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/localtime.html) that the timezone information is determined by `localtime` and `localtime_r` as if by calling [`tzset`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/tzset.html), which reads the environment variable `TZ`.


The implementation of `localtime_s` in [Microsoft CRT](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/localtime-s-localtime32-s-localtime64-s?view=vs-2019) is incompatible with the C standard since it has reversed parameter order and returns `errno_t`.


###  Example

  
```
#define __STDC_WANT_LIB_EXT1__ 1
#define _XOPEN_SOURCE // for putenv
#include <time.h>
#include <stdio.h>
#include <stdlib.h>   // for putenv
 
int main(void)
{
    time_t t = time(NULL);
    printf("UTC:       %s", asctime(gmtime(&t)));
    printf("local:     %s", asctime(localtime(&t)));
    // POSIX-specific
    putenv("TZ=Asia/Singapore");
    printf("Singapore: %s", asctime(localtime(&t)));
 
#ifdef __STDC_LIB_EXT1__
    struct tm buf;
    char str[26];
    asctime_s(str,sizeof str,gmtime_s(&t, &buf));
    printf("UTC:       %s", str);
    asctime_s(str,sizeof str,localtime_s(&t, &buf));
    printf("local:     %s", str);
#endif
}
```
 Possible output:



```
UTC:       Fri Sep 15 14:22:05 2017
local:     Fri Sep 15 14:22:05 2017
Singapore: Fri Sep 15 22:22:05 2017
UTC:       Fri Sep 15 14:22:05 2017
local:     Fri Sep 15 14:22:05 2017
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.3.4 The localtime function (p: 288)
+ K.3.8.2.4 The localtime\_s function (p: 455)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.3.4 The localtime function (p: 394)
+ K.3.8.2.4 The localtime\_s function (p: 627)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.3.4 The localtime function (p: 343)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12.3.4 The localtime function

 ###  See also

 

|  |  |
| --- | --- |
|  [gmtimegmtime\_rgmtime\_s](gmtime "c/chrono/gmtime")
(C23)(C11) |  converts time since epoch to calendar time expressed as Coordinated Universal Time (UTC)  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/localtime "cpp/chrono/c/localtime") for `localtime` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/localtime>

mktime
======

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
time_t mktime( struct tm *arg );
```
 |  |  |

 Renormalizes local calendar time expressed as a `[struct tm](tm "c/chrono/tm")` object and also converts it to time since epoch as a `[time\_t](time_t "c/chrono/time t")` object. `arg->tm_wday` and `arg->tm_yday` are ignored. The values in `arg` are not checked for being out of range.


A negative value of `arg->tm_isdst` causes `mktime` to attempt to determine if Daylight Saving Time was in effect in the specified time.


If the conversion to `time_t` is successful, the `arg` object is modified. All fields of `arg` are updated to fit their proper ranges. `arg->tm_wday` and `arg->tm_yday` are recalculated using information available in other fields.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  arg  |  -  |  pointer to a `[tm](tm "c/chrono/tm")` object specifying local calendar time to convert  |

 ###  Return value

 time since epoch as a `[time\_t](time_t "c/chrono/time t")` object on success, or `-1` if `arg` cannot be represented as a `[time\_t](time_t "c/chrono/time t")` object (POSIX also requires `EOVERFLOW` to be stored in `[errno](../error/errno "c/error/errno")` in this case).


###  Notes

 If the `struct [tm](http://en.cppreference.com/w/c/chrono/tm)` object was obtained from POSIX [`strptime`](http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html) or equivalent function, the value of `tm_isdst` is indeterminate, and needs to be set explicitly before calling `mktime`.


###  Example

  
```
#define _POSIX_C_SOURCE 200112L // for setenv on gcc
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
 
int main(void)
{
    setenv("TZ", "/usr/share/zoneinfo/America/New_York", 1); // POSIX-specific
 
    struct tm tm = *localtime(&(time_t){time(NULL)});
    printf("Today is           %s", asctime(&tm));
    printf("(DST is %s)\n", tm.tm_isdst ? "in effect" : "not in effect");
    tm.tm_mon -= 100;  // tm_mon is now outside its normal range
    mktime(&tm);       // tm_isdst is not set to -1; today's DST status is used
    printf("100 months ago was %s", asctime(&tm));
    printf("(DST was %s)\n", tm.tm_isdst ? "in effect" : "not in effect");
}
```
 Possible output:



```
Today is           Fri Apr 22 11:53:36 2016
(DST is in effect)
100 months ago was Sat Dec 22 10:53:36 2007
(DST was not in effect)
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.2.3 The mktime function (p: 285-286)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.2.3 The mktime function (p: 390-391)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.2.3 The mktime function (p: 340-341)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12.2.3 The mktime function

 ###  See also

 

|  |  |
| --- | --- |
|  [localtimelocaltime\_rlocaltime\_s](localtime "c/chrono/localtime")
(C23)(C11) |  converts time since epoch to calendar time expressed as local time  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/mktime "cpp/chrono/c/mktime") for `mktime` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/mktime>

strftime
========

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
size_t strftime( char*          str, size_t count,
                 const char*          format, const struct tm*          tp );
```
 |  | (until C99) |
| 
```
size_t strftime( char* restrict str, size_t count,
                 const char* restrict format, const struct tm* restrict tp );
```
 |  | (since C99) |

 Converts the date and time information from a given calendar time `tp` to a null-terminated multibyte character string `str` according to [format string](#Format_string) `format`. Up to `count` bytes are written.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  str  |  -  |  pointer to the first element of the char array for output  |
|  count  |  -  |  maximum number of bytes to write  |
|  format  |  -  |  pointer to a null-terminated multibyte character string specifying the [format of conversion](#Format_string) |
|  tp  |  -  |  pointer to a `struct [tm](http://en.cppreference.com/w/c/chrono/tm)` object specifying the time to format  |

 ###  Format string

 The format string consists of zero or more conversion specifiers and ordinary characters (except `%`). All ordinary characters, including the terminating null character, are copied to the output string without modification. Each conversion specification begins with `%` character, optionally followed by `E` or `O` modifier (ignored if unsupported by the locale), followed by the character that determines the behavior of the specifier. The following format specifiers are available:




|  Conversion specifier  |  Explanation  |  Used fields  |
| --- | --- | --- |
| `%` |  writes literal `%`. The full conversion specification must be `%%`.  |  |
| `n`(C99) |  writes newline character  |  |
| `t`(C99) |  writes horizontal tab character  |  |
|  Year  |
| `Y` |  writes **year** as a decimal number, e.g. 2017  | `tm_year` |
| `EY`(C99) |  writes **year** in the alternative representation, e.g.平成23年 (year Heisei 23) instead of 2011年 (year 2011) in ja\_JP locale  | `tm_year` |
| `y` |  writes last 2 digits of **year** as a decimal number (range `[00,99]`)  | `tm_year` |
| `Oy`(C99) |  writes last 2 digits of **year** using the alternative numeric system, e.g. 十一 instead of 11 in ja\_JP locale  | `tm_year` |
| `Ey`(C99) |  writes **year** as offset from locale's alternative calendar period `%EC` (locale-dependent)  | `tm_year` |
| `C`(C99) |  writes first 2 digits of **year** as a decimal number (range `[00,99]`)  | `tm_year` |
| `EC`(C99) |  writes name of the **base year (period)** in the locale's alternative representation, e.g. 平成 (Heisei era) in ja\_JP  | `tm_year` |
| `G`(C99) |  writes **ISO 8601 week-based year**, i.e. the year that contains the specified week. In ISO 8601 weeks begin with Monday and the first week of the year must satisfy the following requirements:* Includes January 4
* Includes first Thursday of the year
 | `tm_year`, `tm_wday`, `tm_yday` |
| `g`(C99) |  writes last 2 digits of **ISO 8601 week-based year**, i.e. the year that contains the specified week (range `[00,99]`). In ISO 8601 weeks begin with Monday and the first week of the year must satisfy the following requirements:* Includes January 4
* Includes first Thursday of the year
 | `tm_year`, `tm_wday`, `tm_yday` |
|  Month  |
| `b` |  writes **abbreviated month** name, e.g. `Oct` (locale dependent)  | `tm_mon` |
| `Ob`(C23) |  writes **abbreviated month** name in the locale's alternative representation  | `tm_mon` |
| `h`(C99) |  synonym of `b` | `tm_mon` |
| `B` |  writes **full month** name, e.g. `October` (locale dependent)  | `tm_mon` |
| `OB`(C23) |  writes appropriate **full month** name in the locale's alternative representation  | `tm_mon` |
| `m` |  writes **month** as a decimal number (range `[01,12]`)  | `tm_mon` |
| `Om`(C99) |  writes **month** using the alternative numeric system, e.g. 十二 instead of 12 in ja\_JP locale  | `tm_mon` |
|  Week  |
| `U` |  writes **week of the year** as a decimal number (Sunday is the first day of the week) (range `[00,53]`)  | `tm_year`, `tm_wday`, `tm_yday` |
| `OU`(C99) |  writes **week of the year**, as by `%U`, using the alternative numeric system, e.g. 五十二 instead of 52 in ja\_JP locale  | `tm_year`, `tm_wday`, `tm_yday` |
| `W` |  writes **week of the year** as a decimal number (Monday is the first day of the week) (range `[00,53]`)  | `tm_year`, `tm_wday`, `tm_yday` |
| `OW`(C99) |  writes **week of the year**, as by `%W`, using the alternative numeric system, e.g. 五十二 instead of 52 in ja\_JP locale  | `tm_year`, `tm_wday`, `tm_yday` |
| `V`(C99) |  writes **ISO 8601 week of the year** (range `[01,53]`). In ISO 8601 weeks begin with Monday and the first week of the year must satisfy the following requirements:* Includes January 4
* Includes first Thursday of the year
 | `tm_year`, `tm_wday`, `tm_yday` |
| `OV`(C99) |  writes **week of the year**, as by `%V`, using the alternative numeric system, e.g. 五十二 instead of 52 in ja\_JP locale  | `tm_year`, `tm_wday`, `tm_yday` |
|  Day of the year/month  |
| `j` |  writes **day of the year** as a decimal number (range `[001,366]`)  | `tm_yday` |
| `d` |  writes **day of the month** as a decimal number (range `[01,31]`)  | `tm_mday` |
| `Od`(C99) |  writes zero-based **day of the month** using the alternative numeric system, e.g. 二十七 instead of 27 in ja\_JP locale Single character is preceded by a space. | `tm_mday` |
| `e`(C99) |  writes **day of the month** as a decimal number (range `[1,31]`). Single digit is preceded by a space. | `tm_mday` |
| `Oe`(C99) |  writes one-based **day of the month** using the alternative numeric system, e.g. 二十七 instead of 27 in ja\_JP locale Single character is preceded by a space. | `tm_mday` |
|  Day of the week  |
| `a` |  writes **abbreviated weekday** name, e.g. `Fri` (locale dependent)  | `tm_wday` |
| `A` |  writes **full weekday** name, e.g. `Friday` (locale dependent)  | `tm_wday` |
| `w` |  writes **weekday** as a decimal number, where Sunday is `0` (range `[0-6]`)  | `tm_wday` |
| `Ow`(C99) |  writes **weekday**, where Sunday is `0`, using the alternative numeric system, e.g. 二 instead of 2 in ja\_JP locale  | `tm_wday` |
| `u`(C99) |  writes **weekday** as a decimal number, where Monday is `1` (ISO 8601 format) (range `[1-7]`)  | `tm_wday` |
| `Ou`(C99) |  writes **weekday**, where Monday is `1`, using the alternative numeric system, e.g. 二 instead of 2 in ja\_JP locale  | `tm_wday` |
|  Hour, minute, second  |
| `H` |  writes **hour** as a decimal number, 24 hour clock (range `[00-23]`)  | `tm_hour` |
| `OH`(C99) |  writes **hour** from 24-hour clock using the alternative numeric system, e.g. 十八 instead of 18 in ja\_JP locale  | `tm_hour` |
| `I` |  writes **hour** as a decimal number, 12 hour clock (range `[01,12]`)  | `tm_hour` |
| `OI`(C99) |  writes **hour** from 12-hour clock using the alternative numeric system, e.g. 六 instead of 06 in ja\_JP locale  | `tm_hour` |
| `M` |  writes **minute** as a decimal number (range `[00,59]`)  | `tm_min` |
| `OM`(C99) |  writes **minute** using the alternative numeric system, e.g. 二十五 instead of 25 in ja\_JP locale  | `tm_min` |
| `S` |  writes **second** as a decimal number (range `[00,60]`)  | `tm_sec` |
| `OS`(C99) |  writes **second** using the alternative numeric system, e.g. 二十四 instead of 24 in ja\_JP locale  | `tm_sec` |
|  Other  |
| `c` |  writes **standard date and time string**, e.g. `Sun Oct 17 04:41:13 2010` (locale dependent)  |  all  |
| `Ec`(C99) |  writes **alternative date and time string**, e.g. using 平成23年 (year Heisei 23) instead of 2011年 (year 2011) in ja\_JP locale  |  all  |
| `x` |  writes localized **date representation** (locale dependent)  |  all  |
| `Ex`(C99) |  writes **alternative date representation**, e.g. using 平成23年 (year Heisei 23) instead of 2011年 (year 2011) in ja\_JP locale  |  all  |
| `X` |  writes localized **time representation**, e.g. 18:40:20 or 6:40:20 PM (locale dependent)  |  all  |
| `EX`(C99) |  writes **alternative time representation** (locale dependent)  |  all  |
| `D`(C99) |  equivalent to **"%m/%d/%y"** | `tm_mon`, `tm_mday`, `tm_year` |
| `F`(C99) |  equivalent to **"%Y-%m-%d"** (the ISO 8601 date format)  | `tm_mon`, `tm_mday`, `tm_year` |
| `r`(C99) |  writes localized **12-hour clock** time (locale dependent)  | `tm_hour`, `tm_min`, `tm_sec` |
| `R`(C99) |  equivalent to **"%H:%M"** | `tm_hour`, `tm_min` |
| `T`(C99) |  equivalent to **"%H:%M:%S"** (the ISO 8601 time format)  | `tm_hour`, `tm_min`, `tm_sec` |
| `p` |  writes localized **a.m. or p.m.** (locale dependent)  | `tm_hour` |
| `z`(C99) |  writes **offset from UTC** in the ISO 8601 format (e.g. `-0430`), or no characters if the time zone information is not available  | `tm_isdst` |
| `Z` |  writes locale-dependent **time zone name or abbreviation**, or no characters if the time zone information is not available  | `tm_isdst` |

 ###  Return value

 The number of bytes written into the character array pointed to by `str` not including the terminating `'\0'` on success. If `count` was reached before the entire string could be stored, `​0​` is returned and the contents are indeterminate.


###  Example

  
```
#include <locale.h>
#include <stdio.h>
#include <time.h>
 
int main(void)
{
    char buff[70];
    struct tm my_time = { .tm_year=112, // = year 2012
                          .tm_mon=9,    // = 10th month
                          .tm_mday=9,   // = 9th day
                          .tm_hour=8,   // = 8 hours
                          .tm_min=10,   // = 10 minutes
                          .tm_sec=20    // = 20 secs
    };
 
    if (strftime(buff, sizeof buff, "%A %c", &my_time))
        puts(buff);
    else
        puts("strftime failed");
 
    setlocale(LC_TIME, "el_GR.utf8");
 
    if (strftime(buff, sizeof buff, "%A %c", &my_time))
        puts(buff);
    else
        puts("strftime failed");
}
```
 Possible output:



```
Sunday Sun Oct  9 08:10:20 2012
Κυριακή Κυρ 09 Οκτ 2012 08:10:20 πμ EST
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.27.3.5 The strftime function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.27.3.5 The strftime function (p: 288-291)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.3.5 The strftime function (p: 394-397)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.3.5 The strftime function (p: 343-347)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12.3.5 The strftime function

 ###  See also

 

|  |  |
| --- | --- |
|  [asctimeasctime\_s](asctime "c/chrono/asctime")
(deprecated in C23)(C11) |  converts a `[tm](tm "c/chrono/tm")` object to a textual representation  (function) |
|  [ctimectime\_s](ctime "c/chrono/ctime")
(deprecated in C23)(C11) |  converts a `[time\_t](time_t "c/chrono/time t")` object to a textual representation  (function) |
|  [wcsftime](wcsftime "c/chrono/wcsftime")
(C95) |  converts a `[tm](tm "c/chrono/tm")` object to custom wide string textual representation  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/strftime "cpp/chrono/c/strftime") for `strftime` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/strftime>

CLOCKS\_PER\_SEC
================

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
#define CLOCKS_PER_SEC /*implementation defined*/
```
 |  |  |

 Expands to an expression (not necessarily a compile-time constant) of type `[clock\_t](clock_t "c/chrono/clock t")` equal to the number of clock ticks per second, as returned by `[clock()](clock "c/chrono/clock")`.


###  Notes

 POSIX defines `CLOCKS_PER_SEC` as one million, regardless of the actual precision of `[clock](clock "c/chrono/clock")`.


Until standardized as `CLOCKS_PER_SEC` in C89, this macro was sometimes known by its IEEE std 1003.1-1988 name `CLK_TCK`: that name was not included in C89 and was removed from POSIX itself in 1996 over ambiguity with `_SC_CLK_TCK`, which gives number of clocks per second for the function [`times()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/times.html)).


###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.1/2 Components of time (p: 284)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.1/2 Components of time (p: 388)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.1/2 Components of time (p: 338)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12.1 Components of time

 ###  See also

 

|  |  |
| --- | --- |
|  [clock](clock "c/chrono/clock") |  returns raw processor clock time since the program is started  (function) |
|  [clock\_t](clock_t "c/chrono/clock t") |  processor time since era type  (typedef) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/CLOCKS_PER_SEC "cpp/chrono/c/CLOCKS PER SEC") for `CLOCKS_PER_SEC` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/CLOCKS_PER_SEC>

tm
==

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
struct tm;
```
 |  |  |

 Structure holding a calendar date and time broken down into its components.


###  Member objects

 

|  |  |
| --- | --- |
| int tm\_sec |  seconds after the minute – [0, 61] (until C99)[0, 60] (since C99)[[note 1]](#cite_note-leapsecond-1)  (public member object) |
| int tm\_min |  minutes after the hour – [0, 59]  (public member object) |
| int tm\_hour |  hours since midnight – [0, 23]  (public member object) |
| int tm\_mday |  day of the month – [1, 31]  (public member object) |
| int tm\_mon |  months since January – [0, 11]  (public member object) |
| int tm\_year |  years since 1900  (public member object) |
| int tm\_wday |  days since Sunday – [0, 6]  (public member object) |
| int tm\_yday |  days since January 1 – [0, 365]  (public member object) |
| int tm\_isdst |  Daylight Saving Time flag. The value is positive if DST is in effect, zero if not and negative if no information is available  (public member object) |

 ######  Notes

 The Standard mandates only the presence of the aforementioned members in either order. The implementations usually add more data-members to this structure.


1. Range allows for a positive leap second. Two leap seconds in the same minute are not allowed (the C89 range 0..61 was a defect)

 ###  Example

  
```
#include <stdio.h>
#include <time.h>
 
int main(void)
{
    struct tm start = {.tm_year=2022-1900, .tm_mday=1};
    mktime(&start);
    printf("%s", asctime(&start));
}
```
 Output:



```
Sat Jan  1 00:00:00 2022
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.1/3 Components of time (p: 284)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.1/3 Components of time (p: 388)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.1/3 Components of time (p: 338)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12.1 Components of time

 ###  See also

 

|  |  |
| --- | --- |
|  [localtimelocaltime\_rlocaltime\_s](localtime "c/chrono/localtime")
(C23)(C11) |  converts time since epoch to calendar time expressed as local time  (function) |
|  [gmtimegmtime\_rgmtime\_s](gmtime "c/chrono/gmtime")
(C23)(C11) |  converts time since epoch to calendar time expressed as Coordinated Universal Time (UTC)  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/tm "cpp/chrono/c/tm") for `tm` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/tm>

time\_t
=======

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
typedef /* unspecified */ time_t;
```
 |  |  |

 Real arithmetic type capable of representing times.


Although not defined by the C standard, this is almost always an integral value holding the number of seconds (not counting leap seconds) since 00:00, Jan 1 1970 UTC, corresponding to  [POSIX time](https://en.wikipedia.org/wiki/Unix_time "enwiki:Unix time").


###  Notes

 The standard uses the term *calendar time* when referring to a value of type `time_t`.


###  Example

 
Show the start of the epoch.



```
#include <stdio.h>
#include <time.h>
#include <stdint.h>
 
int main(void)
{
    time_t epoch = 0;
    printf("%jd seconds since the epoch began\n", (intmax_t)epoch);
    printf("%s", asctime(gmtime(&epoch)));
}
```
 Possible output:



```
0 seconds since the epoch began
Thu Jan  1 00:00:00 1970
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.1/3 Components of time (p: 284)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.1/3 Components of time (p: 388)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.1/3 Components of time (p: 338)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12.1 Components of time

 ###  See also

 

|  |  |
| --- | --- |
|  [time](time "c/chrono/time") |  returns the current calendar time of the system as time since epoch  (function) |
|  [localtimelocaltime\_rlocaltime\_s](localtime "c/chrono/localtime")
(C23)(C11) |  converts time since epoch to calendar time expressed as local time  (function) |
|  [gmtimegmtime\_rgmtime\_s](gmtime "c/chrono/gmtime")
(C23)(C11) |  converts time since epoch to calendar time expressed as Coordinated Universal Time (UTC)  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/time_t "cpp/chrono/c/time t") for `time_t` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/time_t>

clock\_t
========

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
typedef /* unspecified */ clock_t;
```
 |  |  |

 Arithmetic (until C11)Real (since C11) type capable of representing the processor time used by a process. It has implementation-defined range and precision.


###  Example

  
```
#include <stdio.h>
#include <time.h>
#include <math.h>
 
volatile double sink;
int main (void)
{
  clock_t start = clock();
 
  for(size_t i=0; i<3141592; ++i)
      sink+=sin(i);
 
  clock_t end = clock();
  double cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
 
  printf("for loop took %f seconds to execute \n", cpu_time_used);
}
```
 Possible output:



```
for loop took 0.271828 seconds to execute
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.1/3 Components of time (p: 284)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.1/3 Components of time (p: 388)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.1/3 Components of time (p: 338)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12.1 Components of time

 ###  See also

 

|  |  |
| --- | --- |
|  [clock](clock "c/chrono/clock") |  returns raw processor clock time since the program is started  (function) |
|  [CLOCKS\_PER\_SEC](clocks_per_sec "c/chrono/CLOCKS PER SEC") |  number of processor clock ticks per second  (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/clock_t "cpp/chrono/c/clock t") for `clock_t` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/clock_t>

timespec
========

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
struct timespec;
```
 |  | (since C11) |

 Structure holding an interval broken down into seconds and nanoseconds.


###  Member objects

 

|  |  |
| --- | --- |
| `[time\_t](time_t "c/chrono/time t")` `tv_sec` |  whole seconds (valid values are >= 0)  |
| `/* see below */` `tv_nsec` |  nanoseconds (valid values are [0, 999999999])  |

 

|  |  |
| --- | --- |
| The type of `tv_nsec` is `long`. | (until C23) |
| The type of `tv_nsec` is an implementation-defined signed integer type that can represent integers in [0, 999999999]. | (since C23) |

 The declaration order of `tv_sec` and `tv_nsec` is unspecified. Implementation may add other members to `struct timespec`.


###  Notes

 The type of `tv_nsec` is `long long` on some platforms, which is conforming only since C23.


###  Example

  
```
#include <stdio.h>
#include <time.h>
#include <stdint.h>
 
int main(void)
{
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    char buff[100];
    strftime(buff, sizeof buff, "%D %T", gmtime(&ts.tv_sec));
    printf("Current time: %s.%09ld UTC\n", buff, ts.tv_nsec);
    printf("Raw timespec.time_t: %jd\n", (intmax_t)ts.tv_sec);
    printf("Raw timespec.tv_nsec: %09ld\n", ts.tv_nsec);
}
```
 Possible output:



```
Current time: 11/24/21 03:10:50.408191283 UTC
Raw timespec.time_t: 1637723450
Raw timespec.tv_nsec: 408191283
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.1/3 Components of time (p: 284)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.1/3 Components of time (p: 388)

 ###  See also

 

|  |  |
| --- | --- |
|  [timespec\_get](timespec_get "c/chrono/timespec get")
(C11) |  returns the calendar time in seconds and nanoseconds based on a given time base  (function) |
|  [tm](tm "c/chrono/tm") |  calendar time type  (struct) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/timespec "cpp/chrono/c/timespec") for `timespec` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/timespec>

FILE
====

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
typedef /* unspecified */ FILE;
```
 |  |  |

 Each `FILE` object denotes a C stream.


C standard does not specify whether `FILE` is a complete object type. While it may be possible to copy a valid `FILE`, using a pointer to such a copy as an argument for an I/O function invokes unspecified behavior. In other words, `FILE` may be semantically non-copyable.


I/O streams can be used for both unformatted and formatted input and output. Furthermore, the functions that handle input and output can also be locale-sensitive, such that wide/multibyte conversions are performed as necessary.


###  Stream state

 Besides the system-specific information necessary to access the device (*e.g.,* a POSIX file descriptor), each `FILE` object directly or indirectly holds the following:


1. (C95) Character width: unset, narrow, or wide.
2. (C95) Parse state for conversions between multibyte and wide characters (an object of type `[mbstate\_t](../string/multibyte/mbstate_t "c/string/multibyte/mbstate t")`)
3. Buffering state: unbuffered, line-buffered, fully buffered.
4. The buffer, which may be replaced by an external, user-provided buffer.
5. I/O mode: input, output, or update (both input and output).
6. Binary/text mode indicator.
7. End-of-file status indicator.
8. Error status indicator.
9. File position indicator, accessible as an object of type `[fpos\_t](fpos_t "c/io/fpos t")`, which, for wide streams, includes parse state.
10. (C11) Reentrant lock used to prevent data races when multiple threads read, write, position, or query the position of a stream.

 ####  Narrow and wide orientation

 A newly opened stream has no orientation. The first call to `fwide` or to any I/O function establishes the orientation: a wide I/O function makes the stream wide-oriented; a narrow I/O function makes the stream narrow-oriented. Once set, the orientation can be changed with only `[freopen](freopen "c/io/freopen")`. Narrow I/O functions cannot be called on a wide-oriented stream; wide I/O functions cannot be called on a narrow-oriented stream. Wide I/O functions convert between wide and multibyte characters as if by calling `[mbrtowc](../string/multibyte/mbrtowc "c/string/multibyte/mbrtowc")` or `[wcrtomb](../string/multibyte/wcrtomb "c/string/multibyte/wcrtomb")` with the conversion state as described by the stream. Unlike the multibyte character strings that are valid in a program, multibyte character sequences in the file may contain embedded nulls and do not have to begin or end in the initial shift state.


The conversion state of a stream with wide orientation is established by the C locale that is installed at the time the stream's orientation is set.


####  Binary and text modes

 A *text stream* is an ordered sequence of characters that can be composed into lines; a line can be decomposed into zero or more characters plus a terminating `'\n'` (“newline”) character. Whether the last line requires a terminating `'\n'` is implementation-defined. Furthermore, characters may have to be added, altered, or deleted on input and output to conform to the conventions for representing text in the OS (in particular, C streams on Windows OS convert `'\n'` to `'\r\n'` on output, and convert `'\r\n'` to `'\n'` on input).


Data read in from a text stream is guaranteed to compare equal to the data that were earlier written out to that stream only if each of the following is true:


* The data consist of only printing characters and/or the control characters `'\t'` and `'\n'` (in particular, on Windows OS, the character `'\0x1A'` terminates input).
* No `'\n'` character is immediately preceded by space characters (such space characters may disappear when such output is later read as input).
* The last character is `'\n'`.

 A *binary stream* is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream always equal the data that were earlier written out to that stream, except that an implementation is allowed to append an indeterminate number of null characters to the end of the stream. A wide binary stream doesn't need to end in the initial shift state.


###  Notes

 POSIX explicitly requires that the `LC_CTYPE` facet of the currently installed C locale be stored within the `FILE` object the moment the stream's orientation becomes wide; POSIX requires that this `LC_CTYPE` facet be used for all future I/O on this stream until the orientation is changed, regardless of any subsequent call to `[setlocale](../locale/setlocale "c/locale/setlocale")`.


It is intended that each line of text be composed of data that are essentially human-readable. POSIX implementations do not distinguish between text and binary streams (there is no special mapping for `'\n'` or any other characters).


###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21 Input/output <stdio.h> (p: 217-247)
+ 7.29 Extended multibyte and wide character utilities <wchar.h> (p: 295-325)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21 Input/output <stdio.h> (p: 296-339)
+ 7.29 Extended multibyte and wide character utilities <wchar.h> (p: 402-446)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19 Input/output <stdio.h> (p: 262-305)
+ 7.24 Extended multibyte and wide character utilities <wchar.h> (p: 348-392)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9 INPUT/OUTPUT <stdio.h>

 ###  See also

 

|  |  |
| --- | --- |
|  [stdinstdoutstderr](std_streams "c/io/std streams") |  expression of type `FILE*` associated with the input streamexpression of type `FILE*` associated with the output streamexpression of type `FILE*` associated with the error output stream  (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/FILE "cpp/io/c/FILE") for `FILE` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/FILE>

fpos\_t
=======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
typedef /* implementation-defined */ fpos_t;
```
 |  |  |

 `fpos_t` is a non-array complete object type, can be used to store (by `[fgetpos](fgetpos "c/io/fgetpos")`) and restore (by `[fsetpos](fsetpos "c/io/fsetpos")`) the position and multibyte parser state (if any) for a C stream.




|  |  |
| --- | --- |
| The multibyte parser state of a wide-oriented C stream is represented by a `[mbstate\_t](../string/multibyte/mbstate_t "c/string/multibyte/mbstate t")` object, whose value is stored as part of the value of a `fpos_t` object by `[fgetpos](fgetpos "c/io/fgetpos")`. | (since C95) |

 ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.1 Introduction (p: 217-218)
+ 7.21.2 Streams (p: 218-219)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.1 Introduction (p: 296-298)
+ 7.21.2 Streams (p: 298-299)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.1 Introduction (p: 262-264)
+ 7.19.2 Streams (p: 264-265)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.1 Introduction
+ 4.9.2 Streams

 ###  See also

 

|  |  |
| --- | --- |
|  [fgetpos](fgetpos "c/io/fgetpos") |  gets the file position indicator  (function) |
|  [fsetpos](fsetpos "c/io/fsetpos") |  moves the file position indicator to a specific location in a file  (function) |
|  [mbstate\_t](../string/multibyte/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/io/c/fpos_t "cpp/io/c/fpos t") for `fpos_t` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fpos_t>

stdin, stdout, stderr
=====================

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
#define stdin  /* implementation-defined */
```
 |  (1)  |  |
| 
```
#define stdout /* implementation-defined */
```
 |  (2)  |  |
| 
```
#define stderr /* implementation-defined */
```
 |  (3)  |  |

 Three text streams are predefined. These streams are implicitly opened and unoriented at program startup.



1) Associated with the *standard input* stream, used for reading conventional input. At program startup, the stream is fully buffered if and only if the stream can be determined to not refer to an interactive device. 
2) Associated with the *standard output* stream, used for writing conventional output. At program startup, the stream is fully buffered if and only if the stream can be determined to not refer to an interactive device. 
3) Associated with the *standard error* stream, used for writing diagnostic output. At program startup, the stream is not fully buffered. What constitutes an interactive device is implementation-defined.


These macros are expanded to expressions of type `[FILE](http://en.cppreference.com/w/c/io/FILE)\*`.


###  Notes

 Although not mandated by POSIX, the UNIX convention is that `stdin` and `stdout` are line-buffered if associated with a terminal and `stderr` is unbuffered.


These macros may be expanded to modifiable lvalues. If any of these `[FILE](http://en.cppreference.com/w/c/io/FILE)\*` lvalue is modified, subsequent operations on the corresponding stream result in unspecified or undefined behavior.


###  Example

 
This example shows a function equivalent to `[printf](fprintf "c/io/fprintf")`.



```
#include <stdarg.h>
#include <stdio.h>
 
int my_printf(const char * restrict fmt, ...)
{
    va_list vl;
    va_start(vl, fmt);
    int ret = vfprintf(stdout, fmt, vl);
    va_end(vl);
    return ret;
}
 
int main(void)
{
    my_printf("Rounding:\t%f %.0f %.32f\n", 1.5, 1.5, 1.3);
    my_printf("Padding:\t%05.2f %.2f %5.2f\n", 1.5, 1.5, 1.5);
    my_printf("Scientific:\t%E %e\n", 1.5, 1.5);
    my_printf("Hexadecimal:\t%a %A\n", 1.5, 1.5);
}
```
 Possible output:



```
Rounding:       1.500000 2 1.30000000000000004440892098500626
Padding:        01.50 1.50  1.50
Scientific:     1.500000E+00 1.500000e+00
Hexadecimal:    0x1.8p+0 0X1.8P+0
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.1 Introduction (p: 217-218)
+ 7.21.2 Streams (p: 217-219)
+ 7.21.2 Files (p: 219-221)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.1 Introduction (p: 296-298)
+ 7.21.2 Streams (p: 298-299)
+ 7.21.2 Files (p: 300-302)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.1 Introduction (p: 262-264)
+ 7.19.2 Streams (p: 264-265)
+ 7.19.2 Files (p: 266-268)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 7.9.1 Introduction
+ 7.9.2 Streams
+ 7.9.3 Files

 ###  See also

 

|  |  |
| --- | --- |
|  [FILE](file "c/io/FILE") |  object type, capable of holding all information needed to control a C I/O stream  (typedef) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/std_streams "cpp/io/c/std streams") for `stdin, stdout, stderr` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/std_streams>

freopen, freopen\_s
===================

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
|  | (1) |  |
| 
```
FILE *freopen( const char *filename, const char *mode,
               FILE *stream );
```
 | (until C99) |
| 
```
FILE *freopen( const char *restrict filename, const char *restrict mode, 
               FILE *restrict stream );
```
 | (since C99) |
| 
```
errno_t freopen_s( FILE *restrict *restrict newstreamptr,
                   const char *restrict filename, const char *restrict mode,
                   FILE *restrict stream );
```
 |  (2)  | (since C11) |

 
1) First, attempts to close the file associated with `stream`, ignoring any errors. Then, if `filename` is not null, attempts to open the file specified by `filename` using `mode` as if by `[fopen](fopen "c/io/fopen")`, and associates that file with the file stream pointed to by `stream`. If `filename` is a null pointer, then the function attempts to reopen the file that is already associated with `stream` (it is implementation defined which mode changes are allowed in this case). 
2) Same as (1), except that `mode` is treated as in `fopen_s` and that the pointer to the file stream is written to `newstreamptr` 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: 

* `newstreamptr` is a null pointer
* `stream` is a null pointer
* `mode` is a null pointer

 
As with all bounds-checked functions, `freopen_s` 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>`](../io "c/io").

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  filename  |  -  |  file name to associate the file stream to  |
|  mode  |  -  |  null-terminated character string determining new [file access mode](#File_access_flags) |
|  stream  |  -  |  the file stream to modify  |
|  newstreamptr  |  -  |  pointer to a pointer where the function stores the result (an out-parameter)  |

 ###  File access flags

 

|  File access mode string  |  Meaning  |  Explanation  |  Action if file  already exists  |  Action if file  does not exist  |
| --- | --- | --- | --- | --- |
| `"r"` |  read  |  Open a file for reading  |  read from start  |  failure to open  |
| `"w"` |  write  |  Create a file for writing  |  destroy contents  |  create new  |
| `"a"` |  append  |  Append to a file  |  write to end  |  create new  |
| `"r+"` |  read extended  |  Open a file for read/write  |  read from start  |  error  |
| `"w+"` |  write extended  |  Create a file for read/write  |  destroy contents  |  create new  |
| `"a+"` |  append extended  |  Open a file for read/write  |  write to end  |  create new  |
|  File access mode flag `"b"` can optionally be specified to open a file in binary mode. This flag has no effect on POSIX systems, but on Windows it disables special handling of `'\n'` and `'\x1A'`.  On the append file access modes, data is written to the end of the file regardless of the current position of the file position indicator.  |
|  The behavior is undefined if the mode is not one of the strings listed above. Some implementations define additional supported modes (e.g. [Windows](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfopen)).  |
|  In update mode (`'+'`), both input and output may be performed, but output cannot be followed by input without an intervening call to `[fflush](fflush "c/io/fflush")`, `[fseek](fseek "c/io/fseek")`, `[fsetpos](fsetpos "c/io/fsetpos")` or `[rewind](rewind "c/io/rewind")`, and input cannot be followed by output without an intervening call to `[fseek](fseek "c/io/fseek")`, `[fsetpos](fsetpos "c/io/fsetpos")` or `[rewind](rewind "c/io/rewind")`, unless the input operation encountered end of file. In update mode, implementations are permitted to use binary mode even when text mode is specified.  |
|  File access mode flag `"x"` can optionally be appended to `"w"` or `"w+"` specifiers. This flag forces the function to fail if the file exists, instead of overwriting it. (C11) |
|  When using `fopen_s` or `freopen_s`, file access permissions for any file created with `"w"` or `"a"` prevents other users from accessing it. File access mode flag `"u"` can optionally be prepended to any specifier that begins with `"w"` or `"a"`, to enable the default `[fopen](fopen "c/io/fopen")` permissions. (C11) |

 ###  Return value

 
1) A copy of the value of `stream` on success, null pointer on failure. 
2) zero on success (and a copy of the value of `stream` is written to `*newstreamptr`, non-zero on error (and null pointer is written to `*newstreamptr` unless `newstreamptr` is itself a null pointer). ###  Notes

 `freopen` is the only way to change the narrow/wide orientation of a stream once it has been established by an I/O operation or by `fwide`.


Microsoft CRT version of `freopen` does not support any mode changes when `filename` is a null pointer and treats this as an error (see [documentation](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/freopen-wfreopen)). A possible workaround is the non-standard function [`_setmode()`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setmode).


###  Example

 
The following code redirects `stdout` to a file.



```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    puts("stdout is printed to console");
    if (freopen("redir.txt", "w", stdout) == NULL)
    {
       perror("freopen() failed");
       return EXIT_FAILURE;
    }
    puts("stdout is redirected to a file"); // this is written to redir.txt
    fclose(stdout);
    return EXIT_SUCCESS;
}
```
 Output:



```
stdout is printed to console
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.5.4 The freopen function (p: 224-225)
+ K.3.5.2.2 The freopen\_s function (p: 429-430)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.5.4 The freopen function (p: 307)
+ K.3.5.2.2 The freopen\_s function (p: 590)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.5.4 The freopen function (p: 272-273)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.5.4 The freopen function

 ###  See also

 

|  |  |
| --- | --- |
|  [fopenfopen\_s](fopen "c/io/fopen")
(C11) |  opens a file  (function) |
|  [fclose](fclose "c/io/fclose") |  closes a file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/freopen "cpp/io/c/freopen") for `freopen` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/freopen>

fwide
=====

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
int fwide( FILE *stream, int mode );
```
 |  | (since C95) |

 If `mode > 0`, attempts to make `stream` wide-oriented. If `mode < 0`, attempts to make `stream` byte-oriented. If `mode==0`, only queries the current orientation of the stream.


If the orientation of the stream has already been decided (by executing output or by an earlier call to fwide), this function does nothing.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  pointer to the C I/O stream to modify or query  |
|  mode  |  -  |  integer value greater than zero to set the stream wide, less than zero to set the stream narrow, or zero to query only  |

 ###  Return value

 An integer greater than zero if the stream is wide-oriented after this call, less than zero if the stream is byte-oriented after this call, and zero if the stream has no orientation.


###  Example

 
The following code sets and resets the stream orientation.



```
#include <wchar.h>
#include <stdio.h>
#include <stdlib.h>
 
void show_orientation(int n)
{
    n < 0 ? puts("\tnarrow orientation"):
    n > 0 ? puts("\twide orientation"):
            puts("\tno orientation");
}
 
void try_read(FILE* fp)
{
    int c = fgetc(fp);
    if(c == EOF)
        puts("\tnarrow character read failed");
    else
        printf("\tnarrow character read '%c'\n", c);
 
    wint_t wc = fgetwc(fp);
    if(wc == WEOF)
        puts("\twide character read failed");
    else
        printf("\twide character read '%lc'\n", wc);
}
 
int main(void)
{
    enum fwide_orientation { narrow = -1, query, wide };
 
    FILE* fp = fopen("main.cpp", "r");
    if (!fp)
    {
        perror("fopen() failed");
        return EXIT_FAILURE;
    }
 
    puts("1) A newly opened stream has no orientation.");
    show_orientation(fwide(fp, query));
 
    puts("2) Establish byte orientation.");
    show_orientation(fwide(fp, narrow));
    try_read(fp);
 
    puts("3) Only freopen() can reset stream orientation.");
    if (freopen("main.cpp", "r", fp) == NULL)
    {
       perror("freopen() failed");
       return EXIT_FAILURE;
    }
 
    puts("4) A reopened stream has no orientation.");
    show_orientation(fwide(fp, query));
 
    puts("5) Establish wide orientation.");
    show_orientation(fwide(fp, wide));
    try_read(fp);
 
    fclose(fp);
}
```
 Possible output:



```
1) A newly opened stream has no orientation.
        no orientation
2) Establish byte orientation.
        narrow orientation
        narrow character read '#'
        wide character read failed
3) Only freopen() can reset stream orientation.
4) A reopened stream has no orientation.
        no orientation
5) Establish wide orientation.
        wide orientation
        narrow character read failed
        wide character read '#'
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.29.3.5 The fwide function (p: 309)

* C11 standard (ISO/IEC 9899:2011):
+ 7.29.3.5 The fwide function (p: 423)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.3.5 The fwide function (p: 369)

 ###  See also

 

|  |  |
| --- | --- |
|  [fopenfopen\_s](fopen "c/io/fopen")
(C11) |  opens a file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fwide "cpp/io/c/fwide") for `fwide` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fwide>

fclose
======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int fclose( FILE *stream );
```
 |  |  |

 Closes the given file stream. Any unwritten buffered data are flushed to the OS. Any unread buffered data are discarded.


Whether or not the operation succeeds, the stream is no longer associated with a file, and the buffer allocated by `[setbuf](setbuf "c/io/setbuf")` or `[setvbuf](setvbuf "c/io/setvbuf")`, if any, is also disassociated and deallocated if automatic allocation was used.


The behavior is undefined if the value of the pointer `stream` is used after `fclose` returns.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  the file stream to close  |

 ###  Return value

 `​0​` on success, `[EOF](../io "c/io")` otherwise.


###  Example

  
```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    const char* fname = "/tmp/unique_name.txt"; // or tmpnam(NULL);
    int is_ok = EXIT_FAILURE;
 
    FILE* fp = fopen(fname, "w+");
    if (!fp) {
        perror("File opening failed");
        return is_ok;
    }
    fputs("Hello, world!\n", fp);
    rewind(fp);
 
    int c; // note: int, not char, required to handle EOF
    while ((c = fgetc(fp)) != EOF) // standard C I/O file reading loop
        putchar(c);
 
    if (ferror(fp))
        puts("I/O error when reading");
    else if (feof(fp)) {
        puts("End of file is reached successfully");
        is_ok = EXIT_SUCCESS;
    }
 
    fclose(fp);
    remove(fname);
    return is_ok;
}
```
 Possible output:



```
Hello, world!
End of file is reached successfully
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.5.1 The fclose function (p: 304)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.5.1 The fclose function (p: 270)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.5.1 The fclose function

 ###  See also

 

|  |  |
| --- | --- |
|  [fopenfopen\_s](fopen "c/io/fopen")
(C11) |  opens a file  (function) |
|  [freopenfreopen\_s](freopen "c/io/freopen")
(C11) |  open an existing stream with a different name  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fclose "cpp/io/c/fclose") for `fclose` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fclose>

quick\_exit
===========

 

|  Defined in header `<stdlib.h>` |  |  |
| --- | --- | --- |
| 
```
_Noreturn void quick_exit( int exit_code );
```
 |  | (since C11) (until C23) |
| 
```
[[noreturn]] void quick_exit( int exit_code );
```
 |  | (since C23) |

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/quick_exit>

setvbuf
=======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int setvbuf( FILE *         stream, char *         buffer, 
             int mode, size_t size );
```
 |  | (until C99) |
| 
```
int setvbuf( FILE *restrict stream, char *restrict buffer, 
             int mode, size_t size );
```
 |  | (since C99) |
| 
```
#define _IOFBF     /*unspecified*/
#define _IOLBF     /*unspecified*/
#define _IONBF     /*unspecified*/
```
 |  |  |

 Changes the buffering mode of the given file stream `stream` as indicated by the argument `mode`. In addition,


* If `buffer` is a null pointer, resizes the internal buffer to `size`.
* If `buffer` is not a null pointer, instructs the stream to use the user-provided buffer of size `size` beginning at `buffer`. The stream must be closed (with `[fclose](fclose "c/io/fclose")`) before the [lifetime](../language/lifetime "c/language/lifetime") of the array pointed to by `buffer` ends. The contents of the array after a successful call to `setvbuf` are indeterminate and any attempt to use it is undefined behavior.

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  the file stream to set the buffer to  |
|  buffer  |  -  |  pointer to a buffer for the stream to use or null pointer to change size and mode only  |
|  mode  |  -  |  buffering mode to use. It can be one of the following values: 

|  |  |
| --- | --- |
| [\_IOFBF](http://en.cppreference.com/w/c/io) |  full buffering  |
| [\_IOLBF](http://en.cppreference.com/w/c/io) |  line buffering  |
| [\_IONBF](http://en.cppreference.com/w/c/io) |  no buffering  |

 |
|  size  |  -  |  size of the buffer  |

 ###  Return value

 `​0​` on success or nonzero on failure.


###  Notes

 This function may only be used after `stream` has been associated with an open file, but before any other operation (other than a failed call to `[setbuf](setbuf "c/io/setbuf")`/`setvbuf`).


Not all `size` bytes will necessarily be used for buffering: the actual buffer size is usually rounded down to a multiple of 2, a multiple of page size, etc.


On many implementations, line buffering is only available for terminal input streams.


A common error is setting the buffer of stdin or stdout to an array whose lifetime ends before the program terminates:



```
int main(void) {
    char buf[BUFSIZ];
    setbuf(stdin, buf);
} // lifetime of buf ends, undefined behavior
```
 The default buffer size `[BUFSIZ](../io "c/io")` is expected to be the most efficient buffer size for file I/O on the implementation, but POSIX [fstat](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fstat.html) often provides a better estimate.


###  Example

 
One use case for changing buffer size is when a better size is known. (This example uses some POSIX function, e.g. [`fileno`](https://pubs.opengroup.org/onlinepubs/7908799/xsh/fileno.html). See also SO: [#1](https://stackoverflow.com/questions/15749184/fileno-not-available) and [#2](https://stackoverflow.com/questions/44622827/why-am-i-getting-error-implicit-declaration-of-function-fileno-when-i-try-t)).



```
// Make some POSIX functions, such as `int fileno(FILE*)`, visible:
#define _POSIX_SOURCE
 
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
 
int main(void)
{
    FILE* fp = fopen("/tmp/test.txt", "w+");
    if (fp == NULL)
    {
        perror("fopen");
        return EXIT_FAILURE;
    }
 
    struct stat stats;
    if (fstat(fileno(fp), &stats) == -1) // POSIX only
    {
        perror("fstat");
        return EXIT_FAILURE;
    }
 
    printf("BUFSIZ is %d, but optimal block size is %ld\n", BUFSIZ, stats.st_blksize);
    if (setvbuf(fp, NULL, _IOFBF, stats.st_blksize) != 0)
    {
        perror("setvbuf failed"); // POSIX version sets errno
        return EXIT_FAILURE;
    }
 
    int ch;
    while((ch=fgetc(fp)) != EOF); // read entire file: use truss/strace to
                                  // observe the read(2) syscalls used
 
    fclose(fp);
    return EXIT_SUCCESS;
}
```
 Possible output:



```
BUFSIZ is 8192, but optimal block size is 65536
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.5.6 The setvbuf function (p: 225)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.5.6 The setvbuf function (p: 308)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.5.6 The setvbuf function (p: 273-274)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.5.6 The setvbuf function

 ###  See also

 

|  |  |
| --- | --- |
|  [setbuf](setbuf "c/io/setbuf") |  sets the buffer for a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/setvbuf "cpp/io/c/setvbuf") for `setvbuf` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/setvbuf>

fflush
======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int fflush( FILE *stream );
```
 |  |  |

 For output streams (and for update streams on which the last operation was output), writes any unwritten data from the `stream`'s buffer to the associated output device.


For input streams (and for update streams on which the last operation was input), the behavior is undefined.


If `stream` is a null pointer, all open output streams are flushed, including the ones manipulated within library packages or otherwise not directly accessible to the program.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  the file stream to write out  |

 ###  Return value

 Returns zero on success. Otherwise `[EOF](../io "c/io")` is returned and the error indicator of the file stream is set.


###  Notes

 POSIX [extends the specification of fflush](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fflush.html) by defining its effects on an input stream, as long as that stream represents a file or another seekable device: in that case the POSIX file pointer is repositioned to match the C stream pointer (which effectively undoes any read buffering) and the effects of any `[ungetc](ungetc "c/io/ungetc")` or `[ungetwc](ungetwc "c/io/ungetwc")` that weren't yet read back from the stream are discarded.


Microsoft also extends the specification of fflush by defining its effects on an input stream: in Visual Studio 2013 and prior, it [discarded the input buffer](https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2013/9yky46tz(v=vs.120)), in Visual Studio 2015 and newer, it [has no effect, buffers are retained](https://msdn.microsoft.com/en-us/library/9yky46tz.aspx).


###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.5.2 The fflush function (p: 305)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.5.2 The fflush function (p: 270-271)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.5.2 The fflush function

 ###  See also

 

|  |  |
| --- | --- |
|  [fopenfopen\_s](fopen "c/io/fopen")
(C11) |  opens a file  (function) |
|  [fclose](fclose "c/io/fclose") |  closes a file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fflush "cpp/io/c/fflush") for `fflush` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fflush>

fread
=====

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
size_t fread( void          *buffer, size_t size, size_t count,
              FILE          *stream );
```
 |  | (until C99) |
| 
```
size_t fread( void *restrict buffer, size_t size, size_t count,
              FILE *restrict stream );
```
 |  | (since C99) |

 Reads up to `count` objects into the array `buffer` from the given input stream `stream` as if by calling `[fgetc](fgetc "c/io/fgetc")` `size` times for each object, and storing the results, in the order obtained, into the successive positions of `buffer`, which is reinterpreted as an array of `unsigned char`. The file position indicator for the stream is advanced by the number of characters read.


If an error occurs, the resulting value of the file position indicator for the stream is indeterminate. If a partial element is read, its value is indeterminate.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  buffer  |  -  |  pointer to the array where the read objects are stored  |
|  size  |  -  |  size of each object in bytes  |
|  count  |  -  |  the number of the objects to be read  |
|  stream  |  -  |  the stream to read  |

 ###  Return value

 Number of objects read successfully, which may be less than `count` if an error or end-of-file condition occurs.


If `size` or `count` is zero, `fread` returns zero and performs no other action.


`fread` does not distinguish between end-of-file and error, and callers must use `[feof](feof "c/io/feof")` and `[ferror](ferror "c/io/ferror")` to determine which occurred.


###  Example

  
```
#include <stdio.h>
 
enum { SIZE = 5 };
 
int main(void)
{
    const double a[SIZE] = {1.0, 2.0, 3.0, 4.0, 5.0};
    printf("Array has size %ld bytes, element size: %ld\n", sizeof a, sizeof *a);
    FILE *fp = fopen("test.bin", "wb"); // must use binary mode
    fwrite(a, sizeof *a, SIZE, fp); // writes an array of doubles
    fclose(fp);
 
    double b[SIZE];
    fp = fopen("test.bin","rb");
    const size_t ret_code = fread(b, sizeof b[0], SIZE, fp); // reads an array of doubles
    if (ret_code == SIZE)
    {
        printf("Array at %p read successfully, contents:\n", (void*)&a);
        for (int n = 0; n != SIZE; ++n)
            printf("%f ", b[n]);
        putchar('\n');
    }
    else // error handling
    {
        if (feof(fp))
            printf("Error reading test.bin: unexpected end of file\n");
        else if (ferror(fp))
            perror("Error reading test.bin");
    }
 
    fclose(fp);
}
```
 Possible output:



```
Array has size 40 bytes, element size: 8
Array at 0x1337f00d6960 read successfully, contents:
1.000000 2.000000 3.000000 4.000000 5.000000
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.21.8.1 The fread function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.21.8.1 The fread function (p: 243-244)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.8.1 The fread function (p: 335)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.8.1 The fread function (p: 301)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.8.1 The fread function

 ###  See also

 

|  |  |
| --- | --- |
|  [scanffscanfsscanfscanf\_sfscanf\_ssscanf\_s](fscanf "c/io/fscanf")
(C11)(C11)(C11) |  reads formatted input from `[stdin](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [fgets](fgets "c/io/fgets") |  gets a character string from a file stream  (function) |
|  [fwrite](fwrite "c/io/fwrite") |  writes to a file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fread "cpp/io/c/fread") for `fread` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fread>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/system>

setbuf
======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
void setbuf( FILE          *stream, char          *buffer );
```
 |  | (until C99) |
| 
```
void setbuf( FILE *restrict stream, char *restrict buffer );
```
 |  | (since C99) |
| 
```
#define BUFSIZ     /*unspecified*/
```
 |  |  |

 Sets the internal buffer to use for stream operations. It should be at least `BUFSIZ` characters long.


If `buffer` is not null, equivalent to `[setvbuf](http://en.cppreference.com/w/c/io/setvbuf)(stream, buffer, [\_IOFBF](http://en.cppreference.com/w/c/io), [BUFSIZ](http://en.cppreference.com/w/c/io))`.


If `buffer` is null, equivalent to `[setvbuf](http://en.cppreference.com/w/c/io/setvbuf)(stream, [NULL](http://en.cppreference.com/w/c/types/NULL), [\_IONBF](http://en.cppreference.com/w/c/io), 0)`, which turns off buffering.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  the file stream to set the buffer to  |
|  buffer  |  -  |  pointer to a buffer for the stream to use. If a null pointer is supplied, the buffering is turned off  |

 ###  Return value

 None.


###  Notes

 If `[BUFSIZ](../io "c/io")` is not the appropriate buffer size, `[setvbuf](setvbuf "c/io/setvbuf")` can be used to change it.


`[setvbuf](setvbuf "c/io/setvbuf")` should also be used to detect errors, since `setbuf` does not indicate success or failure.


This function may only be used after `stream` has been associated with an open file, but before any other operation (other than a failed call to `setbuf`/`setvbuf`).


A common error is setting the buffer of stdin or stdout to an array whose lifetime ends before the program terminates:



```
int main(void) {
    char buf[BUFSIZ];
    setbuf(stdin, buf);
} // lifetime of buf ends, undefined behavior
```
 ###  Example

 
`setbuf` may be used to disable buffering on streams that require immediate output.



```
#include <stdio.h>
#include <threads.h>
 
int main(void)
{
    setbuf(stdout, NULL); // unbuffered stdout
    putchar('a'); // 'a' appears immediately if stdout is unbuffered
    thrd_sleep(&(struct timespec){.tv_sec=1}, NULL); // sleep 1 sec
    putchar('b'); 
}
```
 Output:



```
ab
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.5.5 The setbuf function (p: 225)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.5.5 The setbuf function (p: 307-308)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.5.5 The setbuf function (p: 273)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.5.5 The setbuf function

 ###  See also

 

|  |  |
| --- | --- |
|  [setvbuf](setvbuf "c/io/setvbuf") |  sets the buffer and its size for a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/setbuf "cpp/io/c/setbuf") for `setbuf` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/setbuf>

fwrite
======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
size_t fwrite( const void *buffer, size_t size, size_t count,
               FILE *stream );
```
 |  | (until C99) |
| 
```
size_t fwrite( const void *restrict buffer, size_t size, size_t count, 
               FILE *restrict stream );
```
 |  | (since C99) |

 Writes `count` of objects from the given array `buffer` to the output stream `stream`. The objects are written as if by reinterpreting each object as an array of `unsigned char` and calling `[fputc](fputc "c/io/fputc")` `size` times for each object to write those `unsigned char`s into `stream`, in order. The file position indicator for the stream is advanced by the number of characters written.


If an error occurs, the resulting value of the file position indicator for the stream is indeterminate.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  buffer  |  -  |  pointer to the first object in the array to be written  |
|  size  |  -  |  size of each object  |
|  count  |  -  |  the number of the objects to be written  |
|  stream  |  -  |  pointer to the output stream  |

 ###  Return value

 The number of objects written successfully, which may be less than `count` if an error occurs.


If `size` or `count` is zero, `fwrite` returns zero and performs no other action.


###  Example

  
```
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
enum { SIZE = 5 };
int main(void)
{
    double a[SIZE] = {1, 2, 3, 4, 5};
    FILE *f1 = fopen("file.bin", "wb");
    assert(f1);
    size_t r1 = fwrite(a, sizeof a[0], SIZE, f1);
    printf("wrote %zu elements out of %d requested\n", r1,  SIZE);
    fclose(f1);
 
    double b[SIZE];
    FILE *f2 = fopen("file.bin", "rb");
    size_t r2 = fread(b, sizeof b[0], SIZE, f2);
    fclose(f2);
    printf("read back: ");
    for(size_t i = 0; i < r2; i++)
        printf("%0.2f ", b[i]);
}
```
 Output:



```
wrote 5 elements out of 5 requested
read back: 1.00 2.00 3.00 4.00 5.00
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.8.2 The fwrite function (p: 335-336)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.8.2 The fwrite function (p: 301-302)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.8.2 The fwrite function

 ###  See also

 

|  |  |
| --- | --- |
|  [printffprintfsprintfsnprintfprintf\_sfprintf\_ssprintf\_ssnprintf\_s](fprintf "c/io/fprintf")
(C99)(C11)(C11)(C11)(C11) |  prints formatted output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [fputs](fputs "c/io/fputs") |  writes a character string to a file stream  (function) |
|  [fread](fread "c/io/fread") |  reads from a file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fwrite "cpp/io/c/fwrite") for `fwrite` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fwrite>

fgetc, getc
===========

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int fgetc( FILE *stream );
```
 |  (1)  |  |
| 
```
int getc( FILE *stream );
```
 |  (2)  |  |

 
1) Reads the next character from the given input stream. 
2) Same as `fgetc`, except that if `getc` is implemented as a macro, it may evaluate stream more than once, so the corresponding argument should never be an expression with side effects. ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  to read the character from  |

 ###  Return value

 On success, returns the obtained character as an `unsigned char` converted to an `int`. On failure, returns `[EOF](../io "c/io")`.


If the failure has been caused by end-of-file condition, additionally sets the *eof* indicator (see `[feof()](feof "c/io/feof")`) on `stream`. If the failure has been caused by some other error, sets the *error* indicator (see `[ferror()](ferror "c/io/ferror")`) on `stream`.


###  Example

  
```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    const char* fname = "/tmp/unique_name.txt"; // or tmpnam(NULL);
    int is_ok = EXIT_FAILURE;
 
    FILE* fp = fopen(fname, "w+");
    if (!fp) {
        perror("File opening failed");
        return is_ok;
    }
    fputs("Hello, world!\n", fp);
    rewind(fp);
 
    int c; // note: int, not char, required to handle EOF
    while ((c = fgetc(fp)) != EOF) // standard C I/O file reading loop
        putchar(c);
 
    if (ferror(fp))
        puts("I/O error when reading");
    else if (feof(fp)) {
        puts("End of file is reached successfully");
        is_ok = EXIT_SUCCESS;
    }
 
    fclose(fp);
    remove(fname);
    return is_ok;
}
```
 Possible output:



```
Hello, world!
End of file is reached successfully
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.7.1 The fgetc function (p: 240-241)
+ 7.21.7.5 The getc function (p: 242)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.7.1 The fgetc function (p: 330)
+ 7.21.7.5 The getc function (p: 332)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.7.1 The fgetc function (p: 296)
+ 7.19.7.5 The getc function (p: 297-298)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.7.1 The fgetc function
+ 4.9.7.5 The getc function

 ###  See also

 

|  |  |
| --- | --- |
|  [getchar](getchar "c/io/getchar") |  reads a character from `[stdin](std_streams "c/io/std streams")`  (function) |
|  [getsgets\_s](gets "c/io/gets")
(removed in C11)(C11) |  reads a character string from `stdin`  (function) |
|  [fputcputc](fputc "c/io/fputc") |  writes a character to a file stream  (function) |
|  [ungetc](ungetc "c/io/ungetc") |  puts a character back into a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fgetc "cpp/io/c/fgetc") for `fgetc, getc` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fgetc>

fgets
=====

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
char *fgets( char          *str, int count, FILE          *stream );
```
 |  | (until C99) |
| 
```
char *fgets( char *restrict str, int count, FILE *restrict stream );
```
 |  | (since C99) |

 Reads at most `count - 1` characters from the given file stream and stores them in the character array pointed to by `str`. Parsing stops if a newline character is found, in which case `str` will contain that newline character, or if end-of-file occurs. If bytes are read and no errors occur, writes a null character at the position immediately after the last character written to `str`.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  str  |  -  |  pointer to an element of a char array  |
|  count  |  -  |  maximum number of characters to write (typically the length of `str`)  |
|  stream  |  -  |  file stream to read the data from  |

 ###  Return value

 `str` on success, null pointer on failure.


If the end-of-file condition is encountered, sets the *eof* indicator on `stream` (see `[feof()](feof "c/io/feof")`). This is only a failure if it causes no bytes to be read, in which case a null pointer is returned and the contents of the array pointed to by `str` are not altered (i.e. the first byte is not overwritten with a null character).


If the failure has been caused by some other error, sets the *error* indicator (see `[ferror()](ferror "c/io/ferror")`) on `stream`. The contents of the array pointed to by `str` are indeterminate (it may not even be null-terminated).


###  Notes

 [POSIX additionally requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html) that `fgets` sets `[errno](../error/errno "c/error/errno")` if a read error occurs.


Although the standard specification is [unclear](https://stackoverflow.com/questions/23388620) in the cases where `count<=1`, common implementations do.


* if `count < 1`, do nothing, report error
* if `count == 1`,
+ some implementations do nothing, report error,
+ others read nothing, store zero in `str[0]`, report success

 ###  Example

  
```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    FILE* tmpf = tmpfile();
    fputs("Alan Turing\n", tmpf);
    fputs("John von Neumann\n", tmpf);
    fputs("Alonzo Church\n", tmpf);
 
    rewind(tmpf);
 
    char buf[8];
    while (fgets(buf, sizeof buf, tmpf) != NULL)
          printf("\"%s\"\n", buf);
 
    if (feof(tmpf))
       puts("End of file reached");
}
```
 Output:



```
"Alan Tu"
"ring
"
"John vo"
"n Neuma"
"nn
"
"Alonzo "
"Church
"
End of file reached
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.7.2 The fgets function (p: 241)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.7.2 The fgets function (p: 331)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.7.2 The fgets function (p: 296)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.7.2 The fgets function

 ###  See also

 

|  |  |
| --- | --- |
|  [scanffscanfsscanfscanf\_sfscanf\_ssscanf\_s](fscanf "c/io/fscanf")
(C11)(C11)(C11) |  reads formatted input from `[stdin](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [getsgets\_s](gets "c/io/gets")
(removed in C11)(C11) |  reads a character string from `stdin`  (function) |
|  [fputs](fputs "c/io/fputs") |  writes a character string to a file stream  (function) |
|  [getlinegetwlinegetdelimgetwdelim](https://en.cppreference.com/w/c/experimental/dynamic/getline "c/experimental/dynamic/getline")
(dynamic memory TR) |  read from a stream into an automatically resized buffer until delimiter/end of line  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fgets "cpp/io/c/fgets") for `fgets` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fgets>

fputc, putc
===========

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int fputc( int ch, FILE *stream );
```
 |  |  |
| 
```
int putc( int ch, FILE *stream );
```
 |  |  |

 Writes a character `ch` to the given output stream `stream`. `putc()` may be implemented as a macro and evaluate `stream` more than once, so the corresponding argument should never be an expression with side effects.


Internally, the character is converted to `unsigned char` just before being written.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ch  |  -  |  character to be written  |
|  stream  |  -  |  output stream  |

 ###  Return value

 On success, returns the written character.


On failure, returns `[EOF](../io "c/io")` and sets the *error* indicator (see `[ferror()](ferror "c/io/ferror")`) on `stream`.


###  Example

 
putc with error checking.



```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    int ret_code = 0;
    for (char c = 'a'; (ret_code != EOF) && (c != 'z'); c++)
        ret_code = putc(c, stdout);
 
    /* Test whether EOF was reached. */
    if (ret_code == EOF)
       if (ferror(stdout)) 
       {
          perror("putc()");
          fprintf(stderr,"putc() failed in file %s at line # %d\n", __FILE__,__LINE__-7);
          exit(EXIT_FAILURE);
       }
    putc('\n', stdout);
 
    return EXIT_SUCCESS;
}
```
 Output:



```
abcdefghijklmnopqrstuvwxy
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.7.3 The fputc function (p: 331)
+ 7.21.7.7 The putc function (p: 333)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.7.3 The fputc function (p: 297)
+ 7.19.7.8 The putc function (p: 299)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.7.3 The fputc function
+ 4.9.7.8 The putc function

 ###  See also

 

|  |  |
| --- | --- |
|  [putchar](putchar "c/io/putchar") |  writes a character to `stdout`  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fputc "cpp/io/c/fputc") for `fputc, putc` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fputc>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/SIG_strategies>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/SIG_types>

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) (until C23) |
| 
```
[[noreturn]] void longjmp( jmp_buf env, int status );
```
 |  | (since C23) |

 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 status) 
{
    printf("foo(%d) called\n", status);
    longjmp(my_jump_buffer, status + 1); // will return status+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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/longjmp>

fputs
=====

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int fputs( const char          *str, FILE          *stream );
```
 |  | (until C99) |
| 
```
int fputs( const char *restrict str, FILE *restrict stream );
```
 |  | (since C99) |

 Writes every character from the null-terminated string `str` to the output stream `stream`, as if by repeatedly executing `[fputc](fputc "c/io/fputc")`.


The terminating null character from `str` is not written.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  str  |  -  |  null-terminated character string to be written  |
|  stream  |  -  |  output stream  |

 ###  Return value

 On success, returns a non-negative value.


On failure, returns `[EOF](../io "c/io")` and sets the *error* indicator (see `[ferror()](ferror "c/io/ferror")`) on `stream`.


###  Notes

 The related function `[puts](puts "c/io/puts")` appends a newline character to the output, while `fputs` writes the string unmodified.


Different implementations return different non-negative numbers: some return the last character written, some return the number of characters written (or INT\_MAX if the string was longer than that), some simply return a non-negative constant such as zero.


###  Example

  
```
#include <stdio.h>
 
int main(void)
{
    int rc = fputs("Hello World", stdout);
 
    if (rc == EOF)
       perror("fputs()"); // POSIX requires that errno is set
}
```
 Output:



```
Hello World
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.7.4 The fputs function (p: 331-332)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.7.4 The fputs function (p: 297)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.7.4 The fputs function

 ###  See also

 

|  |  |
| --- | --- |
|  [printffprintfsprintfsnprintfprintf\_sfprintf\_ssprintf\_ssnprintf\_s](fprintf "c/io/fprintf")
(C99)(C11)(C11)(C11)(C11) |  prints formatted output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [puts](puts "c/io/puts") |  writes a character string to `[stdout](std_streams "c/io/std streams")`  (function) |
|  [fgets](fgets "c/io/fgets") |  gets a character string from a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fputs "cpp/io/c/fputs") for `fputs` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fputs>

getchar
=======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int getchar(void);
```
 |  |  |

 Reads the next character from `[stdin](std_streams "c/io/std streams")`.


Equivalent to `[getc](http://en.cppreference.com/w/c/io/fgetc)([stdin](http://en.cppreference.com/w/c/io/std_streams))`.


###  Parameters

 (none).


###  Return value

 The obtained character on success or `[EOF](../io "c/io")` on failure.


If the failure has been caused by end-of-file condition, additionally sets the *eof* indicator (see `[feof()](feof "c/io/feof")`) on `[stdin](std_streams "c/io/std streams")`. If the failure has been caused by some other error, sets the *error* indicator (see `[ferror()](ferror "c/io/ferror")`) on `[stdin](std_streams "c/io/std streams")`.


###  Example

 
getchar with error checking.



```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{ 
    int ch;
    while ((ch=getchar()) != EOF)   /* read/print "abcde" from stdin */
          printf("%c", ch);
 
    /* Test reason for reaching EOF. */
    if (feof(stdin))          /* if failure caused by end-of-file condition */
       puts("End of file reached");
    else if (ferror(stdin))   /* if failure caused by some other error      */
         {
            perror("getchar()");
            fprintf(stderr,"getchar() failed in file %s at line # %d\n", __FILE__,__LINE__-9);
            exit(EXIT_FAILURE);
         }
 
    return EXIT_SUCCESS;
}
```
 Possible output:



```
abcde
End of file reached
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.7.6 The getchar function (p: 332)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.7.6 The getchar function (p: 298)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.7.6 The getchar function

 ###  See also

 

|  |  |
| --- | --- |
|  [fgetcgetc](fgetc "c/io/fgetc") |  gets a character from a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/getchar "cpp/io/c/getchar") for `getchar` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/getchar>

puts
====

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int puts( const char *str );
```
 |  |  |

 Writes every character from the null-terminated string `str` and one additional newline character `'\n'` to the output stream `stdout`, as if by repeatedly executing `[fputc](fputc "c/io/fputc")`.


The terminating null character from `str` is not written.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  str  |  -  |  character string to be written  |

 ###  Return value

 On success, returns a non-negative value.


On failure, returns `[EOF](../io "c/io")` and sets the *error* indicator (see `[ferror()](ferror "c/io/ferror")`) on `stream`.


###  Notes

 The `puts` function appends the newline character to the output, while `[fputs](fputs "c/io/fputs")` function does not.


Different implementations return different non-negative numbers: some return the last character written, some return the number of characters written (or INT\_MAX if the string was longer than that), some simply return a non-negative constant.


A typical cause of failure for `puts` is running out of space on the file system, when stdout is redirected to a file.


###  Example

  
```
#include <stdio.h>
 
int main(void)
{
    int rc = puts("Hello World");
 
    if (rc == EOF)
       perror("puts()"); // POSIX requires that errno is set
}
```
 Output:



```
Hello World
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.7.9 The puts function (p: 333)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.7.10 The puts function (p: 299)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.7.10 The puts function

 ###  See also

 

|  |  |
| --- | --- |
|  [fputs](fputs "c/io/fputs") |  writes a character string to a file stream  (function) |
|  [printffprintfsprintfsnprintfprintf\_sfprintf\_ssprintf\_ssnprintf\_s](fprintf "c/io/fprintf")
(C99)(C11)(C11)(C11)(C11) |  prints formatted output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/puts "cpp/io/c/puts") for `puts` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/puts>

ungetc
======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int ungetc( int ch, FILE *stream );
```
 |  |  |

 If `ch` does not equal `[EOF](../io "c/io")`, pushes the character `ch` (reinterpreted as `unsigned char`) into the input buffer associated with the stream `stream` in such a manner that subsequent read operation from `stream` will retrieve that character. The external device associated with the stream is not modified.


Stream repositioning operations `[fseek](fseek "c/io/fseek")`, `[fsetpos](fsetpos "c/io/fsetpos")`, and `[rewind](rewind "c/io/rewind")` discard the effects of `ungetc`.


If `ungetc` is called more than once without an intervening read or repositioning, it may fail (in other words, a pushback buffer of size 1 is guaranteed, but any larger buffer is implementation-defined). If multiple successful `ungetc` were performed, read operations retrieve the pushed-back characters in reverse order of `ungetc`.


If `ch` equals `[EOF](../io "c/io")`, the operation fails and the stream is not affected.


A successful call to `ungetc` clears the end of file status flag `[feof](feof "c/io/feof")`.


A successful call to `ungetc` on a binary stream decrements the stream position indicator by one (the behavior is indeterminate if the stream position indicator was zero).


A successful call to `ungetc` on a text stream modifies the stream position indicator in unspecified manner but guarantees that after all pushed-back characters are retrieved with a read operation, the stream position indicator is equal to its value before `ungetc`.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ch  |  -  |  character to be pushed into the input stream buffer  |
|  stream  |  -  |  file stream to put the character back to  |

 ###  Return value

 On success `ch` is returned.


On failure `[EOF](../io "c/io")` is returned and the given stream remains unchanged.


###  Notes

 The size of the pushback buffer varies in practice from 4k (Linux, MacOS) to as little as 4 (Solaris) or the guaranteed minimum 1 (HPUX, AIX).


The apparent size of the pushback buffer may be larger if the character that is pushed back equals the character existing at that location in the external character sequence (the implementation may simply decrement the read file position indicator and avoid maintaining a pushback buffer).


###  Example

 
demonstrates the original purpose of `ungetc`: implementation of `[scanf](fscanf "c/io/fscanf")`.



```
#include <ctype.h>
#include <stdio.h>
 
void demo_scanf(const char* fmt, FILE* s)
{
    while (*fmt != '\0') {
        if (*fmt == '%') {
            int c;
            switch (*++fmt) {
                case 'u':
                    while (isspace(c=getc(s))) {}
                    unsigned int num = 0;
                    while (isdigit(c)) {
                        num = num*10 + c-'0';
                        c = getc(s);
                    }
                    printf("%%u scanned %u\n", num);
                    ungetc(c, s);
                    break;
                case 'c':
                    c = getc(s);
                    printf("%%c scanned '%c'\n", c);
                    break;
            }
        } else {
            ++fmt;
        }
    }
}
 
int main(void)
{
    FILE* f = fopen("input.txt", "w+");
    if (f != NULL) {
        fputs("123x", f);
        rewind(f); 
        demo_scanf("%u%c", f);
        fclose(f);
    }
    return 0;
}
```
 Output:



```
%u scanned 123
%c scanned 'x'
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.7.10 The ungetc function (p: 243)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.7.10 The ungetc function (p: 334)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.7.11 The ungetc function (p: 300)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.7.11 The ungetc function

 ###  See also

 

|  |  |
| --- | --- |
|  [fgetcgetc](fgetc "c/io/fgetc") |  gets a character from a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/ungetc "cpp/io/c/ungetc") for `ungetc` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/ungetc>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/signal>

timespec\_getres
================

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
| 
```
int timespec_getres( struct timespec *ts, int base );
```
 |  | (since C23) |

 If `ts` is non-null and `base` is supported by `timespec_get`, modifies `*ts` to hold the resolution of time provided by `timespec_get` for `base`. For each supported `base`, multiple calls to `timespec_getres` during the same program execution have identical results.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ts  |  -  |  pointer to an object of type `struct timespec` |
|  base  |  -  | `TIME_UTC` or another nonzero integer value indicating the time base  |

 ###  Return value

 The value of `base` if `base` is supported, zero otherwise.


###  Notes

 The POSIX function [`clock_getres(clock_id, ts)`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html) may also be used to populate a `timespec` with the resolution of time identified by `clock_id`.


###  Example

  
```
#include <stdio.h>
#include <time.h>
 
int main(void)
{
    char buff[128];
    struct timespec ts;
    const int res = timespec_getres(&ts, TIME_UTC);
    if (res == TIME_UTC) {
        struct tm timer;
        strftime(buff, sizeof buff, "%D %T", gmtime_r(&ts.tv_sec, &timer));
        printf("Time resolution info: %s.%09ld UTC\n", buff, ts.tv_nsec);
    } else {
        printf("TIME_UTC base is not supported.");
    }
}
```
 Possible output:



```
Time resolution info: 01/01/70 00:00:00.000000001 UTC
```
  ###  See also

 

|  |  |
| --- | --- |
|  [timespec](timespec "c/chrono/timespec")
(C11) |  time in seconds and nanoseconds  (struct) |
|  [timespec\_get](timespec_get "c/chrono/timespec get")
(C11) |  returns the calendar time in seconds and nanoseconds based on a given time base  (function) |
|  [time](time "c/chrono/time") |  returns the current calendar time of the system as time since epoch  (function) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/timespec_getres>

asctime, asctime\_s
===================

 

|  Defined in header `<time.h>` |  |  |
| --- | --- | --- |
|  | (1) |  |
| 
```
char*                asctime( const struct tm* time_ptr );
```
 | (until C23) |
| 
```
[[deprecated]] char* asctime( const struct tm* time_ptr );
```
 | (since C23) |
| 
```
errno_t asctime_s( char* buf, rsize_t bufsz, const struct tm* time_ptr );
```
 |  (2)  | (since C11) |

 1) Converts given calendar time `[tm](tm "c/chrono/tm")` to a textual representation of the following fixed 25-character form: `Www Mmm dd hh:mm:ss yyyy\n` * `Www` - three-letter English abbreviated day of the week from `time_ptr->tm_wday`, one of `Mon`, `Tue`, `Wed`, `Thu`, `Fri`, `Sat`, `Sun`.
* `Mmm` - three-letter English abbreviated month name from `time_ptr->tm_mon`, one of `Jan`, `Feb`, `Mar`, `Apr`, `May`, `Jun`, `Jul`, `Aug`, `Sep`, `Oct`, `Nov`, `Dec`.
* `dd` - 2-digit day of the month from `timeptr->tm_mday` as if printed by `[sprintf](../io/fprintf "c/io/fprintf")` using `%2d`
* `hh` - 2-digit hour from `timeptr->tm_hour` as if printed by `[sprintf](../io/fprintf "c/io/fprintf")` using `%.2d`
* `mm` - 2-digit minute from `timeptr->tm_min` as if printed by `[sprintf](../io/fprintf "c/io/fprintf")` using `%.2d`
* `ss` - 2-digit second from `timeptr->tm_sec` as if printed by `[sprintf](../io/fprintf "c/io/fprintf")` using `%.2d`
* `yyyy` - 4-digit year from `timeptr->tm_year + 1900` as if printed by `[sprintf](../io/fprintf "c/io/fprintf")` using `%4d`

 
 The behavior is undefined if any member of `*time_ptr` is outside its normal range 
 The behavior is undefined if the calendar year indicated by `time_ptr->tm_year` has more than 4 digits or is less than the year 1000. 
 The function does not support localization, and the newline character cannot be removed. 
 The function modifies static storage and is not thread-safe. 

|  |  |
| --- | --- |
|  This function is deprecated and should not be used in new code.  | (since C23) |

 
2) Same as (1), except that the message is written into user-provided storage `buf`, which is guaranteed to be null-terminated, 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: 

* `buf` or `time_ptr` is a null pointer
* `bufsz` is less than 26 or greater than `RSIZE_MAX`
* not all members of `*time_ptr` are within their normal ranges
* the year indicated by `time_ptr->tm_year` is less than 0 or greater than 9999

 
As with all bounds-checked functions, `asctime_s` 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 [`<time.h>`](../chrono "c/chrono").

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  time\_ptr  |  -  |  pointer to a `[tm](tm "c/chrono/tm")` object specifying the time to print  |
|  buf  |  -  |  pointer to a user-supplied buffer at least 26 bytes in length  |
|  bufsz  |  -  |  size of the user-supplied buffer  |

 ###  Return value

 
1) pointer to a static null-terminated character string holding the textual representation of date and time as described above. The string may be shared between `asctime` and `[ctime](ctime "c/chrono/ctime")`, and may be overwritten on each invocation of any of those functions. 
2) zero on success, non-zero on failure, in which case `buf[0]` is set to zero (unless `buf` is a null pointer or `bufsz` is zero or greater than `RSIZE_MAX`). ###  Notes

 `asctime` returns a pointer to static data and is not thread-safe. POSIX marks this function obsolete and recommends `[strftime](strftime "c/chrono/strftime")` instead. The C standard also recommends `[strftime](strftime "c/chrono/strftime")` instead of `asctime` and `asctime_s` because `strftime` is more flexible and locale-sensitive.


POSIX limits undefined behaviors only to when the output string would be longer than 25 characters, when `timeptr->tm_wday` or `timeptr->tm_mon` are not within the expected ranges, or when `timeptr->tm_year` exceeds `INT_MAX-1990`.


Some implementations handle `timeptr->tm_mday==0` as meaning the last day of the preceding month.


###  Example

  
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <time.h>
#include <stdio.h>
 
int main(void)
{
    struct tm tm = *localtime(&(time_t){time(NULL)});
    printf("%s", asctime(&tm));
 
#ifdef __STDC_LIB_EXT1__
    char str[26];
    asctime_s(str, sizeof str, &tm);
    printf("%s", str);
#endif
}
```
 Possible output:



```
Tue May 26 21:51:50 2015
Tue May 26 21:51:50 2015
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.27.2.1 The asctime function (p: 287)
+ K.3.8.2.1 The asctime\_s function (p: 453-454)

* C11 standard (ISO/IEC 9899:2011):
+ 7.27.2.1 The asctime function (p: 392-393)
+ K.3.8.2.1 The asctime\_s function (p: 624-625)

* C99 standard (ISO/IEC 9899:1999):
+ 7.23.3.1 The asctime function (p: 341-342)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.12.3.1 The asctime function

 ###  See also

 

|  |  |
| --- | --- |
|  [ctimectime\_s](ctime "c/chrono/ctime")
(deprecated in C23)(C11) |  converts a `[time\_t](time_t "c/chrono/time t")` object to a textual representation  (function) |
|  [strftime](strftime "c/chrono/strftime") |  converts a `[tm](tm "c/chrono/tm")` object to custom textual representation  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/chrono/c/asctime "cpp/chrono/c/asctime") for `asctime` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/chrono/asctime>

putchar
=======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int putchar( int ch );
```
 |  |  |

 Writes a character `ch` to `stdout`. Internally, the character is converted to `unsigned char` just before being written.


Equivalent to `[putc](http://en.cppreference.com/w/c/io/fputc)(ch, [stdout](http://en.cppreference.com/w/c/io/std_streams))`.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ch  |  -  |  character to be written  |

 ###  Return value

 On success, returns the written character.


On failure, returns `[EOF](../io "c/io")` and sets the *error* indicator (see `[ferror()](ferror "c/io/ferror")`) on `[stdout](std_streams "c/io/std streams")`.


###  Example

 
putchar with error checking.



```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    int ret_code = 0;
    for (char c = 'a'; (ret_code != EOF) && (c != 'z'); c++)
        ret_code = putchar(c);
 
    /* Test whether EOF was reached. */
    if (ret_code == EOF)
       if (ferror(stdout)) 
       {
          fprintf(stderr,"putchar() failed in file %s at line # %d\n", __FILE__,__LINE__-6);
          perror("putchar()");
          exit(EXIT_FAILURE);
       }
    putchar('\n');
 
    // putchar return value is not equal to the argument
    int r = 0x1070;
    printf("\n0x%x\n", r);
    r = putchar(r);
    printf("\n0x%x\n", r);
}
```
 Output:



```
abcdefghijklmnopqrstuvwxy
 
0x1070
p
0x70
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.7.8 The putchar function (p: 333)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.7.9 The putchar function (p: 299)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.7.9 The putchar function

 ###  See also

 

|  |  |
| --- | --- |
|  [fputcputc](fputc "c/io/fputc") |  writes a character to a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/putchar "cpp/io/c/putchar") for `putchar` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/putchar>

fgetwc, getwc
=============

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
wint_t fgetwc( FILE *stream );
```
 |  | (since C95) |
| 
```
wint_t getwc( FILE *stream );
```
 |  | (since C95) |

 Reads the next wide character from the given input stream. `getwc()` may be implemented as a macro and may evaluate `stream` more than once.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  to read the wide character from  |

 ###  Return value

 The next wide character from the stream or `WEOF` on failure.


If the failure has been caused by end-of-file condition, additionally sets the *eof* indicator (see `[feof()](feof "c/io/feof")`) on `stream`. If the failure has been caused by some other error, sets the *error* indicator (see `[ferror()](ferror "c/io/ferror")`) on `stream`.


If an encoding error occurred, additionally sets `[errno](../error/errno "c/error/errno")` to `EILSEQ`.


###  Example

  
```
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <errno.h>
#include <locale.h>
 
int main(void)
{
    setlocale(LC_ALL, "en_US.utf8");
    FILE *fp = fopen("fgetwc.dat", "w");
    if(!fp) {
        perror("Can't open file for writing");
        return EXIT_FAILURE;
    }
    fputs("кошка\n", fp);
    fclose(fp);
 
    fp = fopen("fgetwc.dat", "r");
    if(!fp) {
        perror("Can't open file for reading");
        return EXIT_FAILURE;
    }
    wint_t wc;
    errno = 0;
    while ((wc = fgetwc(fp)) != WEOF)
        putwchar(wc);
 
    if (ferror(fp)) {
        if (errno == EILSEQ)
            puts("Character encoding error while reading.");
        else
            puts("I/O error when reading");
    } else if (feof(fp))
        puts("End of file reached successfully");
 
    fclose(fp);
}
```
 Output:



```
кошка
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.29.3.1 The fgetwc function (p: 307-308)
+ 7.29.3.6 The getwc function (p: 309)

* C11 standard (ISO/IEC 9899:2011):
+ 7.29.3.1 The fgetwc function (p: 421-422)
+ 7.29.3.6 The getwc function (p: 424)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.3.1 The fgetwc function (p: 367)
+ 7.24.3.6 The getwc function (p: 369)

 ###  See also

 

|  |  |
| --- | --- |
|  [fgetcgetc](fgetc "c/io/fgetc") |  gets a character from a file stream  (function) |
|  [fgetws](fgetws "c/io/fgetws")
(C95) |  gets a wide string from a file stream  (function) |
|  [fputwcputwc](fputwc "c/io/fputwc")
(C95) |  writes a wide character to a file stream  (function) |
|  [ungetwc](ungetwc "c/io/ungetwc")
(C95) |  puts a wide character back into a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fgetwc "cpp/io/c/fgetwc") for `fgetwc` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fgetwc>

fputws
======

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
int fputws( const wchar_t *str, FILE *stream );
```
 |  | (since C95) (until C99) |
| 
```
int fputws( const wchar_t * restrict str, FILE * restrict stream );
```
 |  | (since C99) |

 Writes every character from the null-terminated wide string `str` to the output stream `stream`, as if by repeatedly executing `[fputwc](fputwc "c/io/fputwc")`.


The terminating null wide character from `str` is not written.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  str  |  -  |  null-terminated wide string to be written  |
|  stream  |  -  |  output stream  |

 ###  Return value

 On success, returns a non-negative value.


On failure, returns `[EOF](../io "c/io")` and sets the *error* indicator (see `[ferror](ferror "c/io/ferror")`) on `stream`.


###  Example

  
```
#include <locale.h>
#include <stdio.h>
#include <wchar.h>
 
int main(void)
{
    setlocale(LC_ALL, "en_US.utf8");
    int rc = fputws(L"御休みなさい", stdout);
 
    if (rc == EOF)
       perror("fputws()"); // POSIX requires that errno is set
}
```
 Output:



```
御休みなさい
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.29.3.4 The fputws function (p: 423)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.3.4 The fputws function (p: 368)

 ###  See also

 

|  |  |
| --- | --- |
|  [fputs](fputs "c/io/fputs") |  writes a character string to a file stream  (function) |
|  [wprintffwprintfswprintfwprintf\_sfwprintf\_sswprintf\_ssnwprintf\_s](fwprintf "c/io/fwprintf")
(C95)(C95)(C95)(C11)(C11)(C11)(C11) |  prints formatted wide character output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  **fputws**
(C95) |  writes a wide string to a file stream  (function) |
|  [fgetws](fgetws "c/io/fgetws")
(C95) |  gets a wide string from a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fputws "cpp/io/c/fputws") for `fputws` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fputws>

getwchar
========

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
wint_t getwchar(void);
```
 |  | (since C95) |

 Reads the next wide character from `[stdin](std_streams "c/io/std streams")`.


###  Parameters

 (none).


###  Return value

 the obtained wide character or `WEOF` if an error has occurred or the end of file reached.


###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.29.3.7 The getwchar function (p: 424)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.3.7 The getwchar function (p: 369-370)

 ###  See also

 

|  |  |
| --- | --- |
|  [getchar](getchar "c/io/getchar") |  reads a character from `[stdin](std_streams "c/io/std streams")`  (function) |
|  [fgetwcgetwc](fgetwc "c/io/fgetwc")
(C95) |  gets a wide character from a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/getwchar "cpp/io/c/getwchar") for `getwchar` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/getwchar>

putwchar
========

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
wint_t putwchar( wchar_t ch );
```
 |  | (since C95) |

 Writes a wide character `ch` to `stdout`.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ch  |  -  |  wide character to be written  |

 ###  Return value

 `ch` on success, `WEOF` on failure.


###  Example

  
```
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
 
int main()
{
    setlocale(LC_ALL, "en_US.utf8");
 
    const wchar_t data[] =
    {
        L'\u2200', // Unicode name: "FOR ALL"
        L'∀',
        L'\n',
    };
 
    for (size_t t = 0; t != (sizeof data / sizeof(wchar_t)); ++t)
    {
        if (putwchar(data[t]) == WEOF)
        {
            puts("I/O error in putwchar");
            return EXIT_FAILURE;
        }
    }
 
    return EXIT_SUCCESS;
}
```
 Possible output:



```
∀∀
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.31.3.9 The putwchar function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.29.3.9 The putwchar function (p: 310)

* C11 standard (ISO/IEC 9899:2011):
+ 7.29.3.9 The putwchar function (p: 425)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.3.9 The putwchar function (p: 370)

 ###  See also

 

|  |  |
| --- | --- |
|  [putchar](putchar "c/io/putchar") |  writes a character to `stdout`  (function) |
|  [fputwcputwc](fputwc "c/io/fputwc")
(C95) |  writes a wide character to a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/putwchar "cpp/io/c/putwchar") for `putwchar` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/putwchar>

fputwc, putwc
=============

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
wint_t fputwc( wchar_t ch, FILE *stream );
```
 |  | (since C95) |
| 
```
wint_t putwc( wchar_t ch, FILE *stream );
```
 |  | (since C95) |

 Writes a wide character `ch` to the given output stream `stream`. `putwc()` may be implemented as a macro and may evaluate `stream` more than once.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ch  |  -  |  wide character to be written  |
|  stream  |  -  |  the output stream  |

 ###  Return value

 Returns a copy of `ch` on success.


On failure, returns `WEOF` and sets the *error* indicator (see `[ferror()](ferror "c/io/ferror")`) on `stream`.


If an encoding error occurred, additionally sets `[errno](../error/errno "c/error/errno")` to `[EILSEQ](../error/errno_macros "c/error/errno macros")`.


###  Example

  
```
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <errno.h>
 
int main(void)
{
    setlocale(LC_ALL, "en_US.utf8");
 
    errno = 0;
    if (fputwc(L'🍌', stdout) == WEOF) {
        if (errno == EILSEQ)
            puts("Encoding error in fputwc.");
        else
            puts("I/O error in fputwc.");
        return EXIT_FAILURE;
    }
}
```
 Possible output:



```
🍌
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.31.3.3 The fputwc function (p: 430)
+ 7.31.3.8 The putwc function (p: 431-432)

* C17 standard (ISO/IEC 9899:2018):
+ 7.29.3.3 The fputwc function (p: 308)
+ 7.29.3.8 The putwc function (p: 310)

* C11 standard (ISO/IEC 9899:2011):
+ 7.29.3.3 The fputwc function (p: 422-423)
+ 7.29.3.8 The putwc function (p: 424)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.3.3 The fputwc function (p: 368)
+ 7.24.3.8 The putwc function (p: 370)

 ###  See also

 

|  |  |
| --- | --- |
|  [fputcputc](fputc "c/io/fputc") |  writes a character to a file stream  (function) |
|  [fputws](fputws "c/io/fputws")
(C95) |  writes a wide string to a file stream  (function) |
|  [fgetwcgetwc](fgetwc "c/io/fgetwc")
(C95) |  gets a wide character from a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fputwc "cpp/io/c/fputwc") for `fputwc` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fputwc>

scanf, fscanf, sscanf, scanf\_s, fscanf\_s, sscanf\_s
=====================================================

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
|  | (1) |  |
| 
```
int scanf( const char          *format, ... );
```
 | (until C99) |
| 
```
int scanf( const char *restrict format, ... );
```
 | (since C99) |
|  | (2) |  |
| 
```
int fscanf( FILE          *stream, const char          *format, ... );
```
 | (until C99) |
| 
```
int fscanf( FILE *restrict stream, const char *restrict format, ... );
```
 | (since C99) |
|  | (3) |  |
| 
```
int sscanf( const char          *buffer, const char          *format, ... );
```
 | (until C99) |
| 
```
int sscanf( const char *restrict buffer, const char *restrict format, ... );
```
 | (since C99) |
| 
```
int scanf_s(const char *restrict format, ...);
```
 |  (4)  | (since C11) |
| 
```
int fscanf_s(FILE *restrict stream, const char *restrict format, ...);
```
 |  (5)  | (since C11) |
| 
```
int sscanf_s(const char *restrict buffer, const char *restrict format, ...);
```
 |  (6)  | (since C11) |

 Reads data from a variety of sources, interprets it according to `format` and stores the results into given locations.



1) reads the data from `[stdin](std_streams "c/io/std streams")`
 
2) reads the data from file stream `stream`
 
3) reads the data from null-terminated character string `buffer`. Reaching the end of the string is equivalent to reaching the end-of-file condition for `fscanf`
 
4-6) Same as (1-3), except that `%c`, `%s`, and `%[` conversion specifiers each expect two arguments (the usual pointer and a value of type `rsize_t` indicating the size of the receiving array, which may be `1` when reading with a `%c` into a single char) and 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: 

* any of the arguments of pointer type is a null pointer
* `format`, `stream`, or `buffer` is a null pointer
* the number of characters that would be written by `%c`, `%s`, or `%[`, plus the terminating null character, would exceed the second (`rsize_t`) argument provided for each of those conversion specifiers
* optionally, any other detectable error, such as unknown conversion specifier

 
As with all bounds-checked functions, `scanf_s` , `fscanf_s`, and `sscanf_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 [`<stdio.h>`](../io "c/io").

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  input file stream to read from  |
|  buffer  |  -  |  pointer to a null-terminated character string to read from  |
|  format  |  -  |  pointer to a null-terminated character string specifying how to read the input  |
|  ...  |  -  |  receiving arguments.  |

   
 The **format** string consists of.


* non-whitespace multibyte characters except `%`: each such character in the format string consumes exactly one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal.
* whitespace characters: any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling [`isspace`](../string/byte/isspace "c/string/byte/isspace") in a loop). Note that there is no difference between `"\n"`, `" "`, `"\t\t"`, or other whitespace in the format string.
* conversion specifications. Each conversion specification has the following format:
+ introductory `%` character
+ (optional) assignment-suppressing character `*`. If this option is present, the function does not assign the result of the conversion to any receiving argument.
+ (optional) integer number (greater than zero) that specifies *maximum field width*, that is, the maximum number of characters that the function is allowed to consume when doing the conversion specified by the current conversion specification. Note that `%s` and `%[` may lead to buffer overflow if the width is not provided.
+ (optional) *length modifier* that specifies the size of the receiving argument, that is, the actual destination type. This affects the conversion accuracy and overflow rules. The default destination type is different for each conversion type (see table below).
+ conversion format specifier

 The following format specifiers are available:




|  Conversion specifier  |  Explanation  |  Argument type  |
| --- | --- | --- |
| **Length modifier →** | `hh` (C99). | `h` |  (none)  | `l` | `ll` (C99). | `j` (C99). | `z` (C99). | `t` (C99). | `L` |
| `%` |  matches literal `%` | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A |
| `c` |  matches a **character** or a sequence of **characters** If a width specifier is used, matches exactly *width* characters (the argument must be a pointer to an array with sufficient room). Unlike %s and %[, does not append the null character to the array. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A |
| `s` |  matches a sequence of non-whitespace characters (a **string**) If width specifier is used, matches up to *width* or until the first whitespace character, whichever appears first. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). |
| `[`set`]` |  matches a non-empty sequence of character from set of characters. If the first character of the set is `^`, then all characters not in the set are matched. If the set begins with `]` or `^]` then the `]` character is also included into the set. It is implementation-defined whether the character `-` in the non-initial position in the scanset may be indicating a range, as in `[0-9]`. If width specifier is used, matches only up to *width*. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). |
| `d` |  matches a **decimal integer**. The format of the number is the same as expected by [`strtol`](../string/byte/strtol "c/string/byte/strtol") with the value `10` for the `base` argument. | 
`signed char*` or `unsigned char*`
 | 
`signed short*` or `unsigned short*`
 | 
`signed int*` or `unsigned int*`
 | 
`signed long*` or `unsigned long*`
 | 
`signed long long*` or `unsigned long long*`
 | 
`[intmax\_t](http://en.cppreference.com/w/c/types/integer)\*` or `[uintmax\_t](http://en.cppreference.com/w/c/types/integer)\*`
 | `[size\_t](http://en.cppreference.com/w/c/types/size_t)\*` | `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)\*` | N/A |
| `i` |  matches an **integer**. The format of the number is the same as expected by [`strtol`](../string/byte/strtol "c/string/byte/strtol") with the value `​0​` for the `base` argument (base is determined by the first characters parsed). |
| `u` |  matches an unsigned **decimal integer**. The format of the number is the same as expected by [`strtoul`](../string/byte/strtoul "c/string/byte/strtoul") with the value `10` for the `base` argument. |
| `o` |  matches an unsigned **octal integer**. The format of the number is the same as expected by [`strtoul`](../string/byte/strtoul "c/string/byte/strtoul") with the value `8` for the `base` argument. |
| `x`, `X` |  matches an unsigned **hexadecimal integer**. The format of the number is the same as expected by [`strtoul`](../string/byte/strtoul "c/string/byte/strtoul") with the value `16` for the `base` argument. |
| `n` |  returns the **number of characters read so far**. No input is consumed. Does not increment the assignment count. If the specifier has assignment-suppressing operator defined, the behavior is undefined. |
| `a`, `A`(C99) `e`, `E` `f`, `F` `g`, `G` |  matches a **floating-point number**. The format of the number is the same as expected by [`strtof`](../string/byte/strtof "c/string/byte/strtof"). | N/A | N/A | `float*` | `double*` | N/A | N/A | N/A | N/A | `long double*` |
| `p` |  matches implementation defined character sequence defining a **pointer**. `printf` family of functions should produce the same sequence using `%p` format specifier. | N/A | N/A | `void**` | N/A | N/A | N/A | N/A | N/A | N/A |

 For every conversion specifier other than `n`, the longest sequence of input characters which does not exceed any specified ﬁeld width and which either is exactly what the conversion specifier expects or is a prefix of a sequence it would expect, is what's consumed from the stream. The ﬁrst character, if any, after this consumed sequence remains unread. If the consumed sequence has length zero or if the consumed sequence cannot be converted as specified above, the matching failure occurs unless end-of-ﬁle, an encoding error, or a read error prevented input from the stream, in which case it is an input failure.


All conversion specifiers other than `[`, `c`, and `n` consume and discard all leading whitespace characters (determined as if by calling [`isspace`](../string/byte/isspace "c/string/byte/isspace")) before attempting to parse the input. These consumed characters do not count towards the specified maximum field width.


The conversion specifiers `lc`, `ls`, and `l[` perform multibyte-to-wide character conversion as if by calling [`mbrtowc`](../string/multibyte/mbrtowc "c/string/multibyte/mbrtowc") with an [`mbstate_t`](../string/multibyte/mbstate_t "c/string/multibyte/mbstate t") object initialized to zero before the first character is converted.


The conversion specifiers `s` and `[` always store the null terminator in addition to the matched characters. The size of the destination array must be at least one greater than the specified field width. The use of `%s` or `%[`, without specifying the destination array size, is as unsafe as `[gets](gets "c/io/gets")`.


The correct conversion specifications for the [fixed-width integer types](../types/integer "c/types/integer") (`[int8\_t](../types/integer "c/types/integer")`, etc) are defined in the header [`<inttypes.h>`](../types/integer "c/types/integer") (although [`SCNdMAX`](../types/integer "c/types/integer"), [`SCNuMAX`](../types/integer "c/types/integer"), etc is synonymous with `%jd`, `%ju`, etc).


There is a [sequence point](../language/eval_order "c/language/eval order") after the action of each conversion specifier; this permits storing multiple fields in the same "sink" variable.


When parsing an incomplete floating-point value that ends in the exponent with no digits, such as parsing `"100er"` with the conversion specifier `%f`, the sequence `"100e"` (the longest prefix of a possibly valid floating-point number) is consumed, resulting in a matching error (the consumed sequence cannot be converted to a floating-point number), with `"r"` remaining. Some existing implementations do not follow this rule and roll back to consume only `"100"`, leaving `"er"`, e.g. [glibc bug 1765](https://sourceware.org/bugzilla/show_bug.cgi?id=1765).


If a conversion specification is invalid, the behavior is undefined.


###  Return value

 
1-3) Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or `[EOF](../io "c/io")` if input failure occurs before the first receiving argument was assigned. 
4-6) Same as (1-3), except that `[EOF](../io "c/io")` is also returned if there is a runtime constraint violation. ###  Complexity

 Not guaranteed. Notably, some implementations of `sscanf` are O(N), where `N = [strlen](http://en.cppreference.com/w/c/string/byte/strlen)(buffer)` [[1]](https://sourceware.org/bugzilla/show_bug.cgi?id=17577).


###  Notes

 Because most conversion specifiers first consume all consecutive whitespace, code such as.



```
scanf("%d", &a);
scanf("%d", &b);
```
 will read two integers that are entered on different lines (second `%d` will consume the newline left over by the first) or on the same line, separated by spaces or tabs (second `%d` will consume the spaces or tabs). The conversion specifiers that do not consume leading whitespace, such as `%c`, can be made to do so by using a whitespace character in the format string:



```
scanf("%d", &a);
scanf(" %c", &c); // consume all consecutive whitespace after %d, then read a char
```
 ###  Example

  
```
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <stddef.h>
#include <locale.h>
 
int main(void)
{
    int i, j;
    float x, y;
    char str1[10], str2[4];
    wchar_t warr[2];
    setlocale(LC_ALL, "en_US.utf8");
 
    char input[] = "25 54.32E-1 Thompson 56789 0123 56ß水";
    /* parse as follows:
       %d: an integer
       %f: a floating-point value
       %9s: a string of at most 9 non-whitespace characters
       %2d: two-digit integer (digits 5 and 6)
       %f:  a floating-point value (digits 7, 8, 9)
       %*d: an integer which isn't stored anywhere
       ' ': all consecutive whitespace
       %3[0-9]: a string of at most 3 decimal digits (digits 5 and 6)
       %2lc: two wide characters, using multibyte to wide conversion  */
    int ret = sscanf(input, "%d%f%9s%2d%f%*d %3[0-9]%2lc",
                     &i, &x, str1, &j, &y, str2, warr);
 
    printf("Converted %d fields:\n"
           "i = %d\n"
           "x = %f\n"
           "str1 = %s\n"
           "j = %d\n"
           "y = %f\n"
           "str2 = %s\n"
           "warr[0] = U+%x\n"
           "warr[1] = U+%x\n",
           ret, i, x, str1, j, y, str2, warr[0], warr[1]);
 
#ifdef __STDC_LIB_EXT1__
    int n = sscanf_s(input, "%d%f%s", &i, &x, str1, (rsize_t)sizeof str1);
    // writes 25 to i, 5.432 to x, the 9 bytes "Thompson\0" to str1, and 3 to n.
#endif
}
```
 Possible output:



```
Converted 7 fields:
i = 25
x = 5.432000
str1 = Thompson
j = 56
y = 789.000000
str2 = 56
warr[0] = U+df
warr[1] = U+6c34
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.6.2 The fscanf function (p: 231-236)
+ 7.21.6.4 The scanf function (p: 236-237)
+ 7.21.6.7 The sscanf function (p: 238-239)
+ K.3.5.3.2 The fscanf\_s function (p: 430-431)
+ K.3.5.3.4 The scanf\_s function (p: 432)
+ K.3.5.3.7 The sscanf\_s function (p: 433)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.6.2 The fscanf function (p: 317-324)
+ 7.21.6.4 The scanf function (p: 325)
+ 7.21.6.7 The sscanf function (p: 326)
+ K.3.5.3.2 The fscanf\_s function (p: 592-593)
+ K.3.5.3.4 The scanf\_s function (p: 594)
+ K.3.5.3.7 The sscanf\_s function (p: 596)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.6.2 The fscanf function (p: 282-289)
+ 7.19.6.4 The scanf function (p: 290)
+ 7.19.6.7 The sscanf function (p: 291)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.6.2 The fscanf function
+ 4.9.6.4 The scanf function
+ 4.9.6.6 The sscanf function

 ###  See also

 

|  |  |
| --- | --- |
|  [vscanfvfscanfvsscanfvscanf\_svfscanf\_svsscanf\_s](vfscanf "c/io/vfscanf")
(C99)(C99)(C99)(C11)(C11)(C11) |  reads formatted input from `[stdin](std_streams "c/io/std streams")`, a file stream or a buffer using variable argument list  (function) |
|  [fgets](fgets "c/io/fgets") |  gets a character string from a file stream  (function) |
|  [printffprintfsprintfsnprintfprintf\_sfprintf\_ssprintf\_ssnprintf\_s](fprintf "c/io/fprintf")
(C99)(C11)(C11)(C11)(C11) |  prints formatted output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fscanf "cpp/io/c/fscanf") for `scanf, fscanf, sscanf` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fscanf>

wscanf, fwscanf, swscanf, wscanf\_s, fwscanf\_s, swscanf\_s
===========================================================

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
|  | (1) |  |
| 
```
int wscanf( const wchar_t *format, ... );
```
 | (since C95) (until C99) |
| 
```
int wscanf( const wchar_t *restrict format, ... );
```
 | (since C99) |
|  | (2) |  |
| 
```
int fwscanf( FILE *stream, const wchar_t *format, ... );
```
 | (since C95) (until C99) |
| 
```
int fwscanf( FILE *restrict stream,
             const wchar_t *restrict format, ... );
```
 | (since C99) |
|  | (3) |  |
| 
```
int swscanf( const wchar_t *buffer, const wchar_t *format, ... );
```
 | (since C95) (until C99) |
| 
```
int swscanf( const wchar_t *restrict buffer,
             const wchar_t *restrict format, ... );
```
 | (since C99) |
| 
```
int wscanf_s( const wchar_t *restrict format, ...);
```
 |  (4)  | (since C11) |
| 
```
int fwscanf_s( FILE *restrict stream,
               const wchar_t *restrict format, ...);
```
 |  (5)  | (since C11) |
| 
```
int swscanf_s( const wchar_t *restrict s,
               const wchar_t *restrict format, ...);
```
 |  (6)  | (since C11) |

 Reads data from the a variety of sources, interprets it according to `format` and stores the results into given locations.



1) Reads the data from `[stdin](std_streams "c/io/std streams")`. 
2) Reads the data from file stream `stream`. 
3) Reads the data from null-terminated wide string `buffer`. Reaching the end of the string is equivalent to reaching the end-of-file condition for `fwscanf`
 
4-6) Same as (1-3), except that `%c`, `%s`, and `%[` conversion specifiers each expect two arguments (the usual pointer and a value of type `rsize_t` indicating the size of the receiving array, which may be `1` when reading with a `%lc` into a single wide character) and 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: 

* any of the arguments of pointer type is a null pointer
* `format`, `stream`, or `buffer` is a null pointer
* the number of characters that would be written by `%c`, `%s`, or `%[`, plus the terminating null character, would exceed the second (`rsize_t`) argument provided for each of those conversion specifiers
* optionally, any other detectable error, such as unknown conversion specifier

 
As all bounds-checked functions, `wscanf_s`, `fwscanf_s`, and `swscanf_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 [`<wchar.h>`](../string/wide "c/string/wide").

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  input file stream to read from  |
|  buffer  |  -  |  pointer to a null-terminated wide string to read from  |
|  format  |  -  |  pointer to a null-terminated wide string specifying how to read the input  |
|  ...  |  -  |  receiving arguments.  |

   
 The **format** string consists of.


* non-whitespace wide characters except `%`: each such character in the format string consumes exactly one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal.
* whitespace characters: any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling [`iswspace`](../string/wide/iswspace "c/string/wide/iswspace") in a loop). Note that there is no difference between `"\n"`, `" "`, `"\t\t"`, or other whitespace in the format string.
* conversion specifications. Each conversion specification has the following format:
+ introductory `%` character
+ (optional) assignment-suppressing character `*`. If this option is present, the function does not assign the result of the conversion to any receiving argument.
+ (optional) integer number (greater than zero) that specifies *maximum field width*, that is, the maximum number of characters that the function is allowed to consume when doing the conversion specified by the current conversion specification. Note that `%s` and `%[` may lead to buffer overflow if the width is not provided.
+ (optional) *length modifier* that specifies the size of the receiving argument, that is, the actual destination type. This affects the conversion accuracy and overflow rules. The default destination type is different for each conversion type (see table below).
+ conversion format specifier

 The following format specifiers are available:




|  Conversion specifier  |  Explanation  |  Argument type  |
| --- | --- | --- |
| **Length modifier →** | `hh` (C99). | `h` |  (none)  | `l` | `ll` (C99). | `j` (C99). | `z` (C99). | `t` (C99). | `L` |
| `%` |  matches literal `%` | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A |
| `c` |  matches a **character** or a sequence of **characters** If a width specifier is used, matches exactly *width* wide characters (the argument must be a pointer to an array with sufficient room). Unlike %s and %[, does not append the null character to the array. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A |
| `s` |  matches a sequence of non-whitespace characters (a **string**) If width specifier is used, matches up to *width* or until the first whitespace character, whichever appears first. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). |
| `[`set`]` |  matches a non-empty sequence of character from set of characters. If the first character of the set is `^`, then all characters not in the set are matched. If the set begins with `]` or `^]` then the `]` character is also included into the set. It is implementation-defined whether the character `-` in the non-initial position in the scanset may be indicating a range, as in `[0-9]`. If width specifier is used, matches only up to *width*. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). |
| `d` |  matches a **decimal integer**. The format of the number is the same as expected by [`wcstol`](../string/wide/wcstol "c/string/wide/wcstol") with the value `10` for the `base` argument. | 
`signed char*` or `unsigned char*`
 | 
`signed short*` or `unsigned short*`
 | 
`signed int*` or `unsigned int*`
 | 
`signed long*` or `unsigned long*`
 | 
`signed long long*` or `unsigned long long*`
 | 
`[intmax\_t](http://en.cppreference.com/w/c/types/integer)\*` or `[uintmax\_t](http://en.cppreference.com/w/c/types/integer)\*`
 | `[size\_t](http://en.cppreference.com/w/c/types/size_t)\*` | `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)\*` | N/A |
| `i` |  matches an **integer**. The format of the number is the same as expected by [`wcstol`](../string/wide/wcstol "c/string/wide/wcstol") with the value `​0​` for the `base` argument (base is determined by the first characters parsed). |
| `u` |  matches an unsigned **decimal integer**. The format of the number is the same as expected by [`wcstoul`](../string/wide/wcstoul "c/string/wide/wcstoul") with the value `10` for the `base` argument. |
| `o` |  matches an unsigned **octal integer**. The format of the number is the same as expected by [`wcstoul`](../string/wide/wcstoul "c/string/wide/wcstoul") with the value `8` for the `base` argument. |
| `x`, `X` |  matches an unsigned **hexadecimal integer**. The format of the number is the same as expected by [`wcstoul`](../string/wide/wcstoul "c/string/wide/wcstoul") with the value `16` for the `base` argument. |
| `n` |  returns the **number of characters read so far**. No input is consumed. Does not increment the assignment count. If the specifier has assignment-suppressing operator defined, the behavior is undefined. |
| `a`, `A`(C99) `e`, `E` `f`, `F` `g`, `G` |  matches a **floating-point number**. The format of the number is the same as expected by [`wcstof`](../string/wide/wcstof "c/string/wide/wcstof"). | N/A | N/A | `float*` | `double*` | N/A | N/A | N/A | N/A | `long double*` |
| `p` |  matches implementation defined character sequence defining a **pointer**. `printf` family of functions should produce the same sequence using `%p` format specifier. | N/A | N/A | `void**` | N/A | N/A | N/A | N/A | N/A | N/A |

 For every conversion specifier other than `n`, the longest sequence of input characters which does not exceed any specified ﬁeld width and which either is exactly what the conversion specifier expects or is a prefix of a sequence it would expect, is what's consumed from the stream. The ﬁrst character, if any, after this consumed sequence remains unread. If the consumed sequence has length zero or if the consumed sequence cannot be converted as specified above, the matching failure occurs unless end-of-ﬁle, an encoding error, or a read error prevented input from the stream, in which case it is an input failure.


All conversion specifiers other than `[`, `c`, and `n` consume and discard all leading whitespace characters (determined as if by calling [`iswspace`](../string/wide/iswspace "c/string/wide/iswspace")) before attempting to parse the input. These consumed characters do not count towards the specified maximum field width.


If the length specifier `l` is not used, the conversion specifiers `c`, `s`, and `[` perform wide-to-multibyte character conversion as if by calling [`wcrtomb`](../string/multibyte/wcrtomb "c/string/multibyte/wcrtomb") with an [`mbstate_t`](../string/multibyte/mbstate_t "c/string/multibyte/mbstate t") object initialized to zero before the first character is converted.


The conversion specifiers `s` and `[` always store the null terminator in addition to the matched characters. The size of the destination array must be at least one greater than the specified field width. The use of `%s` or `%[`, without specifying the destination array size, is as unsafe as `[gets](gets "c/io/gets")`.


The correct conversion specifications for the [fixed-width integer types](../types/integer "c/types/integer") (`[int8\_t](../types/integer "c/types/integer")`, etc) are defined in the header [`<inttypes.h>`](../types/integer "c/types/integer") (although [`SCNdMAX`](../types/integer "c/types/integer"), [`SCNuMAX`](../types/integer "c/types/integer"), etc is synonymous with `%jd`, `%ju`, etc).


There is a [sequence point](../language/eval_order "c/language/eval order") after the action of each conversion specifier; this permits storing multiple fields in the same "sink" variable.


When parsing an incomplete floating-point value that ends in the exponent with no digits, such as parsing `"100er"` with the conversion specifier `%f`, the sequence `"100e"` (the longest prefix of a possibly valid floating-point number) is consumed, resulting in a matching error (the consumed sequence cannot be converted to a floating-point number), with `"r"` remaining. Some existing implementations do not follow this rule and roll back to consume only `"100"`, leaving `"er"`, e.g. [glibc bug 1765](https://sourceware.org/bugzilla/show_bug.cgi?id=1765).


###  Return value

 
1-3) Number of receiving arguments successfully assigned, or `[EOF](../io "c/io")` if read failure occurs before the first receiving argument was assigned. 
4-6) Same as (1-3), except that `[EOF](../io "c/io")` is also returned if there is a runtime constraint violation. ###  Example

  
```
#include <stdio.h>
#include <wchar.h>
#include <string.h>
 
#define NUM_VARS   3
#define ERR_READ   2
#define ERR_WRITE  3
 
int main(void) {
    wchar_t state[64];
    wchar_t capital[64];
    unsigned int population = 0;
    int elevation = 0;
    int age = 0;
    float pi = 0;
 
#if INTERACTIVE_MODE
    wprintf(L"Enter state, age, and pi value: ");
    if (wscanf(L"%ls%d%f", state, &age, &pi) != NUM_VARS) {
        fprintf(stderr, "Error reading input.\n");
        return ERR_READ;
    }
#else
    wchar_t* input = L"California 170 3.141592";
    if (swscanf(input, L"%ls%d%f", state, &age, &pi) != NUM_VARS) {
        fprintf(stderr, "Error reading input.\n");
        return ERR_READ;
    }
#endif
    wprintf(L"State: %ls\nAge  : %d years\nPi   : %.5f\n\n", state, age, pi);
 
    FILE* fp = tmpfile();
    if (fp) {
        // write some data to temp file
        if (!fwprintf(fp, L"Mississippi Jackson 420000 807")) {
            fprintf(stderr, "Error writing to file.\n");
            fclose(fp);
            return ERR_WRITE;
        }
        // rewind file pointer
        rewind(fp);
 
        // read data into variables
        fwscanf(fp, L"%ls%ls%u%d", state, capital, &population, &elevation);
        wprintf(L"State  : %ls\nCapital: %ls\nJackson population (in 2020): %u\n"
                L"Highest elevation: %dft\n",
                state, capital, population, elevation);
        fclose(fp);
    }
}
```
 Possible output:



```
State: California
Age  : 170 years
Pi   : 3.14159
 
State  : Mississippi
Capital: Jackson
Jackson population (in 2020): 420000
Highest elevation: 807ft
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.29.2.2 The fwscanf function (p: 410-416)
+ 7.29.2.4 The swscanf function (p: 417)
+ 7.29.2.12 The wscanf function (p: 421)
+ K.3.9.1.2 The fwscanf\_s function (p: 628-629)
+ K.3.9.1.5 The swscanf\_s function (p: 631)
+ K.3.9.1.14 The wscanf\_s function (p: 638)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.2.2 The fwscanf function (p: 356-362)
+ 7.24.2.4 The swscanf function (p: 362)
+ 7.24.2.12 The wscanf function (p: 366-367)

 ###  See also

 

|  |  |
| --- | --- |
|  [vwscanfvfwscanfvswscanfvwscanf\_svfwscanf\_svswscanf\_s](vfwscanf "c/io/vfwscanf")
(C99)(C99)(C99)(C11)(C11)(C11) |  reads formatted wide character input from `[stdin](std_streams "c/io/std streams")`, a file stream or a buffer using variable argument list  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fwscanf "cpp/io/c/fwscanf") for `wscanf, fwscanf, swscanf` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fwscanf>

vscanf, vfscanf, vsscanf, vscanf\_s, vfscanf\_s, vsscanf\_s
===========================================================

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int vscanf( const char *restrict format, va_list vlist );
```
 |  (1)  | (since C99) |
| 
```
int vfscanf( FILE *restrict stream, const char *restrict format, 
             va_list vlist );
```
 |  (2)  | (since C99) |
| 
```
int vsscanf( const char *restrict buffer, const char *restrict format, 
             va_list vlist );
```
 |  (3)  | (since C99) |
| 
```
int vscanf_s(const char *restrict format, va_list vlist);
```
 |  (4)  | (since C11) |
| 
```
int vfscanf_s( FILE *restrict stream, const char *restrict format,
               va_list vlist);
```
 |  (5)  | (since C11) |
| 
```
int vsscanf_s( const char *restrict buffer, const char *restrict format,
               va_list vlist);
```
 |  (6)  | (since C11) |

 Reads data from the a variety of sources, interprets it according to `format` and stores the results into locations defined by `vlist`.



1) Reads the data from `[stdin](std_streams "c/io/std streams")`
 
2) Reads the data from file stream `stream`
 
3) Reads the data from null-terminated character string `buffer`. Reaching the end of the string is equivalent to reaching the end-of-file condition for `fscanf`
 
4-6) Same as (1-3), except that `%c`, `%s`, and `%[` conversion specifiers each expect two arguments (the usual pointer and a value of type `rsize_t` indicating the size of the receiving array, which may be 1 when reading with a %c into a single char) and 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: 

* any of the arguments of pointer type is a null pointer
* `format`, `stream`, or `buffer` is a null pointer
* the number of characters that would be written by %c, %s, or %[, plus the terminating null character, would exceed the second (rsize\_t) argument provided for each of those conversion specifiers
* optionally, any other detectable error, such as unknown conversion specifier

 
As with all bounds-checked functions, `vscanf_s` , `vfscanf_s`, and `vsscanf_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 [`<stdio.h>`](../io "c/io").

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  input file stream to read from  |
|  buffer  |  -  |  pointer to a null-terminated character string to read from  |
|  format  |  -  |  pointer to a null-terminated character string specifying how to read the input  |
|  vlist  |  -  |  variable argument list containing the receiving arguments.  |

   
 The **format** string consists of.


* non-whitespace multibyte characters except `%`: each such character in the format string consumes exactly one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal.
* whitespace characters: any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling [`isspace`](../string/byte/isspace "c/string/byte/isspace") in a loop). Note that there is no difference between `"\n"`, `" "`, `"\t\t"`, or other whitespace in the format string.
* conversion specifications. Each conversion specification has the following format:
+ introductory `%` character
+ (optional) assignment-suppressing character `*`. If this option is present, the function does not assign the result of the conversion to any receiving argument.
+ (optional) integer number (greater than zero) that specifies *maximum field width*, that is, the maximum number of characters that the function is allowed to consume when doing the conversion specified by the current conversion specification. Note that `%s` and `%[` may lead to buffer overflow if the width is not provided.
+ (optional) *length modifier* that specifies the size of the receiving argument, that is, the actual destination type. This affects the conversion accuracy and overflow rules. The default destination type is different for each conversion type (see table below).
+ conversion format specifier

 The following format specifiers are available:




|  Conversion specifier  |  Explanation  |  Argument type  |
| --- | --- | --- |
| **Length modifier →** | `hh` (C99). | `h` |  (none)  | `l` | `ll` (C99). | `j` (C99). | `z` (C99). | `t` (C99). | `L` |
| `%` |  matches literal `%` | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A |
| `c` |  matches a **character** or a sequence of **characters** If a width specifier is used, matches exactly *width* characters (the argument must be a pointer to an array with sufficient room). Unlike %s and %[, does not append the null character to the array. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A |
| `s` |  matches a sequence of non-whitespace characters (a **string**) If width specifier is used, matches up to *width* or until the first whitespace character, whichever appears first. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). |
| `[`set`]` |  matches a non-empty sequence of character from set of characters. If the first character of the set is `^`, then all characters not in the set are matched. If the set begins with `]` or `^]` then the `]` character is also included into the set. It is implementation-defined whether the character `-` in the non-initial position in the scanset may be indicating a range, as in `[0-9]`. If width specifier is used, matches only up to *width*. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). |
| `d` |  matches a **decimal integer**. The format of the number is the same as expected by [`strtol`](../string/byte/strtol "c/string/byte/strtol") with the value `10` for the `base` argument. | 
`signed char*` or `unsigned char*`
 | 
`signed short*` or `unsigned short*`
 | 
`signed int*` or `unsigned int*`
 | 
`signed long*` or `unsigned long*`
 | 
`signed long long*` or `unsigned long long*`
 | 
`[intmax\_t](http://en.cppreference.com/w/c/types/integer)\*` or `[uintmax\_t](http://en.cppreference.com/w/c/types/integer)\*`
 | `[size\_t](http://en.cppreference.com/w/c/types/size_t)\*` | `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)\*` | N/A |
| `i` |  matches an **integer**. The format of the number is the same as expected by [`strtol`](../string/byte/strtol "c/string/byte/strtol") with the value `​0​` for the `base` argument (base is determined by the first characters parsed). |
| `u` |  matches an unsigned **decimal integer**. The format of the number is the same as expected by [`strtoul`](../string/byte/strtoul "c/string/byte/strtoul") with the value `10` for the `base` argument. |
| `o` |  matches an unsigned **octal integer**. The format of the number is the same as expected by [`strtoul`](../string/byte/strtoul "c/string/byte/strtoul") with the value `8` for the `base` argument. |
| `x`, `X` |  matches an unsigned **hexadecimal integer**. The format of the number is the same as expected by [`strtoul`](../string/byte/strtoul "c/string/byte/strtoul") with the value `16` for the `base` argument. |
| `n` |  returns the **number of characters read so far**. No input is consumed. Does not increment the assignment count. If the specifier has assignment-suppressing operator defined, the behavior is undefined. |
| `a`, `A`(C99) `e`, `E` `f`, `F` `g`, `G` |  matches a **floating-point number**. The format of the number is the same as expected by [`strtof`](../string/byte/strtof "c/string/byte/strtof"). | N/A | N/A | `float*` | `double*` | N/A | N/A | N/A | N/A | `long double*` |
| `p` |  matches implementation defined character sequence defining a **pointer**. `printf` family of functions should produce the same sequence using `%p` format specifier. | N/A | N/A | `void**` | N/A | N/A | N/A | N/A | N/A | N/A |

 For every conversion specifier other than `n`, the longest sequence of input characters which does not exceed any specified ﬁeld width and which either is exactly what the conversion specifier expects or is a prefix of a sequence it would expect, is what's consumed from the stream. The ﬁrst character, if any, after this consumed sequence remains unread. If the consumed sequence has length zero or if the consumed sequence cannot be converted as specified above, the matching failure occurs unless end-of-ﬁle, an encoding error, or a read error prevented input from the stream, in which case it is an input failure.


All conversion specifiers other than `[`, `c`, and `n` consume and discard all leading whitespace characters (determined as if by calling [`isspace`](../string/byte/isspace "c/string/byte/isspace")) before attempting to parse the input. These consumed characters do not count towards the specified maximum field width.


The conversion specifiers `lc`, `ls`, and `l[` perform multibyte-to-wide character conversion as if by calling [`mbrtowc`](../string/multibyte/mbrtowc "c/string/multibyte/mbrtowc") with an [`mbstate_t`](../string/multibyte/mbstate_t "c/string/multibyte/mbstate t") object initialized to zero before the first character is converted.


The conversion specifiers `s` and `[` always store the null terminator in addition to the matched characters. The size of the destination array must be at least one greater than the specified field width. The use of `%s` or `%[`, without specifying the destination array size, is as unsafe as `[gets](gets "c/io/gets")`.


The correct conversion specifications for the [fixed-width integer types](../types/integer "c/types/integer") (`[int8\_t](../types/integer "c/types/integer")`, etc) are defined in the header [`<inttypes.h>`](../types/integer "c/types/integer") (although [`SCNdMAX`](../types/integer "c/types/integer"), [`SCNuMAX`](../types/integer "c/types/integer"), etc is synonymous with `%jd`, `%ju`, etc).


There is a [sequence point](../language/eval_order "c/language/eval order") after the action of each conversion specifier; this permits storing multiple fields in the same "sink" variable.


When parsing an incomplete floating-point value that ends in the exponent with no digits, such as parsing `"100er"` with the conversion specifier `%f`, the sequence `"100e"` (the longest prefix of a possibly valid floating-point number) is consumed, resulting in a matching error (the consumed sequence cannot be converted to a floating-point number), with `"r"` remaining. Some existing implementations do not follow this rule and roll back to consume only `"100"`, leaving `"er"`, e.g. [glibc bug 1765](https://sourceware.org/bugzilla/show_bug.cgi?id=1765).


###  Return value

 
1-3) Number of receiving arguments successfully assigned, or `[EOF](../io "c/io")` if read failure occurs before the first receiving argument was assigned. 
4-6) Same as (1-3), except that `[EOF](../io "c/io")` is also returned if there is a runtime constraint violation. ###  Notes

 All these functions invoke `va_arg` at least once, the value of `arg` is indeterminate after the return. These functions to not invoke `va_end`, and it must be done by the caller.


###  Example

  
```
#include <stdio.h>
#include <stdbool.h>
#include <stdarg.h>
 
bool checked_sscanf(int count, const char* buf, const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    int rc = vsscanf(buf, fmt, ap);
    va_end(ap);
    return rc == count;
}
 
int main(void)
{
    int n, m;
 
    printf("Parsing '1 2'...");
    if(checked_sscanf(2, "1 2", "%d %d", &n, &m))
        puts("success");
    else
        puts("failure");
 
    printf("Parsing '1 a'...");
    if(checked_sscanf(2, "1 a", "%d %d", &n, &m))
        puts("success");
    else
        puts("failure");
}
```
 Output:



```
Parsing '1 2'...success
Parsing '1 a'...failure
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.6.9 The vfscanf function (p: 327)
+ 7.21.6.11 The vscanf function (p: 328)
+ 7.21.6.14 The vsscanf function (p: 330)
+ K.3.5.3.9 The vfscanf\_s function (p: 597-598)
+ K.3.5.3.11 The vscanf\_s function (p: 599)
+ K.3.5.3.14 The vsscanf\_s function (p: 602)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.6.9 The vfscanf function (p: 293)
+ 7.19.6.11 The vscanf function (p: 294)
+ 7.19.6.14 The vsscanf function (p: 295)

 ###  See also

 

|  |  |
| --- | --- |
|  [scanffscanfsscanfscanf\_sfscanf\_ssscanf\_s](fscanf "c/io/fscanf")
(C11)(C11)(C11) |  reads formatted input from `[stdin](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [vprintfvfprintfvsprintfvsnprintfvprintf\_svfprintf\_svsprintf\_svsnprintf\_s](vfprintf "c/io/vfprintf")
(C99)(C11)(C11)(C11)(C11) |  prints formatted output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer using variable argument list  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/vfscanf "cpp/io/c/vfscanf") for `vscanf, vfscanf, vsscanf` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/vfscanf>

vwprintf, vfwprintf, vswprintf, vwprintf\_s, vfwprintf\_s, vswprintf\_s, vsnwprintf\_s
======================================================================================

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
|  | (1) |  |
| 
```
int vwprintf( const wchar_t *format, va_list vlist );
```
 | (since C95) (until C99) |
| 
```
int vwprintf( const wchar_t *restrict format, va_list vlist );
```
 | (since C99) |
|  | (2) |  |
| 
```
int vfwprintf( FILE* stream, const wchar_t *format, va_list vlist );
```
 | (since C95) (until C99) |
| 
```
int vfwprintf( FILE *restrict stream,
               const wchar_t *restrict format, va_list vlist );
```
 | (since C99) |
|  | (3) |  |
| 
```
int vswprintf( wchar_t *buffer, size_t bufsz,
               const wchar_t *format, va_list vlist );
```
 | (since C95) (until C99) |
| 
```
int vswprintf( wchar_t *restrict buffer, size_t bufsz,
               const wchar_t *restrict format, va_list vlist );
```
 | (since C99) |
| 
```
int vwprintf_s( const wchar_t *restrict format, va_list vlist);
```
 |  (4)  | (since C11) |
| 
```
int vfwprintf_s( FILE * restrict stream,
                 const wchar_t *restrict format, va_list vlist);
```
 |  (5)  | (since C11) |
| 
```
int vswprintf_s( wchar_t *restrict buffer, rsize_t bufsz, 
                 const wchar_t * restrict format, va_list vlist);
```
 |  (6)  | (since C11) |
| 
```
int vsnwprintf_s( wchar_t *restrict buffer, rsize_t bufsz,
                  const wchar_t *restrict format, va_list vlist);
```
 |  (7)  | (since C11) |

 Loads the data from locations, defined by `vlist`, converts them to wide string equivalents and writes the results to a variety of sinks.



1) Writes the results to `[stdout](std_streams "c/io/std streams")`. 
2) Writes the results to a file stream `stream`. 
3) Writes the results to a wide string `buffer`. At most `bufsz-1` wide characters are written followed by null wide character. The resulting wide character string will be terminated with a null wide character, unless `bufsz` is zero. 
4-6) Same as (1-3), 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: * the conversion specifier `%n` is present in `format`
* any of the arguments corresponding to `%s` is a null pointer
* `format` or `buffer` is a null pointer
* `bufsz` is zero or greater than `RSIZE_MAX/sizeof(wchar_t)`
* encoding errors occur in any of string and character conversion specifiers
* (for `vswprintf_s` only), the string to be stored in `buffer` (including the trailing wide null) would be exceed `bufsz`


 
7) Same as (6), except it will truncate the result to fit within the array pointed to by `buffer`. As with all bounds-checked functions, `vwprintf_s` , `vfwprintf_s`, `vswprintf_s`, and `vsnwprintf_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 [`<stdio.h>`](../io "c/io"). ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  output wide stream to write to  |
|  buffer  |  -  |  pointer to a wide string to write to  |
|  bufsz  |  -  |  maximum number of wide characters to write  |
|  format  |  -  |  pointer to a null-terminated wide string specifying how to interpret the data  |
|  vlist  |  -  | [variable argument list](../language/variadic "c/language/variadic") containing the data to print.  |

   
 The **format** string consists of ordinary wide characters (except `%`), which are copied unchanged into the output stream, and conversion specifications. Each conversion specification has the following format:


* introductory `%` character
* (optional) one or more flags that modify the behavior of the conversion:
+ `-`: the result of the conversion is left-justified within the field (by default it is right-justified)
+ `+`: the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative)
+ *space*: if the result of a signed conversion does not start with a sign character, or is empty, space is prepended to the result. It is ignored if `+` flag is present.
+ `#` : *alternative form* of the conversion is performed. See the table below for exact effects otherwise the behavior is undefined.
+ `0` : for integer and floating point number conversions, leading zeros are used to pad the field instead of *space* characters. For integer numbers it is ignored if the precision is explicitly specified. For other conversions using this flag results in undefined behavior. It is ignored if `-` flag is present.

* (optional) integer value or `*` that specifies minimum field width. The result is padded with *space* characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when `*` is used, the width is specified by an additional argument of type `int`, which appears before the argument to be converted and the argument supplying precision if one is supplied. If the value of the argument is negative, it results with the `-` flag specified and positive field width. (Note: This is the minimum width: The value is never truncated.)
+ (optional) `.` followed by integer number or `*`, or neither that specifies *precision* of the conversion. In the case when `*` is used, the *precision* is specified by an additional argument of type `int`, which appears before the argument to be converted, but after the argument supplying minimum field width if one is supplied. If the value of this argument is negative, it is ignored. If neither a number nor `*` is used, the precision is taken as zero. See the table below for exact effects of *precision*.
+ (optional) *length modifier* that specifies the size of the argument (in combination with the conversion format specifier, it specifies the type of the corresponding argument)
+ conversion format specifier

 The following format specifiers are available:




|  ConversionSpecifier  |  Explanation  |  ExpectedArgument Type  |
| --- | --- | --- |
| **LengthModifier****→** | `hh` (C99). | `h` |  (none)  | `l` | `ll` (C99). | `j` (C99). | `z` (C99). | `t` (C99). | `L` |
| `%` |  writes literal `%`. The full conversion specification must be `%%`.  | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A |
| `c` |  writes a **single character**. The argument is first converted to `wchar_t` as if by calling `[btowc](../string/multibyte/btowc "c/string/multibyte/btowc")`. If the **l** modifier is used, the `wint_t` argument is first converted to `wchar_t`. | N/A | N/A | `int` | `wint_t` | N/A | N/A | N/A | N/A | N/A |
| `s` |  writes a **character string** The argument must be a pointer to the initial element of a character array containing a multibyte character sequence beginning in the initial shift state, which is converted to wide character array as if by a call to `[mbrtowc](../string/multibyte/mbrtowc "c/string/multibyte/mbrtowc")` with zero-initialized conversion state. *Precision* specifies the maximum number of wide characters to be written. If *Precision* is not specified, writes every wide characters up to and not including the first null terminator. If the **l** specifier is used, the argument must be a pointer to the initial element of an array of `wchar_t`. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A |
| `d` `i` |  converts a **signed integer** into decimal representation *[-]dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | `signed char` | `short` | `int` | `long` | `long long` | `[intmax\_t](http://en.cppreference.com/w/c/types/integer)` | signed `[size\_t](http://en.cppreference.com/w/c/types/size_t)`
 | `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)` | N/A |
| `o` |  converts an **unsigned integer** into octal representation *oooo*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* precision is increased if necessary, to write one leading zero. In that case if both the converted value and the precision are `​0​`, single `​0​` is written. | `unsigned char` | `unsigned short` | `unsigned int` | `unsigned long` | `unsigned long long` | `[uintmax\_t](http://en.cppreference.com/w/c/types/integer)` | `[size\_t](http://en.cppreference.com/w/c/types/size_t)` | unsigned version of `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)`
 | N/A |
| `x` `X` |  converts an **unsigned integer** into hexadecimal representation *hhhh*. For the `x` conversion letters `abcdef` are used. For the `X` conversion letters `ABCDEF` are used. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* `0x` or `0X` is prefixed to results if the converted value is nonzero. | N/A |
| `u` |  converts an **unsigned integer** into decimal representation *dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | N/A |
| `f` `F` |  converts **floating-point number** to the decimal notation in the style *[-]ddd.ddd*. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | `double` | 
`double` (C99)
 | N/A | N/A | N/A | N/A | `long double` |
| `e` `E` |  converts **floating-point number** to the decimal exponent notation. For the `e` conversion style *[-]d.ddd*`e`*±dd* is used. For the `E` conversion style *[-]d.ddd*`E`*±dd* is used. The exponent contains at least two digits, more digits are used only if necessary. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A |
| `a` `A` (C99). |  converts **floating-point number** to the hexadecimal exponent notation. For the `a` conversion style *[-]*`0x`*h.hhh*`p`*±d* is used. For the `A` conversion style *[-]*`0X`*h.hhh*`P`*±d* is used. The first hexadecimal digit is not `0` if the argument is a normalized floating point value. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the hexadecimal point character. The default precision is sufficient for exact representation of the value. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A |
| `g` `G` |  converts **floating-point number** to decimal or decimal exponent notation depending on the value and the *precision*. For the `g` conversion style conversion with style `e` or `f` will be performed. For the `G` conversion style conversion with style `E` or `F` will be performed. Let `P` equal the precision if nonzero, `6` if the precision is not specified, or `1` if the precision is `​0​`. Then, if a conversion with style `E` would have an exponent of `X`:* if *P > X ≥ −4*, the conversion is with style `f` or `F` and precision *P − 1 − X*.
* otherwise, the conversion is with style `e` or `E` and precision *P − 1*.

Unless *alternative representation* is requested the trailing zeros are removed, also the decimal point character is removed if no fractional part is left. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A |
| `n` |  returns the **number of characters written** so far by this call to the function. The result is *written* to the value pointed to by the argument. The specification may not contain any *flag*, *field width*, or *precision*.  | `signed char*` | `short*` | `int*` | `long*` | `long long*` | `[intmax\_t](http://en.cppreference.com/w/c/types/integer)\*` | signed `[size\_t](http://en.cppreference.com/w/c/types/size_t)\*`
 | `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)\*` | N/A |
| `p` |  writes an implementation defined character sequence defining a **pointer**.  | N/A | N/A | `void*` | N/A | N/A | N/A | N/A | N/A | N/A |

 The floating point conversion functions convert infinity to `inf` or `infinity`. Which one is used is implementation defined.


Not-a-number is converted to `nan` or `nan(*char\_sequence*)`. Which one is used is implementation defined.


The conversions `F`, `E`, `G`, `A` output `INF`, `INFINITY`, `NAN` instead.


Even though `%c` expects `int` argument, it is safe to pass a `char` because of the integer promotion that takes place when a variadic function is called.


The correct conversion specifications for the fixed-width character types (`[int8\_t](../types/integer "c/types/integer")`, etc) are defined in the header [`<inttypes.h>`](../types/integer "c/types/integer") (although `[PRIdMAX](../types/integer "c/types/integer")`, `[PRIuMAX](../types/integer "c/types/integer")`, etc is synonymous with `%jd`, `%ju`, etc).


The memory-writing conversion specifier `%n` is a common target of security exploits where format strings depend on user input and is not supported by the bounds-checked `printf_s` family of functions.


There is a [sequence point](../language/eval_order "c/language/eval order") after the action of each conversion specifier; this permits storing multiple `%n` results in the same variable or, as an edge case, printing a string modified by an earlier `%n` within the same call.


If a conversion specification is invalid, the behavior is undefined.


###  Return value

 
1,4) The number of wide characters written if successful or negative value if an error occurred. 
3) The number of wide characters written if successful or negative value if an error occurred. If the resulting string gets truncated due to `bufsz` limit, function returns the total number of characters (not including the terminating null wide character) which would have been written, if the limit were not imposed.  
2,5) number of wide characters transmitted to the output stream or negative value if an output error, a runtime constraints violation error, or an encoding error occurred. 
6) number of wide characters written to `buffer`, not counting the null wide character (which is always written as long as `buffer` is not a null pointer and `bufsz` is not zero and not greater than `RSIZE_MAX/sizeof(wchar_t)`), or zero on runtime constraint violations, and negative value on encoding errors. 
7) number of wide characters not including the terminating null character (which is always written as long as `buffer` is not a null pointer and `bufsz` is not zero and not greater than `RSIZE_MAX/sizeof(wchar_t)`), which would have been written to `buffer` if `bufsz` was ignored, or a negative value if a runtime constraints violation or an encoding error occurred. ###  Notes

 All these functions invoke `va_arg` at least once, the value of `arg` is indeterminate after the return. These functions to not invoke `va_end`, and it must be done by the caller.


While narrow strings provide `[vsnprintf](vfprintf "c/io/vfprintf")`, which makes it possible to determine the required output buffer size, there is no equivalent for wide strings (until C11's vsnwprintf\_s), and in order to determine the buffer size, the program may need to call `vswprintf`, check the result value, and reallocate a larger buffer, trying again until successful.


`vsnwprintf_s`, unlike `vswprintf_s`, will truncate the result to fit within the array pointed to by `buffer`, even though truncation is treated as an error by most bounds-checked functions.


###  Example

  
```
#include <stdio.h>
#include <time.h>
#include <locale.h>
#include <stdarg.h>
#include <stddef.h>
#include <wchar.h>
 
void debug_wlog(const wchar_t *fmt, ...)
{
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    char time_buf[100];
    size_t rc = strftime(time_buf, sizeof time_buf, "%D %T", gmtime(&ts.tv_sec));
    snprintf(time_buf + rc, sizeof time_buf - rc, ".%06ld UTC", ts.tv_nsec / 1000);
 
    va_list args;
    va_start(args, fmt);
    wchar_t buf[1024];
    int rc2 = vswprintf(buf, sizeof buf / sizeof *buf, fmt, args);
    va_end(args);
 
    if(rc2 > 0)
       wprintf(L"%s [debug]: %ls\n", time_buf, buf);
    else
       wprintf(L"%s [debug]: (string too long)\n", time_buf);
}
 
int main(void)
{
    setlocale(LC_ALL, "");
    debug_wlog(L"Logging, %d, %d, %d", 1, 2, 3);
}
```
 Possible output:



```
02/20/15 22:12:38.476575 UTC [debug]: Logging, 1, 2, 3
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.29.2.5 The vfwprintf function (p: 417-418)
+ 7.29.2.7 The vswprintf function (p: 419)
+ 7.29.2.9 The vwprintf function (p: 420)
+ K.3.9.1.6 The vfwprintf\_s function (p: 632)
+ K.3.9.1.8 The vsnwprintf\_s function (p: 633-634)
+ K.3.9.1.9 The vswprintf\_s function (p: 634-635)
+ K.3.9.1.11 The vwprintf\_s function (p: 636)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.2.5 The vfwprintf function (p: 363)
+ 7.24.2.7 The vswprintf function (p: 364)
+ 7.24.2.9 The vwprintf function (p: 365)

 ###  See also

 

|  |  |
| --- | --- |
|  [vprintfvfprintfvsprintfvsnprintfvprintf\_svfprintf\_svsprintf\_svsnprintf\_s](vfprintf "c/io/vfprintf")
(C99)(C11)(C11)(C11)(C11) |  prints formatted output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer using variable argument list  (function) |
|  [wprintffwprintfswprintfwprintf\_sfwprintf\_sswprintf\_ssnwprintf\_s](fwprintf "c/io/fwprintf")
(C95)(C95)(C95)(C11)(C11)(C11)(C11) |  prints formatted wide character output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/vfwprintf "cpp/io/c/vfwprintf") for `vwprintf, vfwprintf, vswprintf` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/vfwprintf>

vwscanf, vfwscanf, vswscanf, vwscanf\_s, vfwscanf\_s, vswscanf\_s
=================================================================

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
int vwscanf( const wchar_t *restrict format, va_list vlist );
```
 |  (1)  | (since C99) |
| 
```
int vfwscanf( FILE *restrict stream,
              const wchar_t *restrict format, va_list vlist );
```
 |  (2)  | (since C99) |
| 
```
int vswscanf( const wchar_t *restrict buffer,
              const wchar_t *restrict format, va_list vlist );
```
 |  (3)  | (since C99) |
| 
```
int vwscanf_s( const wchar_t *restrict format, va_list vlist );
```
 |  (4)  | (since C11) |
| 
```
int vfwscanf_s( FILE *restrict stream,
                const wchar_t *restrict format, va_list vlist );
```
 |  (5)  | (since C11) |
| 
```
int vswscanf_s( const wchar_t *restrict buffer,
                const wchar_t *restrict format, va_list vlist );
```
 |  (6)  | (since C11) |

 Reads data from the a variety of sources, interprets it according to `format` and stores the results into locations defined by `vlist`.



1) Reads the data from `[stdin](std_streams "c/io/std streams")`. 
2) Reads the data from file stream `stream`. 
3) Reads the data from null-terminated wide string `buffer`. Reaching the end of the string is equivalent to reaching the end-of-file condition for `fwscanf`
 
4-6) Same as (1-3), except that `%c`, `%s`, and `%[` conversion specifiers each expect two arguments (the usual pointer and a value of type `rsize_t` indicating the size of the receiving array, which may be 1 when reading with a %lc into a single wide character) and 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: 

* any of the arguments of pointer type is a null pointer
* `format`, `stream`, or `buffer` is a null pointer
* the number of characters that would be written by %c, %s, or %[, plus the terminating null character, would exceed the second (rsize\_t) argument provided for each of those conversion specifiers
* optionally, any other detectable error, such as unknown conversion specifier

 
As with all bounds-checked functions, `vwscanf_s` , `vfwscanf_s`, and `vswscanf_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 [`<stdio.h>`](../io "c/io").

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  input file stream to read from  |
|  buffer  |  -  |  pointer to a null-terminated wide string to read from  |
|  format  |  -  |  pointer to a null-terminated wide string specifying how to read the input  |
|  vlist  |  -  |  variable argument list containing the receiving arguments.  |

   
 The **format** string consists of.


* non-whitespace wide characters except `%`: each such character in the format string consumes exactly one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal.
* whitespace characters: any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling [`iswspace`](../string/wide/iswspace "c/string/wide/iswspace") in a loop). Note that there is no difference between `"\n"`, `" "`, `"\t\t"`, or other whitespace in the format string.
* conversion specifications. Each conversion specification has the following format:
+ introductory `%` character
+ (optional) assignment-suppressing character `*`. If this option is present, the function does not assign the result of the conversion to any receiving argument.
+ (optional) integer number (greater than zero) that specifies *maximum field width*, that is, the maximum number of characters that the function is allowed to consume when doing the conversion specified by the current conversion specification. Note that `%s` and `%[` may lead to buffer overflow if the width is not provided.
+ (optional) *length modifier* that specifies the size of the receiving argument, that is, the actual destination type. This affects the conversion accuracy and overflow rules. The default destination type is different for each conversion type (see table below).
+ conversion format specifier

 The following format specifiers are available:




|  Conversion specifier  |  Explanation  |  Argument type  |
| --- | --- | --- |
| **Length modifier →** | `hh` (C99). | `h` |  (none)  | `l` | `ll` (C99). | `j` (C99). | `z` (C99). | `t` (C99). | `L` |
| `%` |  matches literal `%` | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A |
| `c` |  matches a **character** or a sequence of **characters** If a width specifier is used, matches exactly *width* wide characters (the argument must be a pointer to an array with sufficient room). Unlike %s and %[, does not append the null character to the array. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A |
| `s` |  matches a sequence of non-whitespace characters (a **string**) If width specifier is used, matches up to *width* or until the first whitespace character, whichever appears first. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). |
| `[`set`]` |  matches a non-empty sequence of character from set of characters. If the first character of the set is `^`, then all characters not in the set are matched. If the set begins with `]` or `^]` then the `]` character is also included into the set. It is implementation-defined whether the character `-` in the non-initial position in the scanset may be indicating a range, as in `[0-9]`. If width specifier is used, matches only up to *width*. Always stores a null character in addition to the characters matched (so the argument array must have room for at least *width+1* characters). |
| `d` |  matches a **decimal integer**. The format of the number is the same as expected by [`wcstol`](../string/wide/wcstol "c/string/wide/wcstol") with the value `10` for the `base` argument. | 
`signed char*` or `unsigned char*`
 | 
`signed short*` or `unsigned short*`
 | 
`signed int*` or `unsigned int*`
 | 
`signed long*` or `unsigned long*`
 | 
`signed long long*` or `unsigned long long*`
 | 
`[intmax\_t](http://en.cppreference.com/w/c/types/integer)\*` or `[uintmax\_t](http://en.cppreference.com/w/c/types/integer)\*`
 | `[size\_t](http://en.cppreference.com/w/c/types/size_t)\*` | `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)\*` | N/A |
| `i` |  matches an **integer**. The format of the number is the same as expected by [`wcstol`](../string/wide/wcstol "c/string/wide/wcstol") with the value `​0​` for the `base` argument (base is determined by the first characters parsed). |
| `u` |  matches an unsigned **decimal integer**. The format of the number is the same as expected by [`wcstoul`](../string/wide/wcstoul "c/string/wide/wcstoul") with the value `10` for the `base` argument. |
| `o` |  matches an unsigned **octal integer**. The format of the number is the same as expected by [`wcstoul`](../string/wide/wcstoul "c/string/wide/wcstoul") with the value `8` for the `base` argument. |
| `x`, `X` |  matches an unsigned **hexadecimal integer**. The format of the number is the same as expected by [`wcstoul`](../string/wide/wcstoul "c/string/wide/wcstoul") with the value `16` for the `base` argument. |
| `n` |  returns the **number of characters read so far**. No input is consumed. Does not increment the assignment count. If the specifier has assignment-suppressing operator defined, the behavior is undefined. |
| `a`, `A`(C99) `e`, `E` `f`, `F` `g`, `G` |  matches a **floating-point number**. The format of the number is the same as expected by [`wcstof`](../string/wide/wcstof "c/string/wide/wcstof"). | N/A | N/A | `float*` | `double*` | N/A | N/A | N/A | N/A | `long double*` |
| `p` |  matches implementation defined character sequence defining a **pointer**. `printf` family of functions should produce the same sequence using `%p` format specifier. | N/A | N/A | `void**` | N/A | N/A | N/A | N/A | N/A | N/A |

 For every conversion specifier other than `n`, the longest sequence of input characters which does not exceed any specified ﬁeld width and which either is exactly what the conversion specifier expects or is a prefix of a sequence it would expect, is what's consumed from the stream. The ﬁrst character, if any, after this consumed sequence remains unread. If the consumed sequence has length zero or if the consumed sequence cannot be converted as specified above, the matching failure occurs unless end-of-ﬁle, an encoding error, or a read error prevented input from the stream, in which case it is an input failure.


All conversion specifiers other than `[`, `c`, and `n` consume and discard all leading whitespace characters (determined as if by calling [`iswspace`](../string/wide/iswspace "c/string/wide/iswspace")) before attempting to parse the input. These consumed characters do not count towards the specified maximum field width.


If the length specifier `l` is not used, the conversion specifiers `c`, `s`, and `[` perform wide-to-multibyte character conversion as if by calling [`wcrtomb`](../string/multibyte/wcrtomb "c/string/multibyte/wcrtomb") with an [`mbstate_t`](../string/multibyte/mbstate_t "c/string/multibyte/mbstate t") object initialized to zero before the first character is converted.


The conversion specifiers `s` and `[` always store the null terminator in addition to the matched characters. The size of the destination array must be at least one greater than the specified field width. The use of `%s` or `%[`, without specifying the destination array size, is as unsafe as `[gets](gets "c/io/gets")`.


The correct conversion specifications for the [fixed-width integer types](../types/integer "c/types/integer") (`[int8\_t](../types/integer "c/types/integer")`, etc) are defined in the header [`<inttypes.h>`](../types/integer "c/types/integer") (although [`SCNdMAX`](../types/integer "c/types/integer"), [`SCNuMAX`](../types/integer "c/types/integer"), etc is synonymous with `%jd`, `%ju`, etc).


There is a [sequence point](../language/eval_order "c/language/eval order") after the action of each conversion specifier; this permits storing multiple fields in the same "sink" variable.


When parsing an incomplete floating-point value that ends in the exponent with no digits, such as parsing `"100er"` with the conversion specifier `%f`, the sequence `"100e"` (the longest prefix of a possibly valid floating-point number) is consumed, resulting in a matching error (the consumed sequence cannot be converted to a floating-point number), with `"r"` remaining. Some existing implementations do not follow this rule and roll back to consume only `"100"`, leaving `"er"`, e.g. [glibc bug 1765](https://sourceware.org/bugzilla/show_bug.cgi?id=1765).


###  Return value

 
1-3) Number of receiving arguments successfully assigned, or `[EOF](../io "c/io")` if read failure occurs before the first receiving argument was assigned. 
4-6) Same as (1-3), except that `[EOF](../io "c/io")` is also returned if there is a runtime constraint violation. ###  Notes

 All these functions may invoke `va_arg`, the value of `arg` is indeterminate after the return. These functions to not invoke `va_end`, and it must be done by the caller.


###  Example

 ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.29.2.6 The vfwscanf function (p: 418)
+ 7.29.2.8 The vswscanf function (p: 419)
+ 7.29.2.10 The vwscanf function (p: 420)
+ K.3.9.1.7 The vfwscanf\_s function (p: 632-633)
+ K.3.9.1.10 The vswscanf\_s function (p: 635-636)
+ K.3.9.1.12 The vwscanf\_s function (p: 637)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.2.6 The vfwscanf function (p: 364)
+ 7.24.2.8 The vswscanf function (p: 365)
+ 7.24.2.10 The vwscanf function (p: 366)

 ###  See also

 

|  |  |
| --- | --- |
|  [wscanffwscanfswscanfwscanf\_sfwscanf\_sswscanf\_s](fwscanf "c/io/fwscanf")
(C95)(C95)(C95)(C11)(C11)(C11) |  reads formatted wide character input from `[stdin](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/vfwscanf "cpp/io/c/vfwscanf") for `vwscanf, vfwscanf, vswscanf` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/vfwscanf>

fgetpos
=======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int fgetpos( FILE          *stream, fpos_t          *pos );
```
 |  | (until C99) |
| 
```
int fgetpos( FILE *restrict stream, fpos_t *restrict pos );
```
 |  | (since C99) |

 Obtains the file position indicator and the current parse state (if any) for the file stream `stream` and stores them in the object pointed to by `pos`. The value stored is only meaningful as the input to `[fsetpos](fsetpos "c/io/fsetpos")`.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  file stream to examine  |
|  pos  |  -  |  pointer to a `[fpos\_t](fpos_t "c/io/fpos t")` object to store the file position indicator to  |

 ###  Return value

 `​0​` upon success, nonzero value otherwise.


###  Example

  
```
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
 
int main(void)
{
    // prepare a file holding 4 values of type double
    enum {SIZE = 4};
    FILE* fp = fopen("test.bin", "wb");
    assert(fp);
    int rc = fwrite((double[SIZE]){1.1, 2.2, 3.3, 4.4}, sizeof(double), SIZE, fp);
    assert(rc == SIZE);
    fclose(fp);
 
    // demo using fsetpos to return to the beginning of a file
    fp = fopen("test.bin", "rb");
    fpos_t pos;
    fgetpos(fp, &pos);               // store start of file in pos
    double d;
    rc = fread(&d, sizeof d, 1, fp); // read the first double
    assert(rc == 1);
    printf("First value in the file: %.1f\n", d);
    fsetpos(fp,&pos);                 // move file position back to the start of the file
    rc = fread(&d, sizeof d, 1, fp);  // read the first double again
    assert(rc == 1);
    printf("First value in the file again: %.1f\n", d);
    fclose(fp);
 
    // demo error handling
    rc = fsetpos(stdin, &pos);
    if(rc) perror("could not fsetpos stdin");
}
```
 Output:



```
First value in the file: 1.1
First value in the file again: 1.1
could not fsetpos stdin: Illegal seek
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.9.1 The fgetpos function (p: 336)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.9.1 The fgetpos function (p: 302)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.9.1 The fgetpos function

 ###  See also

 

|  |  |
| --- | --- |
|  [ftell](ftell "c/io/ftell") |  returns the current file position indicator  (function) |
|  [fseek](fseek "c/io/fseek") |  moves the file position indicator to a specific location in a file  (function) |
|  [fsetpos](fsetpos "c/io/fsetpos") |  moves the file position indicator to a specific location in a file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fgetpos "cpp/io/c/fgetpos") for `fgetpos` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fgetpos>

fsetpos
=======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int fsetpos( FILE *stream, const fpos_t *pos );
```
 |  |  |

 Sets the file position indicator and the multibyte parsing state (if any) for the file stream `stream` according to the value pointed to by `pos`.


Besides establishing new parse state and position, a call to this function undoes the effects of `[ungetc](ungetc "c/io/ungetc")` and clears the end-of-file state, if it is set.


If a read or write error occurs, the error indicator (`[ferror](ferror "c/io/ferror")`) for the stream is set.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  file stream to modify  |
|  pos  |  -  |  pointer to a `[fpos\_t](fpos_t "c/io/fpos t")` object to use as new value of file position indicator  |

 ###  Return value

 `​0​` upon success, nonzero value otherwise.


###  Notes

 After seeking to a non-end position in a wide stream, the next call to any output function may render the remainder of the file undefined, e.g. by outputting a multibyte sequence of a different length.


###  Example

 
fsetpos with error checking.



```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    /* Prepare an array of f-p values. */
    #define SIZE 5
    double A[SIZE] = {1.,2.,3.,4.,5.};
    /* Write array to a file. */
    FILE * fp = fopen("test.bin", "wb");
    fwrite(A,sizeof(double),SIZE,fp);
    fclose (fp);
 
    /* Read the f-p values into array B. */
    double B[SIZE];
    fp = fopen("test.bin","rb");
    fpos_t pos;
    if (fgetpos(fp,&pos) != 0)      /* current position: start of file */
    {
       perror("fgetpos()");
       fprintf(stderr,"fgetpos() failed in file %s at line # %d\n", __FILE__,__LINE__-3);
       exit(EXIT_FAILURE);
    }
 
    int ret_code = fread(B,sizeof(double),1,fp);   /* read one f-p value */
    /* current position: after reading one f-p value */
    printf("%.1f; read count = %d\n", B[0], ret_code);   /* print one f-p value and ret_code */
 
    if (fsetpos(fp,&pos) != 0)   /* reset current position to start of file */
    {
       if (ferror(fp))
       {
          perror("fsetpos()");
          fprintf(stderr,"fsetpos() failed in file %s at line # %d\n", __FILE__,__LINE__-5);
          exit(EXIT_FAILURE);
       }
    }
 
    ret_code = fread(B,sizeof(double),1,fp);   /* reread first f-p value */
    printf("%.1f; read count = %d\n", B[0], ret_code);   /* print one f-p value and ret_code */
    fclose(fp);
 
    return EXIT_SUCCESS; 
}
```
 Output:



```
1.0; read count = 1
1.0; read count = 1
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.9.3 The fsetpos function (p: 337)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.9.3 The fsetpos function (p: 303)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.9.3 The fsetpos function

 ###  See also

 

|  |  |
| --- | --- |
|  [fgetpos](fgetpos "c/io/fgetpos") |  gets the file position indicator  (function) |
|  [ftell](ftell "c/io/ftell") |  returns the current file position indicator  (function) |
|  [fseek](fseek "c/io/fseek") |  moves the file position indicator to a specific location in a file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fsetpos "cpp/io/c/fsetpos") for `fsetpos` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fsetpos>

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.




 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Noreturn>

ftell
=====

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
long ftell( FILE *stream );
```
 |  |  |

 Returns the file position indicator for the file stream `stream`.


If the stream is open in binary mode, the value obtained by this function is the number of bytes from the beginning of the file.


If the stream is open in text mode, the value returned by this function is unspecified and is only meaningful as the input to `[fseek()](fseek "c/io/fseek")`.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  file stream to examine  |

 ###  Return value

 File position indicator on success or `-1L` if failure occurs.


On error, the `errno` variable is set to implementation-defined positive value.


###  Example

 
Demonstrates `ftell()` with error checking. Writes then reads a few floating-point (FP) values to/from a file.



```
#include <stdio.h>
#include <stdlib.h>
 
/* If the condition is not met then exit the program with error message. */
void check(_Bool condition, const char* func, int line)
{
    if (condition)
        return;
    perror(func);
    fprintf(stderr, "%s failed in file %s at line # %d\n", func, __FILE__, line - 1);
    exit(EXIT_FAILURE);
}
 
int main(void)
{
    /* Prepare an array of FP values. */
    #define SIZE 5
    double A[SIZE] = {1.1,2.,3.,4.,5.};
 
    /* Write array to a file. */
    const char* fname = "/tmp/test.bin";
    FILE* file = fopen(fname, "wb");
    check(file != NULL, "fopen()", __LINE__);
 
    const int write_count = fwrite(A, sizeof(double), SIZE, file);
    check(write_count == SIZE, "fwrite()", __LINE__);
 
    fclose(file);
 
    /* Read the FP values into array B. */
    double B[SIZE];
    file = fopen(fname, "rb");
    check(file != NULL, "fopen()", __LINE__);
 
    long int pos = ftell(file); /* position indicator at start of file */
    check(pos != -1L, "ftell()", __LINE__);
    printf("pos: %ld\n", pos);
 
    const int read_count = fread(B, sizeof(double), 1, file); /* read one FP value */
    check(read_count == 1, "fread()", __LINE__);
 
    pos = ftell(file); /* position indicator after reading one FP value */
    check(pos != -1L, "ftell()", __LINE__);
    printf("pos: %ld\n", pos);
    printf("B[0]: %.1f\n", B[0]); /* print one FP value */
 
    return EXIT_SUCCESS;
}
```
 Possible output:



```
pos: 0
pos: 8
B[0]: 1.1
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.9.4 The ftell function (p: 337-338)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.9.4 The ftell function (p: 303-304)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.9.4 The ftell function

 ###  See also

 

|  |  |
| --- | --- |
|  [fgetpos](fgetpos "c/io/fgetpos") |  gets the file position indicator  (function) |
|  [fseek](fseek "c/io/fseek") |  moves the file position indicator to a specific location in a file  (function) |
|  [fsetpos](fsetpos "c/io/fsetpos") |  moves the file position indicator to a specific location in a file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/ftell "cpp/io/c/ftell") for `ftell` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/ftell>

feof
====

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int feof( FILE *stream );
```
 |  |  |

 Checks if the end of the given file stream has been reached.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  the file stream to check  |

 ###  Return value

 nonzero value if the end of the stream has been reached, otherwise `​0​`


###  Notes

 This function only reports the stream state as reported by the most recent I/O operation, it does not examine the associated data source. For example, if the most recent I/O was a `[fgetc](fgetc "c/io/fgetc")`, which returned the last byte of a file, `feof` returns zero. The next `[fgetc](fgetc "c/io/fgetc")` fails and changes the stream state to *end-of-file*. Only then `feof` returns non-zero.


In typical usage, input stream processing stops on any error; `feof` and `[ferror](ferror "c/io/ferror")` are then used to distinguish between different error conditions.


###  Example

  
```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    const char* fname = "/tmp/unique_name.txt"; // or tmpnam(NULL);
    int is_ok = EXIT_FAILURE;
 
    FILE* fp = fopen(fname, "w+");
    if (!fp) {
        perror("File opening failed");
        return is_ok;
    }
    fputs("Hello, world!\n", fp);
    rewind(fp);
 
    int c; // note: int, not char, required to handle EOF
    while ((c = fgetc(fp)) != EOF) // standard C I/O file reading loop
        putchar(c);
 
    if (ferror(fp))
        puts("I/O error when reading");
    else if (feof(fp)) {
        puts("End of file is reached successfully");
        is_ok = EXIT_SUCCESS;
    }
 
    fclose(fp);
    remove(fname);
    return is_ok;
}
```
 Possible output:



```
Hello, world!
End of file is reached successfully
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.10.2 The feof function (p: 339)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.10.2 The feof function (p: 305)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.10.2 The feof function

 ###  See also

 

|  |  |
| --- | --- |
|  [clearerr](clearerr "c/io/clearerr") |  clears errors  (function) |
|  [perror](perror "c/io/perror") |  displays a character string corresponding of the current error to `[stderr](std_streams "c/io/std streams")`  (function) |
|  [ferror](ferror "c/io/ferror") |  checks for a file error  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/feof "cpp/io/c/feof") for `feof` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/feof>

ferror
======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int ferror( FILE *stream );
```
 |  |  |

 Checks the given stream for errors.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  the file stream to check  |

 ###  Return value

 Nonzero value if the file stream has errors occurred, `​0​` otherwise.


###  Example

  
```
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
 
int main(void)
{
    char* fname = tmpnam(NULL);
    FILE* f = fopen(fname, "wb");
    fputs("\xff\xff\n", f); // not a valid UTF-8 character sequence
    fclose(f);
 
    setlocale(LC_ALL, "en_US.utf8");
    f = fopen(fname, "rb");
    wint_t ch;
    while ((ch=fgetwc(f)) != WEOF) // attempt to read as UTF-8 fails
          printf("%#x ", ch);
 
    if (feof(f))
        puts("EOF indicator set");
    if (ferror(f))
        puts("Error indicator set");
}
```
 Output:



```
Error indicator set
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.10.3 The ferror function (p: 339)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.10.3 The ferror function (p: 305)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.10.3 The ferror function

 ###  See also

 

|  |  |
| --- | --- |
|  [clearerr](clearerr "c/io/clearerr") |  clears errors  (function) |
|  [feof](feof "c/io/feof") |  checks for the end-of-file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/ferror "cpp/io/c/ferror") for `ferror` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/ferror>

perror
======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
void perror( const char *s );
```
 |  |  |

 Prints a textual description of the error code currently stored in the system variable `[errno](../error/errno "c/error/errno")` to `[stderr](std_streams "c/io/std streams")`.


The description is formed by concatenating the following components:


* the contents of the null-terminated byte string pointed to by `s`, followed by `": "` (unless `s` is a null pointer or the character pointed to by `s` is the null character)
* implementation-defined error message string describing the error code stored in `errno`, followed by `'\n'`. The error message string is identical to the result of `[strerror](http://en.cppreference.com/w/c/string/byte/strerror)(errno)`.

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  s  |  -  |  pointer to a null-terminated string with explanatory message  |

 ###  Return value

 (none).


###  Example

  
```
#include <stdio.h>
 
int main(void)
{
    FILE *f = fopen("non_existent", "r");
    if (f == NULL) {
        perror("fopen() failed");
    } else {
        fclose(f);
    }
}
```
 Possible output:



```
fopen() failed: No such file or directory
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.10.4 The perror function (p: 339)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.10.4 The perror function (p: 305)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.10.4 The perror function

 ###  See also

 

|  |  |
| --- | --- |
|  [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/io/c/perror "cpp/io/c/perror") for `perror` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/perror>

remove
======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int remove( const char *fname );
```
 |  |  |

 Deletes the file identified by character string pointed to by `fname`.


If the file is currently open by this or another process, the behavior of this function is implementation-defined (in particular, POSIX systems unlink the file name although the file system space is not reclaimed until the last running process closes the file; Windows does not allow the file to be deleted).


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  fname  |  -  |  pointer to a null-terminated string containing the path identifying the file to delete  |

 ###  Return value

 `​0​` upon success or non-zero value on error.


###  Notes

 [POSIX specifies](http://pubs.opengroup.org/onlinepubs/9699919799/functions/remove.html) many additional details for the behavior of this function.


###  Example

  
```
#include <stdio.h>
int main(void)
{
    FILE* fp = fopen("file1.txt", "w"); // create file
    if(!fp) { perror("file1.txt"); return 1; }
    puts("Created file1.txt");
    fclose(fp);
 
    int rc = remove("file1.txt");
    if(rc) { perror("remove"); return 1; }
    puts("Removed file1.txt");
 
    fp = fopen("file1.txt", "r"); // Failure: file does not exist
    if(!fp) perror("Opening removed file failed");
 
    rc = remove("file1.txt"); // Failure: file does not exist
    if(rc) perror("Double-remove failed");
}
```
 Output:



```
Created file1.txt
Removed file1.txt
Opening removed file failed: No such file or directory
Double-remove failed: No such file or directory
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.4.1 The remove function (p: 302)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.4.1 The remove function (p: 268)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.4.1 The remove function

 ###  See also

 

|  |  |
| --- | --- |
|  [rename](rename "c/io/rename") |  renames a file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/remove "cpp/io/c/remove") for `remove` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/remove>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/program/jmp_buf>

clearerr
========

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
void clearerr( FILE *stream );
```
 |  |  |

 Resets the error flags and the [`EOF`](../io#Macro_constants "c/io") indicator for the given file stream.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  the file to reset the error flags for  |

 ###  Return value

 (none).


###  Example

  
```
#include <stdio.h>
#include <assert.h>
 
int main(void)
{
    FILE* tmpf = tmpfile();
    fputs("cppreference.com\n", tmpf);
    rewind(tmpf);
 
    for (int ch; (ch = fgetc(tmpf)) != EOF; putchar(ch)) { }
 
    assert(feof(tmpf)); // the loop is expected to terminate by EOF
    puts("End of file reached");
 
    clearerr(tmpf); // clear EOF
 
    puts(feof(tmpf) ? "EOF indicator set" 
                    : "EOF indicator cleared");
}
```
 Output:



```
cppreference.com
End of file reached
EOF indicator cleared
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.10.1 The clearerr function (p: 246)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.10.1 The clearerr function (p: 338)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.10.1 The clearerr function (p: 304)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.10.1 The clearerr function

 ###  See also

 

|  |  |
| --- | --- |
|  [feof](feof "c/io/feof") |  checks for the end-of-file  (function) |
|  [perror](perror "c/io/perror") |  displays a character string corresponding of the current error to `[stderr](std_streams "c/io/std streams")`  (function) |
|  [ferror](ferror "c/io/ferror") |  checks for a file error  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/clearerr "cpp/io/c/clearerr") for `clearerr` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/clearerr>

rename
======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int rename( const char *old_filename, const char *new_filename );
```
 |  |  |

 Changes the filename of a file. The file is identified by character string pointed to by `old_filename`. The new filename is identified by character string pointed to by `new_filename`.


If `new_filename` exists, the behavior is implementation-defined.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  old\_filename  |  -  |  pointer to a null-terminated string containing the path identifying the file to rename  |
|  new\_filename  |  -  |  pointer to a null-terminated string containing the new path of the file  |

 ###  Return value

 `​0​` upon success or non-zero value on error.


###  Notes

 [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html) specifies many additional details on the semantics of this function.


###  Example

  
```
#include <stdio.h>
int main(void)
{
    FILE* fp = fopen("from.txt", "w"); // create file "from.txt"
    if(!fp) { perror("from.txt"); return 1; }
    fputc('a', fp); // write to "from.txt"
    fclose(fp);
 
    int rc = rename("from.txt", "to.txt");
    if(rc) { perror("rename"); return 1; }
 
    fp = fopen("to.txt", "r");
    if(!fp) { perror("to.txt"); return 1; }
    printf("%c\n", fgetc(fp)); // read from "to.txt"
    fclose(fp);
}
```
 Output:



```
a
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.4.2 The rename function (p: 302-303)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.4.2 The rename function (p: 268-269)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.4.2 The rename function

 ###  See also

 

|  |  |
| --- | --- |
|  [remove](remove "c/io/remove") |  erases a file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/rename "cpp/io/c/rename") for `rename` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/rename>

tmpnam, tmpnam\_s
=================

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
char *tmpnam( char *filename );
```
 |  (1)  |  |
| 
```
errno_t tmpnam_s(char *filename_s, rsize_t maxsize);
```
 |  (2)  | (since C11) |
| 
```
#define TMP_MAX        /*unspecified*/
```
 |  |  |
| 
```
#define TMP_MAX_S      /*unspecified*/
```
 |  | (since C11) |
| 
```
#define L_tmpnam       /*unspecified*/
```
 |  |  |
| 
```
#define L_tmpnam_s     /*unspecified*/
```
 |  | (since C11) |

 
1) Creates a unique valid file name (no longer than `[L\_tmpnam](../io "c/io")` in length) and stores it in character string pointed to by `filename`. The function is capable of generating up to `[TMP\_MAX](../io "c/io")` of unique filenames, but some or all of them may be in use in the filesystem and thus not suitable return values. 
2) Same as (1), except that up to `TMP_MAX_S` names may be generated, no longer than `L_tmpnam_s` in length, 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: 

* `filename_s` is a null pointer
* `maxsize` is greater than `RSIZE_MAX`
* `maxsize` is less than the generated file name string

 
 As with all bounds-checked functions, `tmpnam_s` 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>`](../io "c/io").

 `tmpnam` and `tmpnam_s` modify static state (which may be shared between these functions) and are not required to be thread-safe.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  filename  |  -  |  pointer to the character array capable of holding at least `[L\_tmpnam](../io "c/io")` bytes, to be used as a result buffer. If null pointer is passed, a pointer to an internal static buffer is returned.  |
|  filename\_s  |  -  |  pointer to the character array capable of holding at least `L_tmpnam_s` bytes, to be used as a result buffer.  |
|  maxsize  |  -  |  maximum number of characters the function is allowed to write (typically the size of the `filename_s` array).  |

 ###  Return value

 
1) `filename` if `filename` was not a null pointer. Otherwise a pointer to an internal static buffer is returned. If no suitable filename can be generated, null pointer is returned. 
2) Returns zero and writes the file name to `filename_s` on success. On error, returns non-zero and writes the null character to `filename_s[0]` (only if `filename_s` is not null and `maxsize` is not zero and is not greater than `RSIZE_MAX`). ###  Notes

 Although the names generated by `tmpnam` are difficult to guess, it is possible that a file with that name is created by another process between the moment `tmpnam` returns and the moment this program attempts to use the returned name to create a file. The standard function `[tmpfile](tmpfile "c/io/tmpfile")` and the POSIX function [`mkstemp`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdtemp.html) do not have this problem (creating a unique directory using only the standard C library still requires the use of `tmpnam`).


POSIX systems additionally define the similarly named function [`tempnam`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/tempnam.html), which offers the choice of a directory (which defaults to the optionally defined macro [`P_tmpdir`](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/stdio.h.html)).


###  Example

  
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main(void)
{
    // Note, the compiler/linker may issue a security warning, e.g. GCC:
    // "warning: the use of `tmpnam' is dangerous, better use `mkstemp'"
    char* name1 = tmpnam(NULL);
    printf("temporary file name: %s\n", name1);
 
    char name2[L_tmpnam];
    if (tmpnam(name2))
        printf("temporary file name: %s\n", name2);
 
    // POSIX offers mkstemp. The following declaration might be
    // necessary as mkstemp is absent in the standard C <stdlib.h>.
    int mkstemp(char*);
 
    char name3[] = "/tmp/fileXXXXXX"; // at least six 'X' required ^_^
    int file_descriptor = mkstemp(name3);
    if (file_descriptor != -1)
        printf("temporary file name: %s\n", name3);
    else
        perror("mkstemp");
}
```
 Possible output:



```
temporary file name: /tmp/file90dLlR
temporary file name: /tmp/fileY9LWAg
temporary file name: /tmp/filexgv8PF
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.21.4.4 The tmpnam function (p: TBD)
+ K.3.5.1.2 The tmpnam\_s function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.21.4.4 The tmpnam function (p: 222)
+ K.3.5.1.2 The tmpnam\_s function (p: 427-428)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.4.4 The tmpnam function (p: 303-304)
+ K.3.5.1.2 The tmpnam\_s function (p: 587-588)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.4.4 The tmpnam function (p: 269-270)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.4.4 The tmpnam function

 ###  See also

 

|  |  |
| --- | --- |
|  [tmpfiletmpfile\_s](tmpfile "c/io/tmpfile")
(C11) |  returns a pointer to a temporary file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/tmpnam "cpp/io/c/tmpnam") for `tmpnam` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/tmpnam>

fgetws
======

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
wchar_t *fgetws( wchar_t *str, int count, FILE *stream );
```
 |  | (since C95) (until C99) |
| 
```
wchar_t *fgetws( wchar_t * restrict str, int count, FILE * restrict stream );
```
 |  | (since C99) |

 Reads at most `count - 1` wide characters from the given file stream and stores them in `str`. The produced wide string is always null-terminated. Parsing stops if end-of-file occurs or a newline wide character is found, in which case `str` will contain that wide newline character.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  str  |  -  |  wide string to read the characters to  |
|  count  |  -  |  the length of `str` |
|  stream  |  -  |  file stream to read the data from  |

 ###  Return value

 `str` on success, a null pointer on an error.


###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.29.3.2 The fgetws function (p: 422)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.3.2 The fgetws function (p: 367-368)

 ###  See also

 

|  |  |
| --- | --- |
|  [wscanffwscanfswscanfwscanf\_sfwscanf\_sswscanf\_s](fwscanf "c/io/fwscanf")
(C95)(C95)(C95)(C11)(C11)(C11) |  reads formatted wide character input from `[stdin](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [fgetwcgetwc](fgetwc "c/io/fgetwc")
(C95) |  gets a wide character from a file stream  (function) |
|  [fputws](fputws "c/io/fputws")
(C95) |  writes a wide string to a file stream  (function) |
|  [getlinegetwlinegetdelimgetwdelim](https://en.cppreference.com/w/c/experimental/dynamic/getline "c/experimental/dynamic/getline")
(dynamic memory TR) |  read from a stream into an automatically resized buffer until delimiter/end of line  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fgetws "cpp/io/c/fgetws") for `fgetws` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fgetws>

ungetwc
=======

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
wint_t ungetwc( wint_t ch, FILE *stream );
```
 |  | (since C95) |

 If `ch` does not equal `WEOF`, pushes the wide character `ch` into the input buffer associated with the stream `stream` in such a manner that subsequent read operation from `stream` will retrieve that wide character. The external device associated with the stream is not modified.


Stream repositioning operations `[fseek](fseek "c/io/fseek")`, `[fsetpos](fsetpos "c/io/fsetpos")`, and `[rewind](rewind "c/io/rewind")` discard the effects of `ungetwc`.


If `ungetwc` is called more than once without an intervening read or repositioning, it may fail (in other words, a pushback buffer of size 1 is guaranteed, but any larger buffer is implementation-defined). If multiple successful `ungetwc` were performed, read operations retrieve the pushed-back wide characters in reverse order of `ungetwc`.


If `ch` equals `WEOF`, the operation fails and the stream is not affected.


A successful call to `ungetwc` clears the end of file status flag `[feof](feof "c/io/feof")`.


A successful call to `ungetwc` on a stream (whether text or binary) modifies the stream position indicator in unspecified manner but guarantees that after all pushed-back wide characters are retrieved with a read operation, the stream position indicator is equal to its value before `ungetwc`.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ch  |  -  |  wide character to be put back  |
|  stream  |  -  |  file stream to put the wide character back to  |

 ###  Return value

 On success `ch` is returned.


On failure `WEOF` is returned and the given stream remains unchanged.


###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.29.3.10 The ungetwc function (p: 425-426)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.3.10 The ungetwc function (p: 370-371)

 ###  See also

 

|  |  |
| --- | --- |
|  [ungetc](ungetc "c/io/ungetc") |  puts a character back into a file stream  (function) |
|  [fgetwcgetwc](fgetwc "c/io/fgetwc")
(C95) |  gets a wide character from a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/ungetwc "cpp/io/c/ungetwc") for `ungetwc` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/ungetwc>

rewind
======

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
void rewind( FILE *stream );
```
 |  |  |

 Moves the file position indicator to the beginning of the given file stream.


The function is equivalent to `[fseek](http://en.cppreference.com/w/c/io/fseek)(stream, 0, [SEEK\_SET](http://en.cppreference.com/w/c/io));`, except that end-of-file and error indicators are cleared.


The function drops any effects from previous calls to `[ungetc](ungetc "c/io/ungetc")`.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  file stream to modify  |

 ###  Return value

 (none).


###  Example

 
This example shows how to read a file twice.



```
#include <stdio.h>
 
char str[20];
 
int main(void)
{
    FILE *f;
    char ch;
 
    f = fopen("file.txt", "w");
    for (ch = '0'; ch <= '9'; ch++) {
        fputc(ch, f);
    }
    fclose(f);
 
    f = fopen("file.txt", "r");
    fread(str, 1, 10, f);
    puts(str);
 
    rewind(f);
    fread(str, 1, 10, f);
    puts(str);
    fclose(f);
 
    return 0;
}
```
 Output:



```
0123456789
0123456789
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.21.9.5 The rewind function (p: 338)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.9.5 The rewind function (p: 304)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.9.5 The rewind function

 ###  See also

 

|  |  |
| --- | --- |
|  [fseek](fseek "c/io/fseek") |  moves the file position indicator to a specific location in a file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/rewind "cpp/io/c/rewind") for `rewind` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/rewind>

tmpfile, tmpfile\_s
===================

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
FILE *tmpfile(void);
```
 |  (1)  |  |
| 
```
errno_t tmpfile_s(FILE * restrict * restrict streamptr);
```
 |  (2)  | (since C11) |

 
1) Creates and opens a temporary file. The file is opened as binary file for update (as if by `[fopen](fopen "c/io/fopen")` with `"wb+"` mode). The filename of the file is guaranteed to be unique within the filesystem. At least `[TMP\_MAX](../io "c/io")` files may be opened during the lifetime of a program (this limit may be shared with `[tmpnam](tmpnam "c/io/tmpnam")` and may be further limited by `[FOPEN\_MAX](../io "c/io")`). 
2) Same as (1), except that at least `TMP_MAX_S` files may be opened (the limit may be shared with `tmpnam_s`), and if `streamptr` is a null pointer, the currently installed [constraint handler](../error/set_constraint_handler_s "c/error/set constraint handler s") function is called. As with all bounds-checked functions, `tmpfile_s` 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>`](../io "c/io"). The temporary file created by this function is closed and deleted when the program exits normally. Whether it's deleted on abnormal termination is implementation-defined.


###  Parameters

 
1) (none) 
2) pointer to a pointer that will be updated by this function call ###  Return value

 
1) Pointer to the file stream associated with the file or null pointer if an error has occurred. 
2) Zero if the file was created and open successfully, non-zero if the file was not created or open or if `streamptr` was a null pointer. In addition, pointer to the associated file stream is stored in `*streamptr` on success, and a null pointer value is stored in `*streamptr` on error. ###  Notes

 On some implementations (e.g. older Linux), this function actually creates, opens, and immediately deletes the file from the file system: as long as an open file descriptor to a deleted file is held by a program, the file exists, but since it was deleted, its name does not appear in any directory, so that no other process can open it. Once the file descriptor is closed, or once the program terminates (normally or abnormally), the space occupied by the file is reclaimed by the filesystem. Newer Linux (since 3.11 or later, depending on filesystem) creates such invisible temporary files in one step, via special flag in the [`open()`](https://man7.org/linux/man-pages/man2/open.2.html) syscall.


On some implementations (e.g. Windows), elevated privileges are required as the function may create the temporary file in a system directory.


###  Example

  
```
#define _POSIX_C_SOURCE 200112L
#include <stdio.h>
#include <unistd.h>
 
int main(void)
{
    printf("TMP_MAX = %d, FOPEN_MAX = %d\n", TMP_MAX, FOPEN_MAX);
    FILE* tmpf = tmpfile();
    fputs("Hello, world", tmpf);
    rewind(tmpf);
    char buf[6];
    fgets(buf, sizeof buf, tmpf);
    printf("got back from the file: '%s'\n", buf);
 
    // Linux-specific method to display the tmpfile name
    char fname[FILENAME_MAX], link[FILENAME_MAX] = {0};
    sprintf(fname, "/proc/self/fd/%d", fileno(tmpf));
    if(readlink(fname, link, sizeof link - 1) > 0)
        printf("File name: %s\n", link);
}
```
 Possible output:



```
TMP_MAX = 238328, FOPEN_MAX = 16
got back from the file: 'Hello'
File name: /tmp/tmpfjptPe5 (deleted)
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.4.3 The tmpfile function (p: 222)
+ K.3.5.1.1 The tmpfile\_s function (p: 427)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.4.3 The tmpfile function (p: 303)
+ K.3.5.1.1 The tmpfile\_s function (p: 586-587)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.4.3 The tmpfile function (p: 269)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.4.3 The tmpfile function

 ###  See also

 

|  |  |
| --- | --- |
|  [tmpnamtmpnam\_s](tmpnam "c/io/tmpnam")
(C11) |  returns a unique filename  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/tmpfile "cpp/io/c/tmpfile") for `tmpfile` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/tmpfile>

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 denoted 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]]` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/attributes/noreturn>

thrd\_exit
==========

 

|  Defined in header `<threads.h>` |  |  |
| --- | --- | --- |
| 
```
_Noreturn void thrd_exit( int res );
```
 |  | (since C11) (until C23) |
| 
```
[[noreturn]] void thrd_exit( int res );
```
 |  | (since C23) |

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/thrd_exit>

FLT\_ROUNDS
===========

 

|  Defined in header `<float.h>` |  |  |
| --- | --- | --- |
| 
```
#define FLT_ROUNDS /* implementation defined */
```
 |  |  |

 Returns the current rounding direction of floating-point arithmetic operations.




|  Value  |  Explanation  |
| --- | --- |
| `-1` |  the default rounding direction is not known  |
| `0` |  toward zero; same meaning as `[FE\_TOWARDZERO](../../numeric/fenv/fe_round "c/numeric/fenv/FE round")` |
| `1` |  to nearest; same meaning as `[FE\_TONEAREST](../../numeric/fenv/fe_round "c/numeric/fenv/FE round")` |
| `2` |  towards positive infinity; same meaning as `[FE\_UPWARD](../../numeric/fenv/fe_round "c/numeric/fenv/FE round")` |
| `3` |  towards negative infinity; same meaning as `[FE\_DOWNWARD](../../numeric/fenv/fe_round "c/numeric/fenv/FE round")` |
|  other values  |  implementation-defined behavior  |

 ###  Notes

 The rounding mode can be changed with `[fesetround](../../numeric/fenv/feround "c/numeric/fenv/feround")` and `FLT_ROUNDS` reflects that change.


###  See also

 

|  |  |
| --- | --- |
|  [fegetroundfesetround](../../numeric/fenv/feround "c/numeric/fenv/feround")
(C99)(C99) |  gets or sets rounding direction  (function) |
|  [FE\_DOWNWARDFE\_TONEARESTFE\_TOWARDZEROFE\_UPWARD](../../numeric/fenv/fe_round "c/numeric/fenv/FE round")
(C99) |  floating-point rounding direction  (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/types/climits/FLT_ROUNDS "cpp/types/climits/FLT ROUNDS") for `FLT_ROUNDS` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/types/limits/FLT_ROUNDS>

wprintf, fwprintf, swprintf, wprintf\_s, fwprintf\_s, swprintf\_s, snwprintf\_s
===============================================================================

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
|  | (1) |  |
| 
```
int wprintf( const wchar_t *format, ... );
```
 | (since C95) (until C99) |
| 
```
int wprintf( const wchar_t *restrict format, ... );
```
 | (since C99) |
|  | (2) |  |
| 
```
int fwprintf( FILE *stream, const wchar_t *format, ... );
```
 | (since C95) (until C99) |
| 
```
int fwprintf( FILE *restrict stream,
              const wchar_t *restrict format, ... );
```
 | (since C99) |
|  | (3) |  |
| 
```
int swprintf( wchar_t *buffer, size_t bufsz,
              const wchar_t *format, ... );
```
 | (since C95) (until C99) |
| 
```
int swprintf( wchar_t *restrict buffer, size_t bufsz,
              const wchar_t *restrict format, ... );
```
 | (since C99) |
| 
```
int wprintf_s( const wchar_t *restrict format, ... );
```
 |  (4)  | (since C11) |
| 
```
int fwprintf_s( FILE *restrict stream,
                const wchar_t *restrict format, ... );
```
 |  (5)  | (since C11) |
| 
```
int swprintf_s( wchar_t *restrict buffer, rsize_t bufsz,
                const wchar_t *restrict format, ... );
```
 |  (6)  | (since C11) |
| 
```
int snwprintf_s( wchar_t *restrict s, rsize_t n,
                 const wchar_t *restrict format, ... );
```
 |  (7)  | (since C11) |

 Loads the data from the given locations, converts them to wide string equivalents and writes the results to a variety of sinks.



1) Writes the results to `[stdout](std_streams "c/io/std streams")`. 
2) Writes the results to a file stream `stream`. 
3) If `bufsz` is greater than zero, writes the results to a wide string `buffer`. At most `bufsz-1` wide characters are written followed by null wide character. If `bufsz` is zero, nothing is written (and `buffer` may be a null pointer). 
4-6) Same as (1-3), 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: * the conversion specifier `%n` is present in `format`
* any of the arguments corresponding to `%s` is a null pointer
* `format` or `buffer` is a null pointer
* `bufsz` is zero or greater than `RSIZE_MAX/sizeof(wchar_t)`
* encoding errors occur in any of string and character conversion specifiers
* (only for `swprintf_s`) the number of wide characters to be written, including the null, would exceed `bufsz`.


 
7) Same as (6), except it will truncate the result to fit within the array pointed to by s. As with all bounds-checked functions, `wprintf_s` , `fwprintf_s`, `swprintf_s`, and `snwprintf_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 [`<stdio.h>`](../io "c/io"). ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  output file stream to write to  |
|  buffer  |  -  |  pointer to a wide character string to write to  |
|  bufsz  |  -  |  up to `bufsz-1` wide characters may be written, plus the null terminator  |
|  format  |  -  |  pointer to a null-terminated wide string specifying how to interpret the data  |
|  ...  |  -  |  arguments specifying data to print. If any argument after [default argument promotions](../language/conversion#Default_argument_promotions "c/language/conversion") is not the type expected by the corresponding conversion specifier, or if there are fewer arguments than required by `format`, the behavior is undefined. If there are more arguments than required by `format`, the extraneous arguments are evaluated and ignored.  |

   
 The **format** string consists of ordinary wide characters (except `%`), which are copied unchanged into the output stream, and conversion specifications. Each conversion specification has the following format:


* introductory `%` character
* (optional) one or more flags that modify the behavior of the conversion:
+ `-`: the result of the conversion is left-justified within the field (by default it is right-justified)
+ `+`: the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative)
+ *space*: if the result of a signed conversion does not start with a sign character, or is empty, space is prepended to the result. It is ignored if `+` flag is present.
+ `#` : *alternative form* of the conversion is performed. See the table below for exact effects otherwise the behavior is undefined.
+ `0` : for integer and floating point number conversions, leading zeros are used to pad the field instead of *space* characters. For integer numbers it is ignored if the precision is explicitly specified. For other conversions using this flag results in undefined behavior. It is ignored if `-` flag is present.

* (optional) integer value or `*` that specifies minimum field width. The result is padded with *space* characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when `*` is used, the width is specified by an additional argument of type `int`, which appears before the argument to be converted and the argument supplying precision if one is supplied. If the value of the argument is negative, it results with the `-` flag specified and positive field width. (Note: This is the minimum width: The value is never truncated.)
+ (optional) `.` followed by integer number or `*`, or neither that specifies *precision* of the conversion. In the case when `*` is used, the *precision* is specified by an additional argument of type `int`, which appears before the argument to be converted, but after the argument supplying minimum field width if one is supplied. If the value of this argument is negative, it is ignored. If neither a number nor `*` is used, the precision is taken as zero. See the table below for exact effects of *precision*.
+ (optional) *length modifier* that specifies the size of the argument (in combination with the conversion format specifier, it specifies the type of the corresponding argument)
+ conversion format specifier

 The following format specifiers are available:




|  ConversionSpecifier  |  Explanation  |  ExpectedArgument Type  |
| --- | --- | --- |
| **LengthModifier****→** | `hh` (C99). | `h` |  (none)  | `l` | `ll` (C99). | `j` (C99). | `z` (C99). | `t` (C99). | `L` |
| `%` |  writes literal `%`. The full conversion specification must be `%%`.  | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A |
| `c` |  writes a **single character**. The argument is first converted to `wchar_t` as if by calling `[btowc](../string/multibyte/btowc "c/string/multibyte/btowc")`. If the **l** modifier is used, the `wint_t` argument is first converted to `wchar_t`. | N/A | N/A | `int` | `wint_t` | N/A | N/A | N/A | N/A | N/A |
| `s` |  writes a **character string** The argument must be a pointer to the initial element of a character array containing a multibyte character sequence beginning in the initial shift state, which is converted to wide character array as if by a call to `[mbrtowc](../string/multibyte/mbrtowc "c/string/multibyte/mbrtowc")` with zero-initialized conversion state. *Precision* specifies the maximum number of wide characters to be written. If *Precision* is not specified, writes every wide characters up to and not including the first null terminator. If the **l** specifier is used, the argument must be a pointer to the initial element of an array of `wchar_t`. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A |
| `d` `i` |  converts a **signed integer** into decimal representation *[-]dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | `signed char` | `short` | `int` | `long` | `long long` | `[intmax\_t](http://en.cppreference.com/w/c/types/integer)` | signed `[size\_t](http://en.cppreference.com/w/c/types/size_t)`
 | `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)` | N/A |
| `o` |  converts an **unsigned integer** into octal representation *oooo*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* precision is increased if necessary, to write one leading zero. In that case if both the converted value and the precision are `​0​`, single `​0​` is written. | `unsigned char` | `unsigned short` | `unsigned int` | `unsigned long` | `unsigned long long` | `[uintmax\_t](http://en.cppreference.com/w/c/types/integer)` | `[size\_t](http://en.cppreference.com/w/c/types/size_t)` | unsigned version of `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)`
 | N/A |
| `x` `X` |  converts an **unsigned integer** into hexadecimal representation *hhhh*. For the `x` conversion letters `abcdef` are used. For the `X` conversion letters `ABCDEF` are used. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* `0x` or `0X` is prefixed to results if the converted value is nonzero. | N/A |
| `u` |  converts an **unsigned integer** into decimal representation *dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | N/A |
| `f` `F` |  converts **floating-point number** to the decimal notation in the style *[-]ddd.ddd*. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | `double` | 
`double` (C99)
 | N/A | N/A | N/A | N/A | `long double` |
| `e` `E` |  converts **floating-point number** to the decimal exponent notation. For the `e` conversion style *[-]d.ddd*`e`*±dd* is used. For the `E` conversion style *[-]d.ddd*`E`*±dd* is used. The exponent contains at least two digits, more digits are used only if necessary. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A |
| `a` `A` (C99). |  converts **floating-point number** to the hexadecimal exponent notation. For the `a` conversion style *[-]*`0x`*h.hhh*`p`*±d* is used. For the `A` conversion style *[-]*`0X`*h.hhh*`P`*±d* is used. The first hexadecimal digit is not `0` if the argument is a normalized floating point value. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the hexadecimal point character. The default precision is sufficient for exact representation of the value. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A |
| `g` `G` |  converts **floating-point number** to decimal or decimal exponent notation depending on the value and the *precision*. For the `g` conversion style conversion with style `e` or `f` will be performed. For the `G` conversion style conversion with style `E` or `F` will be performed. Let `P` equal the precision if nonzero, `6` if the precision is not specified, or `1` if the precision is `​0​`. Then, if a conversion with style `E` would have an exponent of `X`:* if *P > X ≥ −4*, the conversion is with style `f` or `F` and precision *P − 1 − X*.
* otherwise, the conversion is with style `e` or `E` and precision *P − 1*.

Unless *alternative representation* is requested the trailing zeros are removed, also the decimal point character is removed if no fractional part is left. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A |
| `n` |  returns the **number of characters written** so far by this call to the function. The result is *written* to the value pointed to by the argument. The specification may not contain any *flag*, *field width*, or *precision*.  | `signed char*` | `short*` | `int*` | `long*` | `long long*` | `[intmax\_t](http://en.cppreference.com/w/c/types/integer)\*` | signed `[size\_t](http://en.cppreference.com/w/c/types/size_t)\*`
 | `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)\*` | N/A |
| `p` |  writes an implementation defined character sequence defining a **pointer**.  | N/A | N/A | `void*` | N/A | N/A | N/A | N/A | N/A | N/A |

 The floating point conversion functions convert infinity to `inf` or `infinity`. Which one is used is implementation defined.


Not-a-number is converted to `nan` or `nan(*char\_sequence*)`. Which one is used is implementation defined.


The conversions `F`, `E`, `G`, `A` output `INF`, `INFINITY`, `NAN` instead.


Even though `%c` expects `int` argument, it is safe to pass a `char` because of the integer promotion that takes place when a variadic function is called.


The correct conversion specifications for the fixed-width character types (`[int8\_t](../types/integer "c/types/integer")`, etc) are defined in the header [`<inttypes.h>`](../types/integer "c/types/integer") (although `[PRIdMAX](../types/integer "c/types/integer")`, `[PRIuMAX](../types/integer "c/types/integer")`, etc is synonymous with `%jd`, `%ju`, etc).


The memory-writing conversion specifier `%n` is a common target of security exploits where format strings depend on user input and is not supported by the bounds-checked `printf_s` family of functions.


There is a [sequence point](../language/eval_order "c/language/eval order") after the action of each conversion specifier; this permits storing multiple `%n` results in the same variable or, as an edge case, printing a string modified by an earlier `%n` within the same call.


If a conversion specification is invalid, the behavior is undefined.


###  Return value

 
1,2) Number of wide characters written if successful or negative value if an error occurred. 
3) Number of wide characters written (not counting the terminating null wide character) if successful or negative value if an encoding error occurred or if the number of characters to be generated was equal or greater than `size` (including when `size` is zero). 
4,5) Number of wide characters written if successful or negative value if an error occurred. 
6) Number of wide characters (not counting the terminating null) that were written to `buffer`. Returns a negative value on encoding errors and on overflow. Returns zero on all other errors. 
7) Number of wide characters (not counting the terminating null) that would have been written to `buffer` had `bufsz` been sufficiently large, or a negative value if an error occurs. (meaning, write was successful and complete only if the return is nonnegative and less than `bufsz`) ###  Notes

 While narrow strings provide `[snprintf](fprintf "c/io/fprintf")`, which makes it possible to determine the required output buffer size, there is no equivalent for wide strings (until `snwprintf_s`) (since C11), and in order to determine the buffer size, the program may need to call `swprintf`, check the result value, and reallocate a larger buffer, trying again until successful.


`snwprintf_s`, unlike `swprintf_s`, will truncate the result to fit within the array pointed to by `buffer`, even though truncation is treated as an error by most bounds-checked functions.


###  Example

  
```
#include <locale.h>
#include <wchar.h>
 
int main(void)
{
    char narrow_str[] = "z\u00df\u6c34\U0001f34c";
                    // or "zß水🍌"
                    // or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9f\x8d\x8c";
    wchar_t warr[29]; // the expected string is 28 characters plus 1 null terminator
    setlocale(LC_ALL, "en_US.utf8");
    swprintf(warr, sizeof warr/sizeof *warr,
              L"Converted from UTF-8: '%s'", narrow_str);
    wprintf(L"%ls\n", warr);
}
```
 Output:



```
Converted from UTF-8: 'zß水🍌'
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.29.2.1 The fwprintf function (p: 403-410)
+ 7.29.2.3 The swprintf function (p: 416)
+ 7.29.2.11 The wprintf function (p: 421)
+ K.3.9.1.1 The fwprintf\_s function (p: 628)
+ K.3.9.1.4 The swprintf\_s function (p: 630-631)
+ K.3.9.1.13 The wprintf\_s function (p: 637-638)

* C99 standard (ISO/IEC 9899:1999):
+ 7.24.2.1 The fwprintf function (p: 349-356)
+ 7.24.2.3 The swprintf function (p: 362)
+ 7.24.2.11 The wprintf function (p: 366)

 ###  See also

 

|  |  |
| --- | --- |
|  [printffprintfsprintfsnprintfprintf\_sfprintf\_ssprintf\_ssnprintf\_s](fprintf "c/io/fprintf")
(C99)(C11)(C11)(C11)(C11) |  prints formatted output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [vwprintfvfwprintfvswprintfvwprintf\_svfwprintf\_svswprintf\_svsnwprintf\_s](vfwprintf "c/io/vfwprintf")
(C95)(C95)(C95)(C11)(C11)(C11)(C11) |  prints formatted wide character output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer using variable argument list  (function) |
|  [fputws](fputws "c/io/fputws")
(C95) |  writes a wide string to a file stream  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fwprintf "cpp/io/c/fwprintf") for `wprintf, fwprintf, swprintf` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fwprintf>

vprintf, vfprintf, vsprintf, vsnprintf, vprintf\_s, vfprintf\_s, vsprintf\_s, vsnprintf\_s
==========================================================================================

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
|  | (1) |  |
| 
```
int vprintf( const char *format, va_list vlist );
```
 | (until C99) |
| 
```
int vprintf( const char *restrict format, va_list vlist );
```
 | (since C99) |
|  | (2) |  |
| 
```
int vfprintf( FILE *stream, const char *format, va_list vlist );
```
 | (until C99) |
| 
```
int vfprintf( FILE *restrict stream, const char *restrict format, 
              va_list vlist );
```
 | (since C99) |
|  | (3) |  |
| 
```
int vsprintf( char *buffer, const char *format, va_list vlist );
```
 | (until C99) |
| 
```
int vsprintf( char *restrict buffer, const char *restrict format, 
              va_list vlist );
```
 | (since C99) |
| 
```
int vsnprintf( char *restrict buffer, size_t bufsz, 
               const char *restrict format, va_list vlist );
```
 |  (4)  | (since C99) |
| 
```
int vprintf_s( const char *restrict format, va_list vlist );
```
 |  (5)  | (since C11) |
| 
```
int vfprintf_s( FILE *restrict stream, const char *restrict format,
                va_list vlist );
```
 |  (6)  | (since C11) |
| 
```
int vsprintf_s( char *restrict buffer, rsize_t bufsz,
                const char *restrict format, va_list vlist );
```
 |  (7)  | (since C11) |
| 
```
int vsnprintf_s( char *restrict buffer, rsize_t bufsz,
                 const char *restrict format, va_list vlist );
```
 |  (8)  | (since C11) |

 Loads the data from the locations, defined by `vlist`, converts them to character string equivalents and writes the results to a variety of sinks.



1) Writes the results to `[stdout](std_streams "c/io/std streams")`. 
2) Writes the results to a file stream `stream`. 
3) Writes the results to a character string `buffer`. 
4) Writes the results to a character string `buffer`. At most `bufsz - 1` characters are written. The resulting character string will be terminated with a null character, unless `bufsz` is zero. If `bufsz` is zero, nothing is written and `buffer` may be a null pointer, however the return value (number of bytes that would be written not including the null terminator) is still calculated and returned. 
5-8) Same as (1-4), 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: * the conversion specifier `%n` is present in `format`
* any of the arguments corresponding to `%s` is a null pointer
* `format` or `buffer` is a null pointer
* `bufsz` is zero or greater than `RSIZE_MAX`
* encoding errors occur in any of string and character conversion specifiers
* (for `vsprintf_s` only), the string to be stored in `buffer` (including the trailing null)) would be exceed `bufsz`

 As with all bounds-checked functions, `vprintf_s` , `vfprintf_s`, `vsprintf_s`, and `vsnprintf_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 [`<stdio.h>`](../io "c/io"). ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  output file stream to write to  |
|  buffer  |  -  |  pointer to a character string to write to  |
|  bufsz  |  -  |  up to bufsz - 1 characters may be written, plus the null terminator  |
|  format  |  -  |  pointer to a null-terminated character string specifying how to interpret the data  |
|  vlist  |  -  |  variable argument list containing the data to print.  |

   
 The **format** string consists of ordinary byte characters (except `%`), which are copied unchanged into the output stream, and conversion specifications. Each conversion specification has the following format:


* introductory `%` character
* (optional) one or more flags that modify the behavior of the conversion:
+ `-`: the result of the conversion is left-justified within the field (by default it is right-justified)
+ `+`: the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative)
+ *space*: if the result of a signed conversion does not start with a sign character, or is empty, space is prepended to the result. It is ignored if `+` flag is present.
+ `#` : *alternative form* of the conversion is performed. See the table below for exact effects otherwise the behavior is undefined.
+ `0` : for integer and floating point number conversions, leading zeros are used to pad the field instead of *space* characters. For integer numbers it is ignored if the precision is explicitly specified. For other conversions using this flag results in undefined behavior. It is ignored if `-` flag is present.

* (optional) integer value or `*` that specifies minimum field width. The result is padded with *space* characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when `*` is used, the width is specified by an additional argument of type `int`, which appears before the argument to be converted and the argument supplying precision if one is supplied. If the value of the argument is negative, it results with the `-` flag specified and positive field width. (Note: This is the minimum width: The value is never truncated.)
+ (optional) `.` followed by integer number or `*`, or neither that specifies *precision* of the conversion. In the case when `*` is used, the *precision* is specified by an additional argument of type `int`, which appears before the argument to be converted, but after the argument supplying minimum field width if one is supplied. If the value of this argument is negative, it is ignored. If neither a number nor `*` is used, the precision is taken as zero. See the table below for exact effects of *precision*.
+ (optional) *length modifier* that specifies the size of the argument (in combination with the conversion format specifier, it specifies the type of the corresponding argument)
+ conversion format specifier

 The following format specifiers are available:




|  ConversionSpecifier  |  Explanation  |  ExpectedArgument Type  |
| --- | --- | --- |
| **LengthModifier****→** | `hh` (C99). | `h` |  (none)  | `l` | `ll` (C99). | `j` (C99). | `z` (C99). | `t` (C99). | `L` |
| `%` |  writes literal `%`. The full conversion specification must be `%%`.  | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A |
| `c` |  writes a **single character**. The argument is first converted to `unsigned char`. If the **l** modifier is used, the argument is first converted to a character string as if by **%ls** with a `wchar_t[2]` argument. | N/A | N/A | `int` | `wint_t` | N/A | N/A | N/A | N/A | N/A |
| `s` |  writes a **character string** The argument must be a pointer to the initial element of an array of characters. *Precision* specifies the maximum number of bytes to be written. If *Precision* is not specified, writes every byte up to and not including the first null terminator. If the **l** specifier is used, the argument must be a pointer to the initial element of an array of `wchar_t`, which is converted to char array as if by a call to `[wcrtomb](../string/multibyte/wcrtomb "c/string/multibyte/wcrtomb")` with zero-initialized conversion state. | N/A | N/A | `char*` | `wchar_t*` | N/A | N/A | N/A | N/A | N/A |
| `d` `i` |  converts a **signed integer** into decimal representation *[-]dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | `signed char` | `short` | `int` | `long` | `long long` | `[intmax\_t](http://en.cppreference.com/w/c/types/integer)` | signed `[size\_t](http://en.cppreference.com/w/c/types/size_t)`
 | `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)` | N/A |
| `o` |  converts an **unsigned integer** into octal representation *oooo*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* precision is increased if necessary, to write one leading zero. In that case if both the converted value and the precision are `​0​`, single `​0​` is written. | `unsigned char` | `unsigned short` | `unsigned int` | `unsigned long` | `unsigned long long` | `[uintmax\_t](http://en.cppreference.com/w/c/types/integer)` | `[size\_t](http://en.cppreference.com/w/c/types/size_t)` | unsigned version of `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)`
 | N/A |
| `x` `X` |  converts an **unsigned integer** into hexadecimal representation *hhhh*. For the `x` conversion letters `abcdef` are used. For the `X` conversion letters `ABCDEF` are used. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. In the *alternative implementation* `0x` or `0X` is prefixed to results if the converted value is nonzero. | N/A |
| `u` |  converts an **unsigned integer** into decimal representation *dddd*. *Precision* specifies the minimum number of digits to appear. The default precision is `1`. If both the converted value and the precision are `​0​` the conversion results in no characters. | N/A |
| `f` `F` |  converts **floating-point number** to the decimal notation in the style *[-]ddd.ddd*. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | `double` | 
`double` (C99)
 | N/A | N/A | N/A | N/A | `long double` |
| `e` `E` |  converts **floating-point number** to the decimal exponent notation. For the `e` conversion style *[-]d.ddd*`e`*±dd* is used. For the `E` conversion style *[-]d.ddd*`E`*±dd* is used. The exponent contains at least two digits, more digits are used only if necessary. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the decimal point character. The default precision is `6`. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A |
| `a` `A` (C99). |  converts **floating-point number** to the hexadecimal exponent notation. For the `a` conversion style *[-]*`0x`*h.hhh*`p`*±d* is used. For the `A` conversion style *[-]*`0X`*h.hhh*`P`*±d* is used. The first hexadecimal digit is not `0` if the argument is a normalized floating point value. If the value is `​0​`, the exponent is also `​0​`. *Precision* specifies the exact number of digits to appear after the hexadecimal point character. The default precision is sufficient for exact representation of the value. In the *alternative implementation* decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A |
| `g` `G` |  converts **floating-point number** to decimal or decimal exponent notation depending on the value and the *precision*. For the `g` conversion style conversion with style `e` or `f` will be performed. For the `G` conversion style conversion with style `E` or `F` will be performed. Let `P` equal the precision if nonzero, `6` if the precision is not specified, or `1` if the precision is `​0​`. Then, if a conversion with style `E` would have an exponent of `X`:* if *P > X ≥ −4*, the conversion is with style `f` or `F` and precision *P − 1 − X*.
* otherwise, the conversion is with style `e` or `E` and precision *P − 1*.

Unless *alternative representation* is requested the trailing zeros are removed, also the decimal point character is removed if no fractional part is left. For infinity and not-a-number conversion style see notes. | N/A | N/A | N/A | N/A | N/A | N/A |
| `n` |  returns the **number of characters written** so far by this call to the function. The result is *written* to the value pointed to by the argument. The specification may not contain any *flag*, *field width*, or *precision*.  | `signed char*` | `short*` | `int*` | `long*` | `long long*` | `[intmax\_t](http://en.cppreference.com/w/c/types/integer)\*` | signed `[size\_t](http://en.cppreference.com/w/c/types/size_t)\*`
 | `[ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)\*` | N/A |
| `p` |  writes an implementation defined character sequence defining a **pointer**.  | N/A | N/A | `void*` | N/A | N/A | N/A | N/A | N/A | N/A |

 The floating point conversion functions convert infinity to `inf` or `infinity`. Which one is used is implementation defined.


Not-a-number is converted to `nan` or `nan(*char\_sequence*)`. Which one is used is implementation defined.


The conversions `F`, `E`, `G`, `A` output `INF`, `INFINITY`, `NAN` instead.


Even though `%c` expects `int` argument, it is safe to pass a `char` because of the integer promotion that takes place when a variadic function is called.


The correct conversion specifications for the fixed-width character types (`[int8\_t](../types/integer "c/types/integer")`, etc) are defined in the header [`<inttypes.h>`](../types/integer "c/types/integer") (although `[PRIdMAX](../types/integer "c/types/integer")`, `[PRIuMAX](../types/integer "c/types/integer")`, etc is synonymous with `%jd`, `%ju`, etc).


The memory-writing conversion specifier `%n` is a common target of security exploits where format strings depend on user input and is not supported by the bounds-checked `printf_s` family of functions.


There is a [sequence point](../language/eval_order "c/language/eval order") after the action of each conversion specifier; this permits storing multiple `%n` results in the same variable or, as an edge case, printing a string modified by an earlier `%n` within the same call.


If a conversion specification is invalid, the behavior is undefined.


###  Return value

 
1-3) The number of characters written if successful or negative value if an error occurred. 
4) The number of characters written if successful or negative value if an error occurred. If the resulting string gets truncated due to `buf_size` limit, function returns the total number of characters (not including the terminating null-byte) which would have been written, if the limit was not imposed.  
5,6) number of characters transmitted to the output stream or negative value if an output error, a runtime constrants violation error, or an encoding error occurred. 
7) number of characters written to `buffer`, not counting the null character (which is always written as long as `buffer` is not a null pointer and `bufsz` is not zero and not greater than `RSIZE_MAX`), or zero on runtime constraint violations, and negative value on encoding errors 
8) number of characters not including the terminating null character (which is always written as long as `buffer` is not a null pointer and `bufsz` is not zero and not greater than `RSIZE_MAX`), which would have been written to `buffer` if `bufsz` was ignored, or a negative value if a runtime constraints violation or an encoding error occurred ###  Notes

 All these functions invoke `va_arg` at least once, the value of `arg` is indeterminate after the return. These functions do not invoke `va_end`, and it must be done by the caller.


`vsnprintf_s`, unlike `vsprintf_s`, will truncate the result to fit within the array pointed to by `buffer`.


###  Example

  
```
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
 
void debug_log(const char *fmt, ...)
{
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    char time_buf[100];
    size_t rc = strftime(time_buf, sizeof time_buf, "%D %T", gmtime(&ts.tv_sec));
    snprintf(time_buf + rc, sizeof time_buf - rc, ".%06ld UTC", ts.tv_nsec / 1000);
 
    va_list args1;
    va_start(args1, fmt);
    va_list args2;
    va_copy(args2, args1);
    char buf[1+vsnprintf(NULL, 0, fmt, args1)];
    va_end(args1);
    vsnprintf(buf, sizeof buf, fmt, args2);
    va_end(args2);
 
    printf("%s [debug]: %s\n", time_buf, buf);
}
 
int main(void)
{
    debug_log("Logging, %d, %d, %d", 1, 2, 3);
}
```
 Possible output:



```
02/20/15 21:58:09.072683 UTC [debug]: Logging, 1, 2, 3
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.6.8 The vfprintf function (p: 238)
+ 7.21.6.10 The vprintf function (p: 239)
+ 7.21.6.12 The vsnprintf function (p: 239-240)
+ 7.21.6.13 The vsprintf function (p: 240)
+ K.3.5.3.8 The vfprintf\_s function (p: 434)
+ K.3.5.3.10 The vprintf\_s function (p: 435)
+ K.3.5.3.12 The vsnprintf\_s function (p: 436-437)
+ K.3.5.3.13 The vsprintf\_s function (p: 437)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.6.8 The vfprintf function (p: 326-327)
+ 7.21.6.10 The vprintf function (p: 328)
+ 7.21.6.12 The vsnprintf function (p: 329)
+ 7.21.6.13 The vsprintf function (p: 329)
+ K.3.5.3.8 The vfprintf\_s function (p: 597)
+ K.3.5.3.10 The vprintf\_s function (p: 598-599)
+ K.3.5.3.12 The vsnprintf\_s function (p: 600)
+ K.3.5.3.13 The vsprintf\_s function (p: 601)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.6.8 The vfprintf function (p: 292)
+ 7.19.6.10 The vprintf function (p: 293)
+ 7.19.6.12 The vsnprintf function (p: 294)
+ 7.19.6.13 The vsprintf function (p: 295)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.6.7 The vfprintf function
+ 4.9.6.8 The vprintf function
+ 4.9.6.9 The vsprintf function

 ###  See also

 

|  |  |
| --- | --- |
|  [vwprintfvfwprintfvswprintfvwprintf\_svfwprintf\_svswprintf\_svsnwprintf\_s](vfwprintf "c/io/vfwprintf")
(C95)(C95)(C95)(C11)(C11)(C11)(C11) |  prints formatted wide character output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer using variable argument list  (function) |
|  [printffprintfsprintfsnprintfprintf\_sfprintf\_ssprintf\_ssnprintf\_s](fprintf "c/io/fprintf")
(C99)(C11)(C11)(C11)(C11) |  prints formatted output to `[stdout](std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [vscanfvfscanfvsscanfvscanf\_svfscanf\_svsscanf\_s](vfscanf "c/io/vfscanf")
(C99)(C99)(C99)(C11)(C11)(C11) |  reads formatted input from `[stdin](std_streams "c/io/std streams")`, a file stream or a buffer using variable argument list  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/vfprintf "cpp/io/c/vfprintf") for `vprintf, vfprintf, vsprintf, vsnprintf` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/vfprintf>

fseek
=====

 

|  Defined in header `<stdio.h>` |  |  |
| --- | --- | --- |
| 
```
int fseek( FILE *stream, long offset, int origin );
```
 |  |  |
| 
```
#define SEEK_SET     /*unspecified*/
#define SEEK_CUR     /*unspecified*/
#define SEEK_END     /*unspecified*/
```
 |  |  |

 Sets the file position indicator for the file stream `stream` to the value pointed to by `offset`.


If the `stream` is open in binary mode, the new position is exactly `offset` bytes measured from the beginning of the file if `origin` is `[SEEK\_SET](../io "c/io")`, from the current file position if `origin` is `[SEEK\_CUR](../io "c/io")`, and from the end of the file if `origin` is `[SEEK\_END](../io "c/io")`. Binary streams are not required to support `[SEEK\_END](../io "c/io")`, in particular if additional null bytes are output.


If the `stream` is open in text mode, the only supported values for `offset` are zero (which works with any `origin`) and a value returned by an earlier call to `[ftell](ftell "c/io/ftell")` on a stream associated with the same file (which only works with `origin` of `[SEEK\_SET](../io "c/io")`).


If the `stream` is wide-oriented, the restrictions of both text and binary streams apply (result of `[ftell](ftell "c/io/ftell")` is allowed with `[SEEK\_SET](../io "c/io")` and zero offset is allowed from `[SEEK\_SET](../io "c/io")` and `[SEEK\_CUR](../io "c/io")`, but not `[SEEK\_END](../io "c/io")`).


In addition to changing the file position indicator, `fseek` undoes the effects of `[ungetc](ungetc "c/io/ungetc")` and clears the end-of-file status, if applicable.


If a read or write error occurs, the error indicator for the stream (`[ferror](ferror "c/io/ferror")`) is set and the file position is unaffected.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  stream  |  -  |  file stream to modify  |
|  offset  |  -  |  number of characters to shift the position relative to origin  |
|  origin  |  -  |  position to which `offset` is added. It can have one of the following values: `[SEEK\_SET](../io "c/io")`, `[SEEK\_CUR](../io "c/io")`, `[SEEK\_END](../io "c/io")` |

 ###  Return value

 `​0​` upon success, nonzero value otherwise.


###  Notes

 After seeking to a non-end position in a wide stream, the next call to any output function may render the remainder of the file undefined, e.g. by outputting a multibyte sequence of a different length.


For text streams, the only valid values of `offset` are `​0​` (applicable to any `origin`) and a value returned by an earlier call to `[ftell](ftell "c/io/ftell")` (only applicable to `SEEK_SET`).


POSIX allows seeking beyond the existing end of file. If an output is performed after this seek, any read from the gap will return zero bytes. Where supported by the filesystem, this creates a *sparse file*.


POSIX also requires that fseek first performs `[fflush](fflush "c/io/fflush")` if there are any unwritten data (but whether the shift state is restored is implementation-defined).


###  Example

 
`fseek` with error checking:



```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    /* Prepare an array of double values. */
    #define SIZE 5
    double A[SIZE] = {1.0, 2.0, 3.0, 4.0, 5.0};
    /* Write array to a file. */
    FILE * fp = fopen("test.bin", "wb");
    fwrite(A, sizeof(double), SIZE, fp);
    fclose (fp);
 
    /* Read the double values into array B. */
    double B[SIZE];
    fp = fopen("test.bin", "rb");
 
    /* Set the file position indicator in front of third double value. */
    if (fseek(fp, sizeof(double) * 2L, SEEK_SET) != 0)
    {
        fprintf(stderr, "fseek() failed in file %s at line # %d\n", __FILE__, __LINE__ - 2);
        fclose(fp);
        return EXIT_FAILURE;
    }
 
    int ret_code = fread(B, sizeof(double), 1, fp); /* read one double value  */
    printf("ret_code == %d\n", ret_code);           /* print the number of values read */
    printf("B[0] == %.1f\n", B[0]);                 /* print one value */
 
    fclose(fp);
    return EXIT_SUCCESS;
}
```
 Possible output:



```
ret_code == 1
B[0] == 3.0
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.21.9.2 The fseek function (p: 245)

* C11 standard (ISO/IEC 9899:2011):
+ 7.21.9.2 The fseek function (p: 336-337)

* C99 standard (ISO/IEC 9899:1999):
+ 7.19.9.2 The fseek function (p: 302-303)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.9.9.2 The fseek function

 ###  See also

 

|  |  |
| --- | --- |
|  [fsetpos](fsetpos "c/io/fsetpos") |  moves the file position indicator to a specific location in a file  (function) |
|  [fgetpos](fgetpos "c/io/fgetpos") |  gets the file position indicator  (function) |
|  [ftell](ftell "c/io/ftell") |  returns the current file position indicator  (function) |
|  [rewind](rewind "c/io/rewind") |  moves the file position indicator to the beginning in a file  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/io/c/fseek "cpp/io/c/fseek") for `fseek` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/io/fseek>

\_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 part.


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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.3.1/4 \_Complex\_I (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.3.1/4 \_Complex\_I (p: 136)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/Complex_I>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/CMPLX>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/imaginary>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/I>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/cimag>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/creal>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/carg>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/Imaginary_I>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/cabs>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/cproj>

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`, \(\small e^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 \(\small{\rm cis}(y)\)cis(y) is \(\small \cos(y)+{\rm i}\sin(y)\)cos(y) + i sin(y).


###  Notes

 The complex exponential function \(\small e^z\)ez  
 for \(\small z = x + {\rm i}y\)z = x+iy equals \(\small e^x {\rm cis}(y)\)ex  
 cis(y), or, \(\small e^x (\cos(y)+{\rm i}\sin(y))\)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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/cexp>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/csqrt>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/catan>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/ccos>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/csin>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/casinh>

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 \(\small \arcsin({\rm i}y) = {\rm i}{\rm arsinh}(y)\)arcsin(iy) = i arsinh(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 \(\small \arcsin z = -{\rm i}\ln({\rm i}z+\sqrt{1-z^2})\)arcsin z = -*i*ln(*i*z + √1-z2  
) For any z, \(\small{ \arcsin(z) = \arccos(-z) - \frac{\pi}{2} }\)arcsin(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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/casin>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/mbsinit>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/btowc>

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\u00B2 =", z * z);
    double complex z2 = ccos(2.0 * carg(z)) + csin(2.0 * carg(z))*I;
    print_complex("z\u00B2 =", cabs(z) * cabs(z) * z2);
}
```
 Output:



```
z  = -1.000000+2.000000*i
z² = -3.000000-4.000000*i
z² = -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) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/complex>

FLT\_EVAL\_METHOD
=================

 

|  Defined in header `<float.h>` |  |  |
| --- | --- | --- |
| 
```
#define FLT_EVAL_METHOD /* implementation defined */
```
 |  | (since C99) |

 Specifies range and precision of floating-point values obtained from floating-point constants and from all operations (operators, implicit conversions of operands) except assignment, cast, and library function call.




|  Value  |  Explanation  |
| --- | --- |
|  negative values except `-1` |  implementation-defined behavior  |
| `-1` |  the default precision is not known  |
| `0` |  all operations and constants evaluate in the range and precision of the type used. Additionally, `float_t` and `double_t` are equivalent to `float` and `double` respectively  |
| `1` |  all operations and constants evaluate in the range and precision of `double`. Additionally, both `float_t` and `double_t` are equivalent to `double` |
| `2` |  all operations and constants evaluate in the range and precision of `long double`. Additionally, both `float_t` and `double_t` are equivalent to `long double` |

 ###  Notes

 Regardless of the value of `FLT_EVAL_METHOD`, any floating-point expression may be *contracted*, that is, calculated as if all intermediate results have infinite range and precision (unless [#pragma](../../preprocessor/impl "c/preprocessor/impl") `STDC FP_CONTRACT` is off).


Cast and assignment strip away any extraneous range and precision: this models the action of storing a value from an extended-precision FPU register into a standard-sized memory location.


###  See also

 

|  |  |
| --- | --- |
|  [float\_tdouble\_t](../../numeric/math/float_t "c/numeric/math/float t")
(C99)(C99) |  most efficient floating-point type at least as wide as `float` or `double`  (typedef) |
| [C++ documentation](https://en.cppreference.com/w/cpp/types/climits/FLT_EVAL_METHOD "cpp/types/climits/FLT EVAL METHOD") for `FLT_EVAL_METHOD` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/types/limits/FLT_EVAL_METHOD>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/mbrtowc>

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` 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>`](../wide "c/string/wide").
 ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/mbsrtowcs>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/catanh>

C keywords: \_Imaginary (since C99)
===================================

 ###  Usage

 * [imaginary floating type](../language/arithmetic_types#Imaginary_floating_types "c/language/arithmetic types") specifier (since C99)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Imaginary>

mbrtoc8
=======

 

|  Defined in header `<uchar.h>` |  |  |
| --- | --- | --- |
| 
```
size_t mbrtoc8( char8_t * restrict pc8, const char * restrict s,
                size_t n, mbstate_t * restrict 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/mbrtoc8>

c8rtomb
=======

 

|  Defined in header `<uchar.h>` |  |  |
| --- | --- | --- |
| 
```
size_t c8rtomb( char* restrict s, char8_t c8, mbstate_t* restrict 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/c8rtomb>

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. The macro is always defined and the encoding is always UTF-16. (since C23) 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](https://open-std.org/JTC1/SC22/WG14/www/docs/n2059.htm#dr_488).


###  Example

 
Note: this example assumes the fix for the defect report [DR488](https://open-std.org/JTC1/SC22/WG14/www/docs/n2059.htm#dr_488) is applied.



```
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <uchar.h>
 
mbstate_t state;
 
int main(void)
{
    setlocale(LC_ALL, "en_US.utf8");
    const char16_t in[] = u"zß水🍌"; // or "z\u00df\u6c34\U0001F34C"
    const 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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.28.1.2 The c16rtomb function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.28.1.2 The c16rtomb function (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/c16rtomb>

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. The macro is always defined and the encoding is always UTF-32. (since C23) 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 <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <uchar.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.30.1.6 The c32rtomb function (p: 411)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/c32rtomb>

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. The macro is always defined and the encoding is always UTF-32. (since C23) 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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.30.1.5 The mbrtoc32 function (p: 410)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/mbrtoc32>

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 <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.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)
{
    for (const char* end = str + strlen(str); 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/mblen>

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 character `'\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 <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.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 = 0;
    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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.24.7.2 The mbtowc function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.22.7.2 The mbtowc function (p: 260)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/mbtowc>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/conj>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/clog>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/cpow>

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. The macro is always defined and the encoding is always UTF-16. (since C23) 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 <locale.h>
#include <stdio.h>
#include <uchar.h>
 
mbstate_t state;
 
int main(void)
{
    setlocale(LC_ALL, "en_US.utf8");
    const char in[] = u8"zß水🍌"; // or "z\u00df\u6c34\U0001F34C"
    const 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];
    const char *p_in = in, *end = in + in_sz;
    char16_t *p_out = out;
    for (size_t rc; (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;
        };
    }
 
    const 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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.30.1.3 The mbrtoc16 function (p: 408-409)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/mbrtoc16>

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` 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>`](../../program "c/program").

 ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/wctomb>

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` 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>`](../../program "c/program").

 ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/wcstombs>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/wctob>

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` 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>`](../wide "c/string/wide").
 ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/wcsrtombs>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/mbrlen>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/mbstate_t>

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` 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>`](../wide "c/string/wide").

 ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/wcrtomb>

char8\_t
========

 

|  Defined in header `<uchar.h>` |  |  |
| --- | --- | --- |
| 
```
typedef unsigned char char8_t;
```
 |  | (since C23) |

 `char8_t` is an unsigned integer type used for UTF-8 and is the same type as `unsigned char`.


###  Example

  
```
#include <uchar.h>
#include <stdio.h>
 
int main(void)
{
    char8_t str[] = u8"zß水🍌"; // or "z\u00df\u6c34\U0001f34c"
    size_t str_sz = sizeof str; // sizeof *str == 1 by definition
    printf("%zu UTF-8 code units: [ ", str_sz);
    for (size_t n = 0; n < str_sz; ++n)
        printf("%02X ", str[n]);
    printf("]\n");
}
```
 Possible output:



```
11 UTF-8 code units: [ 7A C3 9F E6 B0 B4 F0 9F 8D 8C 00 ]
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.30 Unicode utilities <uchar.h> (p: 410)

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/language/types "cpp/language/types") for `Fundamental types` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/char8_t>

char16\_t
=========

 

|  Defined in header `<uchar.h>` |  |  |
| --- | --- | --- |
| 
```
typedef uint_least16_t char16_t;
```
 |  | (since C11) |

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


###  Notes

 On any given platform, by the definition of `[uint\_least16\_t](http://en.cppreference.com/w/c/types/integer)`, 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 <stdio.h>
#include <uchar.h>
 
int main(void)
{
    const char16_t wcs[] = u"zß水🍌"; // or "z\u00df\u6c34\U0001f34c"
    const 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

 * C17 standard (ISO/IEC 9899:2018):
+ 7.28 Unicode utilities <uchar.h> (p: 292)
+ 7.20.1.2 Minimum-width integer types (p: 212-213)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/char16_t>

C keywords: \_Generic (since C11)
=================================

 ###  Usage

 * [Type-generic expression](../language/generic "c/language/generic") (since C11)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Generic>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/isalnum>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/isblank>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/isalpha>

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 <ctype.h>
#include <limits.h>
#include <stdio.h>
 
int main(void)
{
    for (int ndx = 0; UCHAR_MAX >= ndx; ++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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/isxdigit>

C keywords: \_Complex (since C99)
=================================

 ###  Usage

 * [`_Complex` type](../language/arithmetic_types#Complex_floating_types "c/language/arithmetic types"): as the declaration of the type (since C99)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Complex>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/isupper>

isspace
=======

 

|  Defined in header `<ctype.h>` |  |  |
| --- | --- | --- |
| 
```
int isspace( int ch );
```
 |  |  |

 Checks if the given character is either.


* A standard white-space character:
+ Space (0x20, `' '`),
+ Form feed (0x0c, `'\f'`),
+ Line feed (0x0a, `'\n'`),
+ Carriage return (0x0d, `'\r'`),
+ Horizontal tab (0x09, `'\t'`),
+ Vertical tab (0x0b, `'\v'`),

* Or a locale-specific white-space character.

 The behavior is undefined if the value of `ch` is not representable as `unsigned char` and is not equal to `[EOF](../../io "c/io")`.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ch  |  -  |  character to classify  |

 ###  Return value

 Non-zero value if the character is a whitespace character, zero otherwise.


###  Example

  
```
#include <ctype.h>
#include <limits.h>
#include <stdio.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.4.1.10 The isspace function (p: TBD)

* 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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/isspace>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/islower>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/iscntrl>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/isgraph>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/toupper>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/ispunct>

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`. The implied radix is always 10.


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

 If the value of the result cannot be represented, i.e. the converted value falls out of range of the corresponding return type, the behavior is undefined.


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


###  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("0042")); // treated as a decimal number with leading zeros
    printf("%i\n", atoi("0x2A")); // only leading zero is converted discarding "x2A"
    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
42
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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/atoi>

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 `[isspace](isspace "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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/atof>

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 set the pointer pointed to by `str_end` to point to the character past the last numeric 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("\n --> 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

 * C17 standard (ISO/IEC 9899:2018):
+ 7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions (p: 251-252)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strtol>

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, might be set to a position past the last character interpreted  |
|  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 <errno.h>
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    const char *p = "10 200000000000000000000000000000 30 -40 - 42";
    printf("Parsing '%s':\n", p);
    char *end = NULL;
    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)
        {
            errno = 0;
            printf("range error, got ");
        }
        printf("%lu\n", i);
    }
    printf("After the loop p points to '%s'\n", p);
}
```
 Output:



```
Parsing '10 200000000000000000000000000000 30 -40 - 42':
'10' -> 10
' 200000000000000000000000000000' -> range error, got 18446744073709551615
' 30' -> 30
' -40' -> 18446744073709551576
After the loop p points to ' - 42'
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.24.1.7 The strtol, strtoll, strtoul, and strtoull functions (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions (p: 251-252)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strtoul>

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 `endptr` 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 <errno.h>
#include <inttypes.h>
#include <stdio.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.8.2.3 The strtoimax and strtoumax functions (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.8.2.3 The strtoimax and strtoumax functions (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strtoimax>

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 `[isspace](isspace "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 (`[errno](../../error/errno "c/error/errno")` is set to `[ERANGE](../../error/errno_macros "c/error/errno macros")`) 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strtof>

strfromf, strfromd, strfromld
=============================

 

|  Defined in header `<stdlib.h>` |  |  |
| --- | --- | --- |
| 
```
int strfromf( char *restrict s, size_t n, const char *restrict format, float fp );
```
 |  | (since C23) |
| 
```
int strfromd( char *restrict s, size_t n, const char *restrict format, double fp );
```
 |  | (since C23) |
| 
```
int strfroml( char *restrict s, size_t n, const char *restrict format, long double fp );
```
 |  | (since C23) |

 Converts a floating-point value to a byte string.


The functions are equivalent to `[snprintf](http://en.cppreference.com/w/c/io/fprintf)(s, n, format, fp)`, except that the format string shall only contain the character %, an optional precision that does not contain an asterisk \*, and one of the conversion specifiers `a`, `A`, `e`, `E`, `f`, `F`, `g`, or `G`, which applies to the type `double`, `float`, or `long double`) indicated by the function suffix (rather than by a length modifier). Use of these functions with any other format string results in undefined behavior.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  s  |  -  |  pointer to a character string to write to  |
|  n  |  -  |  up to n - 1 characters may be written, plus the null terminator  |
|  format  |  -  |  pointer to a null-terminated byte string specifying how to interpret the data  |
|  fp  |  -  |  floating-point value to convert  |

 ###  Return value

 The number of characters that would have been written had `n` been sufficiently large, not counting the terminating null character. Thus, the null-terminated output has been completely written if and only if the returned value is both nonnegative and less than `n`.


###  Example

 ###  Reference

 * C23 standard (ISO/IEC 9899:2023):
+ 7.24.1.3 The strfromd, strfromf, and strfroml functions

 ###  See also

 

|  |  |
| --- | --- |
|  [printffprintfsprintfsnprintfprintf\_sfprintf\_ssprintf\_ssnprintf\_s](../../io/fprintf "c/io/fprintf")
(C99)(C11)(C11)(C11)(C11) |  prints formatted output to `[stdout](../../io/std_streams "c/io/std streams")`, a file stream or a buffer  (function) |
|  [strtofstrtodstrtold](strtof "c/string/byte/strtof")
(C99)(C99) |  converts a byte string to a floating point value  (function) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strfromf>

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` 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>`](../byte "c/string/byte"). ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strcat>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/tolower>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strxfrm>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strdup>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/isprint>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/ctan>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/csinh>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/cacosh>

char32\_t
=========

 

|  Defined in header `<uchar.h>` |  |  |
| --- | --- | --- |
| 
```
typedef uint_least32_t char32_t;
```
 |  | (since C11) |

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


###  Notes

 On any given platform, by the definition of `[uint\_least32\_t](http://en.cppreference.com/w/c/types/integer)`, 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 <stdio.h>
#include <uchar.h>
 
int main(void)
{
    const char32_t wc[] = U"zß水🍌"; // or "z\u00df\u6c34\U0001f34c"
    const 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

 * C17 standard (ISO/IEC 9899:2018):
+ 7.28 Unicode utilities <uchar.h> (p: 292)
+ 7.20.1.2 Minimum-width integer types (p: 212-213)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/multibyte/char32_t>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strndup>

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` 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>`](../byte "c/string/byte"). ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strlen>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strcmp>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/isdigit>

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` 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>`](../byte "c/string/byte"). ###  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); // r4 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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.26.3.2 The strncat function (p: 379)
+ K.3.7.2.2 The strncat\_s function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.24.3.2 The strncat function (p: 265-266)
+ K.3.7.2.2 The strncat\_s function (p: 449-450)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strncat>

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` 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>`](../byte "c/string/byte"). ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strncpy>

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 <stdio.h>
#include <string.h>
 
void demo(const char* lhs, const char* rhs, int sz)
{
    const int rc = strncmp(lhs, rhs, sz);
    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);
    else
        printf("First %d chars of [%s] equal [%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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.24.4.4 The strncmp function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.24.4.4 The strncmp function (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strncmp>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strcoll>

strchr
======

 

|  Defined in header `<string.h>` |  |  |
| --- | --- | --- |
| 
```
char *strchr( const char *str, int ch );
```
 |  (1)  |  |
| 
```
/*QChar*/ *strchr( /*QChar*/ *str, int ch );
```
 |  (2)  | (since C23) |

 
1) 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'`. 
2) Type-generic function equivalent to (1). Let `T` be an unqualified character object type. * If `str` is of type `const T*`, the return type is `const char*`.
* Otherwise, if `str` is of type `T*`, the return type is `char*`.
* Otherwise, the behavior is undefined.

 If a macro definition of each of these generic functions is suppressed to access an actual function (e.g. if `(strchr)` or a function pointer is used), the actual function declaration (1) becomes visible. 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strchr>

strrchr
=======

 

|  Defined in header `<string.h>` |  |  |
| --- | --- | --- |
| 
```
char *strrchr( const char *str, int ch );
```
 |  (1)  |  |
| 
```
/*QChar*/ *strrchr( /*QChar*/ *str, int ch );
```
 |  (2)  | (since C23) |

 
1) 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'`. 
2) Type-generic function equivalent to (1). Let `T` be an unqualified character object type. * If `str` is of type `const T*`, the return type is `const char*`.
* Otherwise, if `str` is of type `T*`, the return type is `char*`.
* Otherwise, the behavior is undefined.

 If a macro definition of each of these generic functions is suppressed to access an actual function (e.g. if `(strrchr)` or a function pointer is used), the actual function declaration (1) becomes visible. 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strrchr>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strspn>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strcspn>

strpbrk
=======

 

|  Defined in header `<string.h>` |  |  |
| --- | --- | --- |
| 
```
char *strpbrk( const char *dest, const char *breakset );
```
 |  (1)  |  |
| 
```
/*QChar*/ *strpbrk( /*QChar*/ *dest, const char *breakset );
```
 |  (2)  | (since C23) |

 
1 ) 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. 
2) Type-generic function equivalent to (1). Let `T` be an unqualified character object type. * If `dest` is of type `const T*`, the return type is `const char*`.
* Otherwise, if `dest` is of type `T*`, the return type is `char*`.
* Otherwise, the behavior is undefined.

 If a macro definition of each of these generic functions is suppressed to access an actual function (e.g. if `(strpbrk)` or a function pointer is used), the actual function declaration (1) becomes visible. 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strpbrk>

strstr
======

 

|  Defined in header `<string.h>` |  |  |
| --- | --- | --- |
| 
```
char *strstr( const char *str, const char *substr );
```
 |  (1)  |  |
| 
```
/*QChar*/ *strstr( /*QChar*/ *str, const char *substr );
```
 |  (2)  | (since C23) |

 
1) 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. 
2) Type-generic function equivalent to (1). Let `T` be an unqualified character object type. * If `str` is of type `const T*`, the return type is `const char*`.
* Otherwise, if `str` is of type `T*`, the return type is `char*`.
* Otherwise, the behavior is undefined.

 If a macro definition of each of these generic functions is suppressed to access an actual function (e.g. if `(strstr)` or a function pointer is used), the actual function declaration (1) becomes visible. 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strstr>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/memcmp>

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` 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>`](../byte "c/string/byte"). ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/memcpy>

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` 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>`](../byte "c/string/byte"). ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/memmove>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/memccpy>

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>`](../byte "c/string/byte"). ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strerror>

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 included in POSIX print category.


###  Example

  
```
#include <locale.h>
#include <stdio.h>
#include <wchar.h>
#include <wctype.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.30.2.1.8 The iswprint function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.30.2.1.8 The iswprint function (p: TBD)

* 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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswprint>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswspace>

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 call 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` 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>`](../byte "c/string/byte"). ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/strtok>

memchr
======

 

|  Defined in header `<string.h>` |  |  |
| --- | --- | --- |
| 
```
void *memchr( const void *ptr, int ch, size_t count );
```
 |  (1)  |  |
| 
```
/*QVoid*/ *memchr( /*QVoid*/ *ptr, int ch, size_t count );
```
 |  (2)  | (since C23) |

 
1) 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`. 
2) Type-generic function equivalent to (1). Let `T` be an unqualified object type (including `void`). * If `ptr` is of type `const T*`, the return type is `const void*`.
* Otherwise, if `ptr` is of type `T*`, the return type is `void*`.
* Otherwise, the behavior is undefined.

 If a macro definition of each of these generic functions is suppressed to access an actual function (e.g. if `(memchr)` or a function pointer is used), the actual function declaration (1) becomes visible. 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/memchr>

memset, memset\_explicit, memset\_s
===================================

 

|  Defined in header `<string.h>` |  |  |
| --- | --- | --- |
| 
```
void *memset( void *dest, int ch, size_t count );
```
 |  (1)  |  |
| 
```
void *memset_explicit( void *dest, int ch, size_t count );
```
 |  (2)  | (since C23) |
| 
```
errno_t memset_s( void *dest, rsize_t destsz, int ch, rsize_t count );
```
 |  (3)  | (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 is safe for sensitive information. 
3) 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` 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>`](../byte "c/string/byte"). ###  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,2) A copy of `dest`
 
3) 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_explicit` and `memset_s`: they are 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/byte/memset>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswcntrl>

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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.30.2.1.6 The iswgraph function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.30.2.1.6 The iswgraph function (p: TBD)

* 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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswgraph>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/cacos>

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 an alphabetic character, zero otherwise.


###  Notes

 [ISO 30112](https://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf) specifies which Unicode characters are include in POSIX alpha category.


###  Example

  
```
#include <locale.h>
#include <stdio.h>
#include <wchar.h>
#include <wctype.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));
}
```
 Possible output:



```
in the default locale, iswalpha(0xb83) = 0
in Unicode locale, iswalpha(0xb83) = 1
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ TBD The iswalpha function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.30.2.1.2 The iswalpha function (p: 327)

* 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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswalpha>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/ctanh>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswlower>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswxdigit>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/random/srand>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/complex/ccosh>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswupper>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/random/RAND_MAX>

C keywords: alignas (since C23)
===============================

 ###  Usage

 * [`alignas`](../language/alignas "c/language/alignas") alignment specifier. (since C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/alignas>

C keywords: alignof (since C23)
===============================

 ###  Usage

 * [`alignof` operator](../language/alignof "c/language/alignof") (since C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/alignof>

C keywords: bool (since C23)
============================

 ###  Usage

 * [boolean type](../language/arithmetic_types#Boolean_type "c/language/arithmetic types"): as the declaration of the type (since C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/bool>

C keywords: break
=================

 ###  Usage

 * [`break` statement](../language/break "c/language/break"): as the declaration of the statement

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/break>

C keywords: case
================

 ###  Usage

 * [`switch` statement](../language/switch "c/language/switch"): as the declaration of the case labels

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/case>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/char>

C keywords: const
=================

 ###  Usage

 * [`const` type qualifier](../language/const "c/language/const")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/const>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/default>

C keywords: do
==============

 ###  Usage

 * [`do-while` loop](../language/do "c/language/do"): as the declaration of the loop

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/do>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/double>

C keywords: auto
================

 ###  Usage

 * [automatic duration storage-class specifier](../language/storage_duration "c/language/storage duration") with no linkage.
* type inference (since C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/auto>

C keywords: continue
====================

 ###  Usage

 * [`continue` statement](../language/continue "c/language/continue"): as the declaration of the statement

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/continue>

C keywords: else
================

 ###  Usage

 * [`if` statement](../language/if "c/language/if"): as the declaration of the alternative branch

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/else>

C keywords: enum
================

 ###  Usage

 * [declaration of an enumeration type](../language/enum "c/language/enum")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/enum>

C keywords: extern
==================

 ###  Usage

 * [static duration storage-class specifier](../language/storage_duration "c/language/storage duration") with either internal or more usually external linkage.

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/extern>

C keywords: false (since C23)
=============================

 ###  Usage

 * [predefined boolean constant](../language/bool_constant "c/language/bool constant")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/false>

C keywords: float
=================

 ###  Usage

 * [`float` type](../language/types "c/language/types"): as the declaration of the type

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/float>

C keywords: goto
================

 ###  Usage

 * [`goto` statement](../language/goto "c/language/goto"): as the declaration of the statement

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/goto>

C keywords: for
===============

 ###  Usage

 * [`for` loop](../language/for "c/language/for"): as the declaration of the loop

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/for>

C keywords: if
==============

 ###  Usage

 * [`if` statement](../language/if "c/language/if"): as the declaration of the `if` statement

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/if>

C keywords: inline (since C99)
==============================

 ###  Usage

 * [inline function specifier](../language/inline "c/language/inline") (since C99)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/inline>

C keywords: int
===============

 ###  Usage

 * [`int` type](../language/types "c/language/types"): as the declaration of the type

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/int>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/random/rand>

C keywords: long
================

 ###  Usage

 * [`long` type modifier](../language/types "c/language/types")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/long>

C keywords: nullptr (since C23)
===============================

 ###  Usage

 * [`nullptr` pointer constant](../language/nullptr "c/language/nullptr") (since C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/nullptr>

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.

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/register>

C keywords: restrict (since C99)
================================

 ###  Usage

 * [`restrict` type qualifier](../language/restrict "c/language/restrict") (since C99)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/restrict>

C keywords: return
==================

 ###  Usage

 * [`return` statement](../language/return "c/language/return"): as the declaration of the statement

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/return>

C keywords: short
=================

 ###  Usage

 * [`short` type modifier](../language/types "c/language/types")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/short>

C keywords: signed
==================

 ###  Usage

 * [`signed` type modifier](../language/types "c/language/types")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/signed>

C keywords: sizeof
==================

 ###  Usage

 * [`sizeof` operator](../language/sizeof "c/language/sizeof")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/sizeof>

C keywords: static\_assert (since C23)
======================================

 ###  Usage

 * [static assert declaration](../language/_static_assert "c/language/ Static assert") (since C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/static_assert>

C keywords: struct
==================

 ###  Usage

 * [declaration of a compound type](../language/struct "c/language/struct")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/struct>

C keywords: static
==================

 ###  Usage

 * [declarations of file scope with static storage duration and internal linkage](../language/storage_duration "c/language/storage duration")
* [definitions of block scope variables with static storage duration and initialized once](../language/storage_duration#Static_local_variables "c/language/storage duration")

 

|  |  |
| --- | --- |
| * static [array indices](../language/array "c/language/array") in function parameter declarations.
 | (since C99) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/static>

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 a 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 <locale.h>
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
 
void test(wchar_t a3, wchar_t u3, wchar_t j3)
{
    printf("\t '%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'３'; // the full-width 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);
}
```
 Possible output:



```
In American locale:
         '3'  '三' '３'
iswdigit: 1    0    0
jdigit:   0    0    0
 
In Japanese locale:
         '3'  '三' '３'
iswdigit: 1    0    0
jdigit:   0    0    1
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ TBD 7.30.2.1.5 The iswdigit function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.30.2.1.5 The iswdigit function (p: 327)

* 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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswdigit>

C keywords: switch
==================

 ###  Usage

 * [`switch` statement](../language/switch "c/language/switch"): as the declaration of the statement

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/switch>

C keywords: thread\_local (since C23)
=====================================

 ###  Usage

 * [thread storage-class specifier](../language/storage_duration "c/language/storage duration") (since C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/thread_local>

C keywords: true (since C23)
============================

 ###  Usage

 * [predefined boolean constant](../language/bool_constant "c/language/bool constant")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/true>

C keywords: typedef
===================

 ###  Usage

 * [`typedef` declaration](../language/typedef "c/language/typedef")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/typedef>

C keywords: union
=================

 ###  Usage

 * [declaration of a union type](../language/union "c/language/union")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/union>

C keywords: typeof (since C23)
==============================

 ###  Usage

 * [`typeof` operator](../language/typeof "c/language/typeof") (since C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/typeof>

C keywords: typeof\_unqual (since C23)
======================================

 ###  Usage

 * [`typeof` operator](../language/typeof "c/language/typeof") that removes qualifiers (since C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/typeof_unqual>

C keywords: unsigned
====================

 ###  Usage

 * [`unsigned` type modifier](../language/types "c/language/types")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/unsigned>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/void>

C keywords: volatile
====================

 ###  Usage

 * [`volatile` type qualifier](../language/volatile "c/language/volatile")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/volatile>

C keywords: \_Decimal32 (since C23)
===================================

 ###  Usage

 * [`_Decimal32` type](../language/types "c/language/types"): as the declaration of the type (since C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Decimal32>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/while>

C keywords: \_Atomic (since C11)
================================

 ###  Usage

 * [atomic type specifier and qualifier](../language/atomic "c/language/atomic") (since C11)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Atomic>

C keywords: \_Decimal128 (since C23)
====================================

 ###  Usage

 * [`_Decimal128` type](../language/types "c/language/types"): as the declaration of the type (since C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Decimal128>

C keywords: \_Static\_assert (since C11)(deprecated in C23)
===========================================================

 ###  Usage

 * [static assert declaration](../language/_static_assert "c/language/ Static assert") (since C11)(deprecated in C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Static_assert>

C keywords: \_Thread\_local (since C11)
=======================================

 ###  Usage

 * [thread storage-class specifier](../language/storage_duration "c/language/storage duration") (since C11)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Thread_local>

thread\_local
=============

 

|  Defined in header `<threads.h>` |  |  |
| --- | --- | --- |
| 
```
#define thread_local _Thread_local
```
 |  | (since C11) (removed in C23) |

 Convenience macro which can be used to specify that an object has [thread-local storage duration](../language/storage_duration "c/language/storage duration").


###  Notes

 Since C23, `thread_local` is itself a keyword, which may also be a predefined macro, so `<threads.h>` no longer provides it.


###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/thread_local>

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](../../locale/lc_categories "c/locale/LC categories")` 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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.30.2.2.2 The wctype function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.30.2.2.2 The wctype function (p: TBD)

* 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](../../locale/lc_categories "c/locale/LC categories")` category  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/string/wide/wctype "cpp/string/wide/wctype") for `wctype` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wctype>

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](../../locale/lc_categories "c/locale/LC categories")` category identified by `desc`.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  wc  |  -  |  the wide character to classify  |
|  desc  |  -  |  the `[LC\_CTYPE](../../locale/lc_categories "c/locale/LC categories")` 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](../../locale/lc_categories "c/locale/LC categories")` facet of the current C locale, zero otherwise.


###  Example

  
```
#include <locale.h>
#include <stdio.h>
#include <wchar.h>
#include <wctype.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?\t%s\n", cats[n], classify(L'\u6c34', cats[n]));
}
```
 Output:



```
The character 水 is...
digit?  false
alpha?  true
space?  false
cntrl?  false
jkanji? true
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.30.2.2.1 The iswctype function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.30.2.2.1 The iswctype function (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswctype>

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 an alphanumeric character, zero otherwise.


###  Notes

 [ISO 30112](https://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 <locale.h>
#include <wchar.h>
#include <wctype.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));
}
```
 Possible output:



```
in the default locale, iswalnum(0x13ad) = 0
in Unicode locale, iswalnum(0x13ad) = 1
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ TBD The iswalnum function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.30.2.1.1 The iswalnum function (p: 327)

* 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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswalnum>

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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswblank>

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](https://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)
{
    const 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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.30.2.1.9 The iswpunct function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.30.2.1.9 The iswpunct function (p: TBD)

* 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`** |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/iswpunct>

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 <locale.h>
#include <stdio.h>
#include <wchar.h>
#include <wctype.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.30.3.1.1 The towlower function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.30.3.1.1 The towlower function (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/towlower>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/towupper>

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](../../locale/lc_categories "c/locale/LC categories")` mapping category identified by `desc`.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  wc  |  -  |  the wide character to map  |
|  desc  |  -  |  the `[LC\_CTYPE](../../locale/lc_categories "c/locale/LC categories")` 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](../../locale/lc_categories "c/locale/LC categories")` 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");
    const 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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.30.3.2.1 The towctrans function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.30.3.2.1 The towctrans function (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/towctrans>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcstoul>

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 `[iswspace](iswspace "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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcstof>

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](../../types/integer "c/types/integer")` or `[uintmax\_t](../../types/integer "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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcstoimax>

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` 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>`](../../io "c/io").. ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcslen>

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` 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>`](../wide "c/string/wide").

 ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcsncpy>

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` 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>`](../wide "c/string/wide").

 ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcscat>

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` 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>`](../wide "c/string/wide").

 ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcsncat>

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 <locale.h>
#include <stdio.h>
#include <wchar.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.29.4.4.1 The wcscmp function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.29.4.4.1 The wcscmp function (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcscmp>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcsncmp>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcscoll>

C keywords: \_Decimal64 (since C23)
===================================

 ###  Usage

 * [`_Decimal64` type](../language/types "c/language/types"): as the declaration of the type (since C23)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/_Decimal64>

wcsrchr
=======

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
wchar_t *wcsrchr( const wchar_t *str, wchar_t ch );
```
 |  (1)  | (since C95) |
| 
```
/*QWchar_t*/ *wcsrchr( /*QWchar_t*/ *str, wchar_t ch );
```
 |  (2)  | (since C23) |

 
1) Finds the last occurrence of the wide character `ch` in the wide string pointed to by `str`. 
2) Type-generic function equivalent to (1). Let `T` be an unqualified wide character object type. * If `str` is of type `const T*`, the return type is `const wchar_t*`.
* Otherwise, if `str` is of type `T*`, the return type is `wchar_t*`.
* Otherwise, the behavior is undefined.

 If a macro definition of each of these generic functions is suppressed to access an actual function (e.g. if `(wcsrchr)` or a function pointer is used), the actual function declaration (1) becomes visible. ###  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 <locale.h>
#include <stdio.h>
#include <wchar.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");
 
    cat ? printf("The character 猫 found at position %td\n", cat - arr)
        : puts("The character 猫 not found");
 
    dog ? printf("The character 犬 found at position %td\n", dog - arr)
        : puts("The character 犬 not found");
}
```
 Output:



```
The character 猫 found at position 4
The character 犬 not found
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.31.4.6.4 The wcsrchr function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.29.4.5.4 The wcsrchr function (p: 318)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcsrchr>

wcschr
======

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
wchar_t *wcschr( const wchar_t *str, wchar_t ch );
```
 |  (1)  | (since C95) |
| 
```
/*QWchar_t*/ *wcschr( /*QWchar_t*/ *str, wchar_t ch );
```
 |  (2)  | (since C23) |

 
1) Finds the first occurrence of the wide character `ch` in the wide string pointed to by `str`. 
2) Type-generic function equivalent to (1). Let `T` be an unqualified wide character object type. * If `str` is of type `const T*`, the return type is `const wchar_t*`.
* Otherwise, if `str` is of type `T*`, the return type is `wchar_t*`.
* Otherwise, the behavior is undefined.

 If a macro definition of each of these generic functions is suppressed to access an actual function (e.g. if `(wcschr)` or a function pointer is used), the actual function declaration (1) becomes visible. ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcschr>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcsspn>

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` 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>`](../wide "c/string/wide").

 ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wmemcpy>

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.

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/keyword/fortran>

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 <locale.h>
#include <stdio.h>
#include <wchar.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.29.4.6.2 The wmemset function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.29.4.6.2 The wmemset function (p: TBD)

* 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\_explicitmemset\_s](../byte/memset "c/string/byte/memset")
(C23)(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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wmemset>

wmemchr
=======

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
wchar_t *wmemchr( const wchar_t *ptr, wchar_t ch, size_t count );
```
 |  (1)  | (since C95) |
| 
```
/*QWchar_t*/ *wmemchr( /*Qwchar_t*/ *ptr, wchar_t ch, size_t count );
```
 |  (2)  | (since C23) |

 
1) 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`. 
2) Type-generic function equivalent to (1). Let `T` be an unqualified wide character object type. * If `ptr` is of type `const T*`, the return type is `const wchar_t*`.
* Otherwise, if `ptr` is of type `T*`, the return type is `wchar_t*`.
* Otherwise, the behavior is undefined.

 If a macro definition of each of these generic functions is suppressed to access an actual function (e.g. if `(wmemchr)` or a function pointer is used), the actual function declaration (1) becomes visible. 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 <locale.h>
#include <stdio.h>
#include <wchar.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.29.4.5.8 The wmemchr function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.29.4.5.8 The wmemchr function (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wmemchr>

lconv
=====

 

|  Defined in header `<locale.h>` |  |  |
| --- | --- | --- |
| 
```
struct lconv;
```
 |  |  |

 The struct `lconv` contains numeric and monetary formatting rules as defined by a C locale. Objects of this struct may be obtained with `[localeconv](localeconv "c/locale/localeconv")`. The members of `lconv` are values of type `char` and of type `char*`. Each `char*` member except `decimal_point` may be pointing at a null character (that is, at an empty C-string). The members of type `char` are all non-negative numbers, any of which may be `[CHAR\_MAX](../types/limits "c/types/limits")` if the corresponding value is not available in the current C locale.


###  Member objects

 ####  Non-monetary numeric formatting parameters

 

|  |  |
| --- | --- |
| char\* decimal\_point |  the character used as the decimal point  (public member object) |
| char\* thousands\_sep |  the character used to separate groups of digits before the decimal point  (public member object) |
| char\* grouping |  a string whose elements indicate the sizes of digit groups  (public member object) |

 ####  Monetary numeric formatting parameters

 

|  |  |
| --- | --- |
| char\* mon\_decimal\_point |  the character used as the decimal point  (public member object) |
| char\* mon\_thousands\_sep |  the character used to separate groups of digits before the decimal point  (public member object) |
| char\* mon\_grouping |  a string whose elements indicate the sizes of digit groups  (public member object) |
| char\* positive\_sign |  a string used to indicate non-negative monetary quantity  (public member object) |
| char\* negative\_sign |  a string used to indicate negative monetary quantity  (public member object) |

 ####  Local monetary numeric formatting parameters

 

|  |  |
| --- | --- |
| char\* currency\_symbol |  the symbol used for currency in the current C locale  (public member object) |
| char frac\_digits |  the number of digits after the decimal point to display in a monetary quantity  (public member object) |
| char p\_cs\_precedes | `1` if currency\_symbol is placed before non-negative value, `​0​` if after  (public member object) |
| char n\_cs\_precedes | `1` if currency\_symbol is placed before negative value, `​0​` if after  (public member object) |
| char p\_sep\_by\_space |  indicates the separation of `currency_symbol`, `positive_sign`, and the non-negative monetary value  (public member object) |
| char n\_sep\_by\_space |  indicates the separation of `currency_symbol`, `negative_sign`, and the negative monetary value  (public member object) |
| char p\_sign\_posn |  indicates the position of `positive_sign` in a non-negative monetary value  (public member object) |
| char n\_sign\_posn |  indicates the position of `negative_sign` in a negative monetary value  (public member object) |

 ####  International monetary numeric formatting parameters

 

|  |  |
| --- | --- |
| char\* int\_curr\_symbol |  the string used as international currency name in the current C locale  (public member object) |
| char int\_frac\_digits |  the number of digits after the decimal point to display in an international monetary quantity  (public member object) |
| char int\_p\_cs\_precedes
(C99) | `1` if int\_curr\_symbol is placed before non-negative international monetary value, `​0​` if after  (public member object) |
| char int\_n\_cs\_precedes
(C99) | `1` if int\_curr\_symbol is placed before negative international monetary value, `​0​` if after  (public member object) |
| char int\_p\_sep\_by\_space
(C99) |  indicates the separation of `int_curr_symbol`, `positive_sign`, and the non-negative international monetary value  (public member object) |
| char int\_n\_sep\_by\_space
(C99) |  indicates the separation of `int_curr_symbol`, `negative_sign`, and the negative international monetary value  (public member object) |
| char int\_p\_sign\_posn
(C99) |  indicates the position of `positive_sign` in a non-negative international monetary value  (public member object) |
| char int\_n\_sign\_posn
(C99) |  indicates the position of `negative_sign` in a negative international monetary value  (public member object) |

   
 The characters of the C-strings pointed to by `grouping` and `mon_grouping` are interpreted according to their numeric values. When the terminating `'\0'` is encountered, the last value seen is assumed to repeat for the remainder of digits. If `[CHAR\_MAX](../types/limits "c/types/limits")` is encountered, no further digits are grouped. The typical grouping of three digits at a time is `"\003"`.


The values of `p_sep_by_space`, `n_sep_by_space`, `int_p_sep_by_space`, `int_n_sep_by_space` are interpreted as follows:




|  |  |
| --- | --- |
|  0  |  no space separates the currency symbol and the value  |
|  1  |  sign sticks to the currency symbol, value is separated by a space  |
|  2  |  sign sticks to the value. Currency symbol is separated by a space  |

 The values of `p_sign_posn`, `n_sign_posn`, `int_p_sign_posn`, `int_n_sign_posn` are interpreted as follows:




|  |  |
| --- | --- |
|  0  |  parentheses around the value and the currency symbol are used to represent the sign  |
|  1  |  sign before the value and the currency symbol  |
|  2  |  sign after the value and the currency symbol  |
|  3  |  sign before the currency symbol  |
|  4  |  sign after the currency symbol  |

 ###  Example

  
```
#include <locale.h>
#include <stdio.h>
 
int main(void)
{
    setlocale(LC_ALL, "ja_JP.UTF-8");
    struct lconv *lc = localeconv();
    printf("Japanese currency symbol: %s(%s)\n", lc->currency_symbol, lc->int_curr_symbol);
}
```
 Possible output:



```
Japanese currency symbol: ￥(JPY )
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.11/2 Localization <locale.h> (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.11/2 Localization <locale.h> (p: TBD)

* C11 standard (ISO/IEC 9899:2011):
+ 7.11/2 Localization <locale.h> (p: 223)

* C99 standard (ISO/IEC 9899:1999):
+ 7.11/2 Localization <locale.h> (p: 204)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.4 LOCALIZATION <locale.h>

 ###  See also

 

|  |  |
| --- | --- |
|  [localeconv](localeconv "c/locale/localeconv") |  queries numeric and monetary formatting details of the current locale  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/locale/lconv "cpp/locale/lconv") for `lconv` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/locale/lconv>

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](../../locale/lc_categories "c/locale/LC categories")` 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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.30.3.2.2 The wctrans function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.30.3.2.2 The wctrans function (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wctrans>

LC\_ALL, LC\_COLLATE, LC\_CTYPE, LC\_MONETARY, LC\_NUMERIC, LC\_TIME
====================================================================

 

|  Defined in header `<locale.h>` |  |  |
| --- | --- | --- |
| 
```
#define LC_ALL      /*implementation defined*/
```
 |  |  |
| 
```
#define LC_COLLATE  /*implementation defined*/
```
 |  |  |
| 
```
#define LC_CTYPE    /*implementation defined*/
```
 |  |  |
| 
```
#define LC_MONETARY /*implementation defined*/
```
 |  |  |
| 
```
#define LC_NUMERIC  /*implementation defined*/
```
 |  |  |
| 
```
#define LC_TIME     /*implementation defined*/
```
 |  |  |

 Each of the above macro constants expand to integer constant expressions with distinct values that are suitable for use as the first argument of `[setlocale](setlocale "c/locale/setlocale")`.




|  Constant  |  Explanation  |
| --- | --- |
| `LC_ALL` |  selects the entire C locale  |
| `LC_COLLATE` |  selects the collation category of the C locale  |
| `LC_CTYPE` |  selects the character classification category of the C locale  |
| `LC_MONETARY` |  selects the monetary formatting category of the C locale  |
| `LC_NUMERIC` |  selects the numeric formatting category of the C locale  |
| `LC_TIME` |  selects the time formatting category of the C locale  |

 Additional macro constants, with names that begin with `LC_` followed by at least one uppercase letter, may be defined in `locale.h`. For example, the POSIX specification requires LC\_MESSAGES (which controls, among other things, `[perror](../io/perror "c/io/perror")` and `[strerror](../string/byte/strerror "c/string/byte/strerror")`), ISO/IEC 30112:2014 ([2014 draft](http://www.open-std.org/JTC1/SC35/WG5/docs/30112d10.pdf)) additionally defines LC\_IDENTIFICATION, LC\_XLITERATE, LC\_NAME, LC\_ADDRESS, LC\_TELEPHONE, LC\_PAPER, LC\_MEASUREMENT, and LC\_KEYBOARD, which are supported by the GNU C library (except for LC\_XLITERATE).


###  Example

  
```
#include <stdio.h>
#include <locale.h>
#include <time.h>
#include <wchar.h>
 
int main(void)
{
    setlocale(LC_ALL, "en_US.UTF-8"); // the C locale will be the UTF-8 enabled English
    setlocale(LC_NUMERIC, "de_DE.utf8");   // decimal dot will be German
    setlocale(LC_TIME, "ja_JP.utf8");      // date/time formatting will be Japanese
    wchar_t str[100];
    time_t t = time(NULL);
    wcsftime(str, 100, L"%A %c", localtime(&t));
    wprintf(L"Number: %.2f\nDate: %Ls\n", 3.14, str);
}
```
 Possible output:



```
Number: 3,14
Date: 月曜日 2017年09月25日 13時00分15秒
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.11/3 Localization <locale.h> (p: 224)

* C99 standard (ISO/IEC 9899:1999):
+ 7.11/3 Localization <locale.h> (p: 205)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.4 LOCALIZATION <locale.h>

 ###  See also

 

|  |  |
| --- | --- |
|  [setlocale](setlocale "c/locale/setlocale") |  gets and sets the current C locale  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/locale/LC_categories "cpp/locale/LC categories") for locale categories |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/locale/LC_categories>

C17
===

 **ISO/IEC 9899:2018**, a.k.a. **C17**/**C18** (denote the year of completion and publication respectively), is the current revision of the C standard.


C17 is same as C11, except that it bumps the [`__STDC_VERSION__`](preprocessor/replace "c/preprocessor/replace") predefined macro to `201710L`, contains several defect reports, and deprecates some features.


 Obsolete
---------

 ###  Deprecated

 * `[ATOMIC\_VAR\_INIT](atomic/atomic_var_init "c/atomic/ATOMIC VAR INIT")`
* Support for calling [`realloc()`](memory/realloc "c/memory/realloc") with zero size

  Defect reports
---------------

  

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


 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/17>

va\_start
=========

 

|  Defined in header `<stdarg.h>` |  |  |
| --- | --- | --- |
| 
```
void va_start( va_list ap, parmN );
```
 |  | (until C23) |
| 
```
void va_start( va_list ap, ... );
```
 |  | (since C23) |

 The `va_start` macro enables access to the variable arguments following the named argument `parmN` (until C23).


`va_start` shall be invoked with an instance to a valid `va_list` object `ap` before any calls to `va_arg`.




|  |  |
| --- | --- |
| If `parmN` is declared with `register` storage class specifier, with an array type, with a function type, or with a type not compatible with the type that results from default argument promotions, the behavior is undefined. | (until C23) |
| Only the first argument passed to `va_start` is evaluated. Any additional arguments are neither expanded nor used in any way. | (since C23) |

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ap  |  -  |  an instance of the `va_list` type  |
|  parmN  |  -  |  the named parameter preceding the first variable parameter  |

 ###  Expanded value

 (none).


###  Example

  
```
#include <stdio.h>
#include <stdarg.h>
 
int add_nums_C99(int count, ...)
{
    int result = 0;
    va_list args;
    va_start(args, count); // count can be omitted since C23
 
    for (int i = 0; i < count; ++i) {
        result += va_arg(args, int);
    }
 
    va_end(args);
    return result;
}
 
#if __STDC_VERSION__ > 201710L
// Same as above, valid since C23
int add_nums_C23(...)
{
    int result = 0;
    va_list args;
    va_start(args);
 
    int count = va_arg(args, int);
    for (int i = 0; i < count; ++i) {
        result += va_arg(args, int);
    }
 
    va_end(args);
    return result;
}
#endif
 
int main(void)
{
    printf("%d\n", add_nums_C99(4, 25, 25, 50, 50));
#if __STDC_VERSION__ > 201710L
    printf("%d\n", add_nums_C23(4, 25, 25, 50, 50));
#endif
}
```
 Possible output:



```
150
150
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.16.1.4 The va\_start macro (p: 198-199)

* C11 standard (ISO/IEC 9899:2011):
+ 7.16.1.4 The va\_start macro (p: 271-272)

* C99 standard (ISO/IEC 9899:1999):
+ 7.15.1.4 The va\_start macro (p: 251-252)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.8.1.1 The va\_start macro

 ###  See also

 

|  |  |
| --- | --- |
|  [va\_arg](va_arg "c/variadic/va arg") |  accesses the next variadic function argument  (function macro) |
|  [va\_copy](va_copy "c/variadic/va copy")
(C99) |  makes a copy of the variadic function arguments  (function macro) |
|  [va\_end](va_end "c/variadic/va end") |  ends traversal of the variadic function arguments  (function macro) |
|  [va\_list](va_list "c/variadic/va list") |  holds the information needed by va\_start, va\_arg, va\_end, and va\_copy  (typedef) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/variadic/va_start "cpp/utility/variadic/va start") for `va_start` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/variadic/va_start>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/fenv/FE_round>

va\_arg
=======

 

|  Defined in header `<stdarg.h>` |  |  |
| --- | --- | --- |
| 
```
T va_arg( va_list ap, T );
```
 |  |  |

 The `va_arg` macro expands to an expression of type `T` that corresponds to the next parameter from the `va_list` `ap`.


Prior to calling `va_arg`, `ap` must be initialized by a call to either `va_start` or `va_copy`, with no intervening call to `va_end`. Each invocation of the `va_arg` macro modifies `ap` to point to the next variable argument.


If the type of the next argument in `ap` (after promotions) is not compatible with `T`, the behavior is undefined, unless:


* one type is a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types; or
* one type is pointer to `void` and the other is a pointer to a character type.

 If `va_arg` is called when there are no more arguments in `ap`, the behavior is undefined.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ap  |  -  |  an instance of the `va_list` type  |
|  T  |  -  |  the type of the next parameter in `ap` |

 ###  Expanded value

 the next variable parameter in `ap`.


###  Example

  
```
#include <stdio.h>
#include <stdarg.h>
#include <math.h>
 
double stddev(int count, ...) 
{
    double sum = 0;
    double sum_sq = 0;
    va_list args;
    va_start(args, count);
    for (int i = 0; i < count; ++i) {
        double num = va_arg(args, double);
        sum += num;
        sum_sq += num*num;
    }
    va_end(args);
    return sqrt(sum_sq/count - (sum/count)*(sum/count));
}
 
int main(void) 
{
    printf("%f\n", stddev(4, 25.0, 27.3, 26.9, 25.7));
}
```
 Output:



```
0.920258
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.16.1.1 The va\_arg macro (p: 269-270)

* C99 standard (ISO/IEC 9899:1999):
+ 7.15.1.1 The va\_arg macro (p: 249-250)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.8.1.2 The va\_arg macro

 ###  See also

 

|  |  |
| --- | --- |
|  [va\_copy](va_copy "c/variadic/va copy")
(C99) |  makes a copy of the variadic function arguments  (function macro) |
|  [va\_end](va_end "c/variadic/va end") |  ends traversal of the variadic function arguments  (function macro) |
|  [va\_list](va_list "c/variadic/va list") |  holds the information needed by va\_start, va\_arg, va\_end, and va\_copy  (typedef) |
|  [va\_start](va_start "c/variadic/va start") |  enables access to variadic function arguments  (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/variadic/va_arg "cpp/utility/variadic/va arg") for `va_arg` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/variadic/va_arg>

va\_copy
========

 

|  Defined in header `<stdarg.h>` |  |  |
| --- | --- | --- |
| 
```
void va_copy( va_list dest, va_list src );
```
 |  | (since C99) |

 The `va_copy` macro copies `src` to `dest`.


`va_end` should be called on `dest` before the function returns or any subsequent re-initialization of `dest` (via calls to `va_start` or `va_copy`).


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  dest  |  -  |  an instance of the `va_list` type to initialize  |
|  src  |  -  |  the source `va_list` that will be used to initialize `dest` |

 ###  Expanded value

 (none).


###  Example

  
```
#include <stdio.h>
#include <stdarg.h>
#include <math.h>
 
double sample_stddev(int count, ...) 
{
    /* Compute the mean with args1. */
    double sum = 0;
    va_list args1;
    va_start(args1, count);
    va_list args2;
    va_copy(args2, args1);   /* copy va_list object */
    for (int i = 0; i < count; ++i) {
        double num = va_arg(args1, double);
        sum += num;
    }
    va_end(args1);
    double mean = sum / count;
 
    /* Compute standard deviation with args2 and mean. */
    double sum_sq_diff = 0;
    for (int i = 0; i < count; ++i) {
        double num = va_arg(args2, double);
        sum_sq_diff += (num-mean) * (num-mean);
    }
    va_end(args2);
    return sqrt(sum_sq_diff / count);
}
 
int main(void) 
{
    printf("%f\n", sample_stddev(4, 25.0, 27.3, 26.9, 25.7));
}
```
 Possible output:



```
0.920258
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.16.1.2 The va\_copy macro (p: 270)

* C99 standard (ISO/IEC 9899:1999):
+ 7.15.1.2 The va\_copy macro (p: 250)

 ###  See also

 

|  |  |
| --- | --- |
|  [va\_arg](va_arg "c/variadic/va arg") |  accesses the next variadic function argument  (function macro) |
|  [va\_end](va_end "c/variadic/va end") |  ends traversal of the variadic function arguments  (function macro) |
|  [va\_list](va_list "c/variadic/va list") |  holds the information needed by va\_start, va\_arg, va\_end, and va\_copy  (typedef) |
|  [va\_start](va_start "c/variadic/va start") |  enables access to variadic function arguments  (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/variadic/va_copy "cpp/utility/variadic/va copy") for `va_copy` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/variadic/va_copy>

va\_end
=======

 

|  Defined in header `<stdarg.h>` |  |  |
| --- | --- | --- |
| 
```
void va_end( va_list ap );
```
 |  |  |

 The `va_end` macro performs cleanup for an `ap` object initialized by a call to `va_start` or `va_copy`. `va_end` may modify `ap` so that it is no longer usable.


If there is no corresponding call to `va_start` or `va_copy`, or if `va_end` is not called before a function that calls `va_start` or `va_copy` returns, the behavior is undefined.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ap  |  -  |  an instance of the `va_list` type to clean up  |

 ###  Expanded value

 (none).


###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.16.1.3 The va\_end macro (p: 270-271)

* C99 standard (ISO/IEC 9899:1999):
+ 7.15.1.3 The va\_end macro (p: 250-251)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.8.1.3 The va\_end macro

 ###  See also

 

|  |  |
| --- | --- |
|  [va\_arg](va_arg "c/variadic/va arg") |  accesses the next variadic function argument  (function macro) |
|  [va\_copy](va_copy "c/variadic/va copy")
(C99) |  makes a copy of the variadic function arguments  (function macro) |
|  [va\_list](va_list "c/variadic/va list") |  holds the information needed by va\_start, va\_arg, va\_end, and va\_copy  (typedef) |
|  [va\_start](va_start "c/variadic/va start") |  enables access to variadic function arguments  (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/variadic/va_end "cpp/utility/variadic/va end") for `va_end` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/variadic/va_end>

va\_list
========

 

|  Defined in header `<stdarg.h>` |  |  |
| --- | --- | --- |
| 
```
/* unspecified */ va_list;
```
 |  |  |

 `va_list` is a complete object type suitable for holding the information needed by the macros `va_start`, `va_copy`, `va_arg`, and `va_end`.


If a `va_list` instance is created, passed to another function, and used via `va_arg` in that function, then any subsequent use in the calling function should be preceded by a call to `va_end`.


It is legal to pass a pointer to a `va_list` object to another function and then use that object after the function returns.


###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.16/3 Variable arguments <stdarg.h> (p: 269)

* C99 standard (ISO/IEC 9899:1999):
+ 7.15/3 Variable arguments <stdarg.h> (p: 249)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.8 VARIABLE ARGUMENTS <stdarg.h>

 ###  See also

 

|  |  |
| --- | --- |
|  [va\_arg](va_arg "c/variadic/va arg") |  accesses the next variadic function argument  (function macro) |
|  [va\_copy](va_copy "c/variadic/va copy")
(C99) |  makes a copy of the variadic function arguments  (function macro) |
|  [va\_end](va_end "c/variadic/va end") |  ends traversal of the variadic function arguments  (function macro) |
|  [va\_start](va_start "c/variadic/va start") |  enables access to variadic function arguments  (function macro) |
| [C++ documentation](https://en.cppreference.com/w/cpp/utility/variadic/va_list "cpp/utility/variadic/va list") for `va_list` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/variadic/va_list>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcstol>

setlocale
=========

 

|  Defined in header `<locale.h>` |  |  |
| --- | --- | --- |
| 
```
char* setlocale( int category, const char* locale );
```
 |  |  |

 The `setlocale` function installs the specified system locale or its portion as the new C locale. The modifications remain in effect and influences the execution of all locale-sensitive C library functions until the next call to `setlocale`. If `locale` is a null pointer, `setlocale` queries the current C locale without modifying it.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  category  |  -  |  locale category identifier, one of the [LC\_xxx](lc_categories "c/locale/LC categories") macros. May be null.  |
|  locale  |  -  |  system-specific locale identifier. Can be `""` for the user-preferred locale or `"C"` for the minimal locale  |

 ###  Return value

 pointer to a narrow null-terminated string identifying the C locale after applying the changes, if any, or null pointer on failure.


A copy of the returned string along with the category used in this call to `setlocale` may be used later in the program to restore the locale back to the state at the end of this call.


###  Notes

 During program startup, the equivalent of `setlocale([LC\_ALL](http://en.cppreference.com/w/c/locale/LC_categories), "C");` is executed before any user code is run.


Although the return type is `char*`, modifying the pointed-to characters is undefined behavior.


Because `setlocale` modifies global state which affects execution of locale-dependent functions, it is undefined behavior to call it from one thread, while another thread is executing any of the following functions: `[fprintf](../io/fprintf "c/io/fprintf")`, `[isprint](../string/byte/isprint "c/string/byte/isprint")`, `[iswdigit](../string/wide/iswdigit "c/string/wide/iswdigit")`, `[localeconv](localeconv "c/locale/localeconv")`, `[tolower](../string/byte/tolower "c/string/byte/tolower")`, `[fscanf](../io/fscanf "c/io/fscanf")`, `[ispunct](../string/byte/ispunct "c/string/byte/ispunct")`, `[iswgraph](../string/wide/iswgraph "c/string/wide/iswgraph")`, `[mblen](../string/multibyte/mblen "c/string/multibyte/mblen")`, `[toupper](../string/byte/toupper "c/string/byte/toupper")`, `[isalnum](../string/byte/isalnum "c/string/byte/isalnum")`, `[isspace](../string/byte/isspace "c/string/byte/isspace")`, `[iswlower](../string/wide/iswlower "c/string/wide/iswlower")`, `[mbstowcs](../string/multibyte/mbstowcs "c/string/multibyte/mbstowcs")`, `[towlower](../string/wide/towlower "c/string/wide/towlower")`, `[isalpha](../string/byte/isalpha "c/string/byte/isalpha")`, `[isupper](../string/byte/isupper "c/string/byte/isupper")`, `[iswprint](../string/wide/iswprint "c/string/wide/iswprint")`, `[mbtowc](../string/multibyte/mbtowc "c/string/multibyte/mbtowc")`, `[towupper](../string/wide/towupper "c/string/wide/towupper")`, `[isblank](../string/byte/isblank "c/string/byte/isblank")`, `[iswalnum](../string/wide/iswalnum "c/string/wide/iswalnum")`, `[iswpunct](../string/wide/iswpunct "c/string/wide/iswpunct")`, `setlocale`, `[wcscoll](../string/wide/wcscoll "c/string/wide/wcscoll")`, `[iscntrl](../string/byte/iscntrl "c/string/byte/iscntrl")`, `[iswalpha](../string/wide/iswalpha "c/string/wide/iswalpha")`, `[iswspace](../string/wide/iswspace "c/string/wide/iswspace")`, `[strcoll](../string/byte/strcoll "c/string/byte/strcoll")`, `[wcstod](../string/wide/wcstof "c/string/wide/wcstof")`, `[isdigit](../string/byte/isdigit "c/string/byte/isdigit")`, `[iswblank](../string/wide/iswblank "c/string/wide/iswblank")`, `[iswupper](../string/wide/iswupper "c/string/wide/iswupper")`, `[strerror](../string/byte/strerror "c/string/byte/strerror")`, `[wcstombs](../string/multibyte/wcstombs "c/string/multibyte/wcstombs")`, `[isgraph](../string/byte/isgraph "c/string/byte/isgraph")`, `[iswcntrl](../string/wide/iswcntrl "c/string/wide/iswcntrl")`, `[iswxdigit](../string/wide/iswxdigit "c/string/wide/iswxdigit")`, `[strtod](../string/byte/strtof "c/string/byte/strtof")`, `[wcsxfrm](../string/wide/wcsxfrm "c/string/wide/wcsxfrm")`, `[islower](../string/byte/islower "c/string/byte/islower")`, `[iswctype](../string/wide/iswctype "c/string/wide/iswctype")`, `[isxdigit](../string/byte/isxdigit "c/string/byte/isxdigit")`.


POSIX also defines a locale named "POSIX", which is always accessible and is exactly equivalent to the default minimal "C" locale.


POSIX also specifies that the returned pointer, not just the contents of the pointed-to string, may be invalidated by subsequent calls to `setlocale`.


###  Example

  
```
#include <stdio.h>
#include <locale.h>
#include <time.h>
#include <wchar.h>
 
int main(void)
{
    // the C locale will be UTF-8 enabled English;
    // decimal dot will be German
    // date and time formatting will be Japanese
    setlocale(LC_ALL, "en_US.UTF-8");
    setlocale(LC_NUMERIC, "de_DE.utf8");
    setlocale(LC_TIME, "ja_JP.utf8");
 
    wchar_t str[100];
    time_t t = time(NULL);
    wcsftime(str, 100, L"%A %c", localtime(&t));
    wprintf(L"Number: %.2f\nDate: %ls\n", 3.14, str);
}
```
 Possible output:



```
Number: 3,14
Date: 月曜日 2017年09月25日 13時00分15秒
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.11.1.1 The setlocale function (p: 163-164)

* C11 standard (ISO/IEC 9899:2011):
+ 7.11.1.1 The setlocale function (p: 224-225)

* C99 standard (ISO/IEC 9899:1999):
+ 7.11.1.1 The setlocale function (p: 205-206)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.4.1.1 The setlocale function

 ###  See also

 

|  |  |
| --- | --- |
|  [LC\_ALLLC\_COLLATELC\_CTYPELC\_MONETARYLC\_NUMERICLC\_TIME](lc_categories "c/locale/LC categories") |  locale categories for `setlocale`  (macro constant) |
| [C++ documentation](https://en.cppreference.com/w/cpp/locale/setlocale "cpp/locale/setlocale") for `setlocale` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/locale/setlocale>

C23
===

 The next generation of the C standard.


See: [The current WD of C23](https://open-std.org/JTC1/SC22/WG14/www/docs/n3096.pdf).


 Obsolete
---------

 ###  Removed

 * Old-style function [declarations](language/function_declaration "c/language/function declaration") and [definitions](language/function_definition "c/language/function definition")
* Representations for [signed integers](language/arithmetic_types "c/language/arithmetic types") other than two's complement
* Permission that `u`/`U`-prefixed [character constants](language/character_constant "c/language/character constant") and [string literals](language/string_literal "c/language/string literal") may be not UTF-16/32
* Mixed wide [string literal](language/string_literal "c/language/string literal") concatenation
* Support for calling [`realloc()`](memory/realloc "c/memory/realloc") with zero size (the behavior becomes undefined)
* [`__alignof_is_defined`](types "c/types") and [`__alignas_is_defined`](types "c/types")
* [`static_assert`](error/static_assert "c/error/static assert") is not provided as a macro defined in [`<assert.h>`](error "c/error") (becomes a keyword)
* [`thread_local`](thread/thread_local "c/thread/thread local") is not provided as a macro defined in [`<threads.h>`](thread "c/thread") (becomes a keyword)

 ###  Deprecated

 * [`<stdnoreturn.h>`](language/_noreturn "c/language/ Noreturn")
* Old feature-test macros
	+ [`__STDC_IEC_559__`](preprocessor/replace "c/preprocessor/replace")
	+ [`__STDC_IEC_559_COMPLEX__`](preprocessor/replace "c/preprocessor/replace")
* [`_Noreturn`](language/_noreturn "c/language/ Noreturn") function specifier
* [`_Noreturn`](language/attributes/noreturn "c/language/attributes/noreturn") attribute token
* `[asctime()](chrono/asctime "c/chrono/asctime")`
* `[ctime()](chrono/ctime "c/chrono/ctime")`
* [`DECIMAL_DIG`](types/limits "c/types/limits") (use the appropriate type-specific macro ([`FLT_DECIMAL_DIG`](types/limits#Limits_of_floating-point_types "c/types/limits"), etc) instead)
* Definition of following numeric limit macros in [`<math.h>`](numeric/math "c/numeric/math") (they should be used via [`<float.h>`](types/limits#Limits_of_floating_point_types "c/types/limits"))
	+ [`INFINITY`](numeric/math "c/numeric/math")
	+ [`DEC_INFINITY`](numeric/math "c/numeric/math")
	+ [`NAN`](numeric/math "c/numeric/math")
	+ [`DEC_NAN`](numeric/math "c/numeric/math")
* [`__bool_true_false_are_defined`](types "c/types")

  New language features
----------------------

 * [Decimal floating-point types](language/arithmetic_types "c/language/arithmetic types") ([`_Decimal32`](keyword/_decimal32 "c/keyword/ Decimal32"), [`_Decimal64`](keyword/_decimal64 "c/keyword/ Decimal64"), and [`_Decimal128`](keyword/_decimal128 "c/keyword/ Decimal128"))
* [Bit-precise integers](language/arithmetic_types "c/language/arithmetic types") ([`_BitInt(N)`](https://en.cppreference.com/mwiki/index.php?title=c/keyword/_BitInt(N)&action=edit&redlink=1 "c/keyword/ BitInt(N) (page does not exist)"))
* [Binary integer constants](language/integer_constant "c/language/integer constant")
* [`u8` character constants](language/character_constant "c/language/character constant")
* Type change of [`u8` string literals](language/string_literal "c/language/string literal")
* Digit separator `'`
* Empty [initializer](language/initialization "c/language/initialization") `={}`
* [Attributes](language/attributes "c/language/attributes")
	+ `[[[deprecated](language/attributes/deprecated "c/language/attributes/deprecated")]]`
	+ `[[[fallthrough](language/attributes/fallthrough "c/language/attributes/fallthrough")]]`
	+ `[[[maybe\_unused](language/attributes/maybe_unused "c/language/attributes/maybe unused")]]`
	+ `[[[nodiscard](language/attributes/nodiscard "c/language/attributes/nodiscard")]]`
	+ `[[[noreturn](language/attributes/noreturn "c/language/attributes/noreturn")]]`
	+ `[[[reproducible](https://en.cppreference.com/mwiki/index.php?title=c/language/attributes/reproducible&action=edit&redlink=1 "c/language/attributes/reproducible (page does not exist)")]]`
	+ `[[[unsequenced](https://en.cppreference.com/mwiki/index.php?title=c/language/attributes/unsequenced&action=edit&redlink=1 "c/language/attributes/unsequenced (page does not exist)")]]`
* Unnamed parameters in [function definitions](language/function_definition "c/language/function definition")
* Identical cvr-qualifications for [array types](language/array "c/language/array") and their element types
* Single-argument [`_Static_assert`](language/_static_assert "c/language/ Static assert")
* [`static_assert`](keyword/static_assert "c/keyword/static assert") becomes a keyword (may be a predefined macro for compatibility reasons)
* [`thread_local`](keyword/thread_local "c/keyword/thread local") becomes a keyword (may be a predefined macro for compatibility reasons)
* [Labels](language/goto "c/language/goto") followed by declarations and `}`
* [`nullptr`](keyword/nullptr "c/keyword/nullptr") constant and the associated [`nullptr_t`](types/nullptr_t "c/types/nullptr t") type
* [`true`](keyword/true "c/keyword/true") and [`false`](keyword/false "c/keyword/false") become keywords (may be predefined macros for compatibility reasons)
* New preprocessor directives
	+ [`#elifdef`](preprocessor/conditional "c/preprocessor/conditional")
	+ [`#elifndef`](preprocessor/conditional "c/preprocessor/conditional")
	+ [`#warning`](preprocessor/error "c/preprocessor/error")
	+ [`#embed`](preprocessor/embed "c/preprocessor/embed")
* Pragmas for rounding direction
	+ `STDC` [`FENV_ROUND`](preprocessor/impl "c/preprocessor/impl")
	+ `STDC` [`FENV_DEC_ROUND`](preprocessor/impl "c/preprocessor/impl")

 ###  Feature test macros for optional features

 * [`__STDC_IEC_60559_BFP__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates IEEE-754 binary floating-point arithmetic and required math functions are supported. This macro supersedes [`__STDC_IEC_559__`](preprocessor/replace "c/preprocessor/replace").
* [`__STDC_IEC_60559_DFP__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates IEEE-754 decimal floating-point arithmetic and required math functions are supported.
* [`__STDC_IEC_60559_COMPLEX__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates IEEE-754 complex arithmetic and required math functions are supported. This macro supersedes [`__STDC_IEC_559_COMPLEX__`](preprocessor/replace "c/preprocessor/replace").

  New library features
---------------------

 ###  New headers

 * `<stdbit.h>`
* `<stdckdint.h>`

 ###  Library features

 * Extended binary floating-point math functions
* Decimal floating-point math functions
	+ -`d*N*` variants for existing and new floating-point math functions
	+ [`quantizedN()`](https://en.cppreference.com/mwiki/index.php?title=c/numeric/math/quantize&action=edit&redlink=1 "c/numeric/math/quantize (page does not exist)")
	+ [`samequantumdN()`](https://en.cppreference.com/mwiki/index.php?title=c/numeric/math/samequantum&action=edit&redlink=1 "c/numeric/math/samequantum (page does not exist)")
	+ [`quantumdN()`](https://en.cppreference.com/mwiki/index.php?title=c/numeric/math/quantum&action=edit&redlink=1 "c/numeric/math/quantum (page does not exist)")
	+ [`llquantexpdN()`](https://en.cppreference.com/mwiki/index.php?title=c/numeric/math/llquantexp&action=edit&redlink=1 "c/numeric/math/llquantexp (page does not exist)")
	+ [`encodedecdN()`](https://en.cppreference.com/mwiki/index.php?title=c/numeric/math/encodedec&action=edit&redlink=1 "c/numeric/math/encodedec (page does not exist)")
	+ [`decodedecdN()`](https://en.cppreference.com/mwiki/index.php?title=c/numeric/math/decodedec&action=edit&redlink=1 "c/numeric/math/decodedec (page does not exist)")
	+ [`encodebindN()`](https://en.cppreference.com/mwiki/index.php?title=c/numeric/math/encodebin&action=edit&redlink=1 "c/numeric/math/encodebin (page does not exist)")
	+ [`decodebindN()`](https://en.cppreference.com/mwiki/index.php?title=c/numeric/math/decodebin&action=edit&redlink=1 "c/numeric/math/decodebin (page does not exist)")
* [Floating-point formatting functions](string/byte/strfromf "c/string/byte/strfromf")
* Library support for UTF-8
	+ `char8_t` type alias
	+ [`mbrtoc8()`](string/multibyte/mbrtoc8 "c/string/multibyte/mbrtoc8")
	+ [`c8rtomb()`](string/multibyte/c8rtomb "c/string/multibyte/c8rtomb")
	+ [`atomic_char8_t`](thread "c/thread") type alias
	+ [`ATOMIC_CHAR8_T_LOCK_FREE`](atomic/atomic_lock_free_consts "c/atomic/ATOMIC LOCK FREE consts") test macro
* [`memset_explicit()`](string/byte/memset "c/string/byte/memset")
* POSIX functions
	+ [`memccpy()`](string/byte/memccpy "c/string/byte/memccpy")
	+ [`strdup()`](string/byte/strdup "c/string/byte/strdup")
	+ [`strndup()`](string/byte/strndup "c/string/byte/strndup")
	+ [`gmtime_r()`](chrono/gmtime "c/chrono/gmtime")
	+ [`localtime_r()`](chrono/localtime "c/chrono/localtime")
	+ Extensions for [`strftime()`](chrono/strftime "c/chrono/strftime") and [`wcsftime()`](chrono/wcsftime "c/chrono/wcsftime")
* Extensions for [`fscanf()`](io/fscanf "c/io/fscanf") and [`fprintf()`](io/fprintf "c/io/fprintf") function families
	+ `w*N*` and `wf*N*` length modifiers for [`[u]intN_t`](types/integer "c/types/integer") and [`[u]int_fastN_t`](types/integer "c/types/integer") respectively
	+ `H`, `D`, and `DD` length modifiers for `_Decimal32`, `_Decimal64`, and `_Decimal128` respectively
	+ `b` conversion specifier for unsigned integer types
* [`timespec_getres()`](chrono/timespec_getres "c/chrono/timespec getres")
* Macro constants for width of integer types
* Additional numeric limit macros for floating-point types
* Library version-test macros
	+ [`__STDC_VERSION_FENV_H__`](numeric/fenv "c/numeric/fenv")
	+ [`__STDC_VERSION_MATH_H__`](numeric/math "c/numeric/math")
	+ [`__STDC_VERSION_STDINT_H__`](types/integer "c/types/integer")
	+ [`__STDC_VERSION_STDLIB_H__`](string/byte "c/string/byte")
	+ [`__STDC_VERSION_TGMATH_H__`](numeric/tgmath "c/numeric/tgmath")
	+ [`__STDC_VERSION_TIME_H__`](chrono "c/chrono")
	+ [`__STDC_VERSION_STDCKDINT_H__`](https://en.cppreference.com/mwiki/index.php?title=STDC_VERSION_STDCKDINT_H&action=edit&redlink=1 "STDC VERSION STDCKDINT H (page does not exist)")
	+ [`__STDC_VERSION_STDBIT_H__`](https://en.cppreference.com/mwiki/index.php?title=STDC_VERSION_STDBIT_H&action=edit&redlink=1 "STDC VERSION STDBIT H (page does not exist)")

  Defect reports
---------------

  

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


  Compiler support
-----------------

 ###  C23 core language features

 

|  C23 feature |  Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++ (ex Portland Group/PGI) | Nvidia nvcc |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| [`_Static_assert`](language/_static_assert "c/language/ Static assert") with no message  | [N2265](https://open-std.org/JTC1/SC22/WG14/www/docs/n2265.pdf) | 9  | 9  | Yes  | Yes  | 6.5  | 2021.1.2 (clang based)  |  |  |  |  |  |  |
| `[[[nodiscard](language/attributes/nodiscard "c/language/attributes/nodiscard")]]` | [N2267](https://open-std.org/JTC1/SC22/WG14/www/docs/n2267.pdf) | 10  | 9  |  | Yes  | 6.4  | 2021.1.2 (clang based)  |  |  |  |  |  |  |
| `[[[maybe\_unused](language/attributes/maybe_unused "c/language/attributes/maybe unused")]]` | [N2270](https://open-std.org/JTC1/SC22/WG14/www/docs/n2270.pdf) | 10  | 9  |  | Yes  | 6.4  | 2021.1.2 (clang based)  |  |  |  |  |  |  |
| `[[[deprecated](language/attributes/deprecated "c/language/attributes/deprecated")]]` | [N2334](https://open-std.org/JTC1/SC22/WG14/www/docs/n2334.pdf) | 10  | 9  |  | Yes  | 6.4  | 2021.1.2 (clang based)  |  |  |  |  |  |  |
| [Attributes](language/attributes "c/language/attributes") | [N2335](https://open-std.org/JTC1/SC22/WG14/www/docs/n2335.pdf)[N2554](https://open-std.org/JTC1/SC22/WG14/www/docs/n2554.pdf) | 10  | 9  |  | Yes  | 6.4  | 2021.1.2 (clang based)  |  |  |  |  |  |  |
|  IEEE 754 decimal floating-point types  | [N2341](https://open-std.org/JTC1/SC22/WG14/www/docs/n2341.pdf) | 4.2 (partial)\* |  |  |  |  | 13.0 (partial)\* |  |  |  |  |  |  |
| `[[[fallthrough](language/attributes/fallthrough "c/language/attributes/fallthrough")]]` | [N2408](https://open-std.org/JTC1/SC22/WG14/www/docs/n2408.pdf) | 10  | 9  |  | Yes  | 6.4  | 2021.1.2 (clang based)  |  |  |  |  |  |  |
| [`u8` character constants](language/character_constant "c/language/character constant") | [N2418](https://open-std.org/JTC1/SC22/WG14/www/docs/n2418.pdf) | 10  | 15  |  |  | 6.5  | 2022.2  |  |  |  |  |  |  |
|  Removal of [function definitions](language/function_definition "c/language/function definition") without prototype  | [N2432](https://open-std.org/JTC1/SC22/WG14/www/docs/n2432.pdf) | 10  | 15  |  |  |  | 2022.2  |  |  |  |  |  |  |
| `[[[nodiscard](language/attributes/nodiscard "c/language/attributes/nodiscard")]]` with message  | [N2448](https://open-std.org/JTC1/SC22/WG14/www/docs/n2448.pdf) | 11  | 10  |  | Yes  | 6.4  | 2021.1.2 (clang based)  |  |  |  |  |  |  |
|  Unnamed parameters in function definitions  | [N2480](https://open-std.org/JTC1/SC22/WG14/www/docs/n2480.pdf) | 11  | 11  |  | Yes  | 6.4  | 2021.1.2 (clang based)  |  |  |  |  |  |  |
| [Labels](language/statements#Labels "c/language/statements") before declarations and end of blocks  | [N2508](https://open-std.org/JTC1/SC22/WG14/www/docs/n2508.pdf) | 11  | 16  | Partial\* |  | 6.5  | 17.0\* |  |  |  |  |  |  |
| [Binary integer constants](language/integer_constant "c/language/integer constant") | [N2549](https://open-std.org/JTC1/SC22/WG14/www/docs/n2549.pdf) | 4.3\*11  | 2.9\*9  | 19.0 (2015)\*\* | Yes  | 6.5  | 11.0\* |  |  |  |  |  |  |
| [`__has_c_attribute`](language/attributes#Attribute_testing "c/language/attributes") in preprocessor conditionals  | [N2553](https://open-std.org/JTC1/SC22/WG14/www/docs/n2553.pdf) | 11  | 9  |  | Yes  | 6.5  | 2021.1.2 (clang based)  |  |  |  |  |  |  |
|  Allow duplicate attributes  | [N2557](https://open-std.org/JTC1/SC22/WG14/www/docs/n2557.pdf) | 11  | 13  |  | Yes  | 6.5  | 2021.4 (clang-based  |  |  |  |  |  |  |
|  IEEE 754 interchange and extended types  | [N2601](https://open-std.org/JTC1/SC22/WG14/www/docs/n2601.pdf) | 7 (partial)\* | 6 (partial)\* |  | Partial\* |  |  |  |  |  |  |  |  |
|  Digit separators  | [N2626](https://open-std.org/JTC1/SC22/WG14/www/docs/n2626.pdf) | 12  | 13  | 19.0 (2015)\*\* | Yes  | 6.5  | 18.0\* |  |  |  |  |  |  |
| [`#elifdef` and `#elifndef`](preprocessor/conditional "c/preprocessor/conditional") | [N2645](https://open-std.org/JTC1/SC22/WG14/www/docs/n2645.pdf) | 12  | 13  |  | 13.1.6\* | 6.5  | 2021.4  |  |  |  |  |  |  |
|  Type change of [`u8` string literals](language/string_literal "c/language/string literal") | [N2653](https://open-std.org/JTC1/SC22/WG14/www/docs/n2653.htm) |  |  |  |  |  |  |  |  |  |  |  |  |
| `[[[maybe\_unused](language/attributes/maybe_unused "c/language/attributes/maybe unused")]]` for labels  | [N2662](https://open-std.org/JTC1/SC22/WG14/www/docs/n2662.pdf) | 11  | 16  |  |  | 6.5  | 2022.2  |  |  |  |  |  |  |
|  [`#warning`](preprocessor/error "c/preprocessor/error") | [N2686](https://open-std.org/JTC1/SC22/WG14/www/docs/n2686.pdf) | Yes  | Yes  |  | Yes  | 6.5  | Yes  |  |  |  |  |  |  |
|  Bit-precise integer types (`_BitInt`)  | [N2763](https://open-std.org/JTC1/SC22/WG14/www/docs/n2763.pdf) |  | 15  |  |  | 6.5  | 2022.2  |  |  |  |  |  |  |
| `[[[noreturn](language/attributes/noreturn "c/language/attributes/noreturn")]]` | [N2764](https://open-std.org/JTC1/SC22/WG14/www/docs/n2764.pdf) | 13  | 15  |  |  | 6.5  | 2022.2  |  |  |  |  |  |  |
|  Suffixes for bit-precise integer constants  | [N2775](https://open-std.org/JTC1/SC22/WG14/www/docs/n2775.pdf) |  | 15  |  |  |  | 2022.2  |  |  |  |  |  |  |
| [`__has_include`](preprocessor/include "c/preprocessor/include") in preprocessor conditionals  | [N2799](https://open-std.org/JTC1/SC22/WG14/www/docs/n2799.pdf) | 5  | Yes  | 19.11\* | Yes  | 6.5  | 18.0  |  |  |  |  |  |  |
|  Identifier Syntax using Unicode Standard Annex 31  | [N2836](https://open-std.org/JTC1/SC22/WG14/www/docs/n2836.pdf) | 13  | 15  |  |  | 6.5  | 2022.2  |  |  |  |  |  |  |
|  Removal of [function declarations](language/function_declaration "c/language/function declaration") without prototype  | [N2841](https://open-std.org/JTC1/SC22/WG14/www/docs/n2841.htm) | 13  | 15  |  |  |  | 2022.2  |  |  |  |  |  |  |
| [Empty initializers](language/initialization#Empty_initialization "c/language/initialization") | [N2900](https://open-std.org/JTC1/SC22/WG14/www/docs/n2900.htm) | Partial\* | Partial\* |  | Partial\* | Partial\* | Partial\* |  |  |  |  |  |  |
| [`typeof`](language/typeof "c/language/typeof") and [`typeof_unqual`](language/typeof "c/language/typeof") | [N2927](https://open-std.org/JTC1/SC22/WG14/www/docs/n2927.htm)[N2930](https://open-std.org/JTC1/SC22/WG14/www/docs/n2930.pdf) | Partial\*13  | Partial\*16  |  | Partial\* | Partial\* | Partial\* |  |  |  | Partial\* |  |  |
|  New spelling of keywords  | [N2934](https://open-std.org/JTC1/SC22/WG14/www/docs/n2934.pdf) | 13  | 16  |  |  | 6.5  |  |  |  |  |  |  |  |
|  Predefined [`true` and `false`](language/bool_constant "c/language/bool constant") | [N2935](https://open-std.org/JTC1/SC22/WG14/www/docs/n2935.pdf) | 13  | 15  |  |  |  | 2022.2  |  |  |  |  |  |  |
| `[[[unsequenced](https://en.cppreference.com/mwiki/index.php?title=c/language/attributes/unsequenced&action=edit&redlink=1 "c/language/attributes/unsequenced (page does not exist)")]]` and `[[[reproducible](https://en.cppreference.com/mwiki/index.php?title=c/language/attributes/reproducible&action=edit&redlink=1 "c/language/attributes/reproducible (page does not exist)")]]` | [N2956](https://open-std.org/JTC1/SC22/WG14/www/docs/n2956.htm) |  |  |  |  |  |  |  |  |  |  |  |  |
|  Relax requirements for [variadic parameter list](language/variadic "c/language/variadic") | [N2975](https://open-std.org/JTC1/SC22/WG14/www/docs/n2975.pdf) | 13  | 16  |  |  | 6.5  | 2023.1  |  |  |  |  |  |  |
|  Type inference in object definitions  | [N3007](https://open-std.org/JTC1/SC22/WG14/www/docs/n3007.htm) | 13  |  |  |  |  |  |  |  |  |  |  |  |
|  [`#embed`](preprocessor/embed "c/preprocessor/embed") | [N3017](https://open-std.org/JTC1/SC22/WG14/www/docs/n3017.htm) |  |  |  |  |  |  |  |  |  |  |  |  |
| [`constexpr`](https://en.cppreference.com/mwiki/index.php?title=c/language/constexpr&action=edit&redlink=1 "c/language/constexpr (page does not exist)") objects  | [N3018](https://open-std.org/JTC1/SC22/WG14/www/docs/n3018.htm) | 13  |  |  |  |  |  |  |  |  |  |  |  |
|  Improved Normal Enumerations  | [N3029](https://open-std.org/JTC1/SC22/WG14/www/docs/n3029.htm) | 13  |  |  |  |  |  |  |  |  |  |  |  |
|  Enhancements to Enumerations  | [N3030](https://open-std.org/JTC1/SC22/WG14/www/docs/n3030.htm) | 13  | Maybe  |  |  |  |  |  |  |  |  |  |  |
| [`__VA_OPT__`](preprocessor/replace#Function-like_macros "c/preprocessor/replace") | [N3033](https://open-std.org/JTC1/SC22/WG14/www/docs/n3033.htm) | 8  | 12  |  |  | 6.5  |  |  |  |  |  |  |  |
|  Storage-class specifiers for compound literals  | [N3038](https://open-std.org/JTC1/SC22/WG14/www/docs/n3038.htm) | 13  |  |  |  |  |  |  |  |  |  |  |  |
| [`nullptr`](language/nullptr "c/language/nullptr") | [N3042](https://open-std.org/JTC1/SC22/WG14/www/docs/n3042.htm) | 13  | 16  |  |  |  |  |  |  |  |  |  |  |
|  C23 feature |  Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++(ex Portland Group/PGI) | Nvidia nvcc |

 ###  C23 library features

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/23>

localeconv
==========

 

|  Defined in header `<locale.h>` |  |  |
| --- | --- | --- |
| 
```
struct lconv *localeconv(void);
```
 |  |  |

 The `localeconv` function obtains a pointer to a static object of type `[lconv](lconv "c/locale/lconv")`, which represents numeric and monetary formatting rules of the current C locale.


###  Parameters

 (none).


###  Return value

 pointer to the current `[lconv](lconv "c/locale/lconv")` object.


###  Notes

 Modifying the object references through the returned pointer is undefined behavior.


`localeconv` modifies a static object, calling it from different threads without synchronization is undefined behavior.


###  Example

  
```
#include <stdio.h>
#include <locale.h>
 
int main(void)
{
  setlocale(LC_MONETARY, "en_IN.utf8");
  struct lconv *lc = localeconv();
  printf("Local Currency Symbol        : %s\n", lc->currency_symbol);
  printf("International Currency Symbol: %s\n", lc->int_curr_symbol);
}
```
 Output:



```
Local Currency Symbol        : ₹
International Currency Symbol: INR
```
  ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.11.2.1 The localeconv function (p: 225-230)

* C99 standard (ISO/IEC 9899:1999):
+ 7.11.2.1 The localeconv function (p: 206-211)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.4.2.1 The localeconv function

 ###  See also

 

|  |  |
| --- | --- |
|  [setlocale](setlocale "c/locale/setlocale") |  gets and sets the current C locale  (function) |
|  [lconv](lconv "c/locale/lconv") |  formatting details, returned by `localeconv`  (struct) |
| [C++ documentation](https://en.cppreference.com/w/cpp/locale/localeconv "cpp/locale/localeconv") for `localeconv` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/locale/localeconv>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/fenv/feclearexcept>

wcsstr
======

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
wchar_t *wcsstr( const wchar_t *dest, const wchar_t *src );
```
 |  (1)  | (since C95) |
| 
```
/*QWchar_t*/ *wcsstr( /*QWchar_t*/ *dest, const wchar_t *src );
```
 |  (2)  | (since C23) |

 
1) Finds the first occurrence of the wide string `src` in the wide string pointed to by `dest`. The terminating null characters are not compared. 
2) Type-generic function equivalent to (1). Let `T` be an unqualified wide character object type. * If `dest` is of type `const T*`, the return type is `const wchar_t*`.
* Otherwise, if `dest` is of type `T*`, the return type is `wchar_t*`.
* Otherwise, the behavior is undefined.

 If a macro definition of each of these generic functions is suppressed to access an actual function (e.g. if `(wcsstr)` or a function pointer is used), the actual function declaration (1) becomes visible. ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcsstr>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/fenv/fetestexcept>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/fenv/feraiseexcept>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/fenv/feexceptflag>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/fenv/feenv>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/fenv/feround>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/fenv/feholdexcept>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/fenv/feupdateenv>

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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/fenv/FE_exceptions>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/numeric/fenv/FE_DFL_ENV>

typeof operators (since C23)
============================

 Determines the type of an object.


###  Syntax

 

|  |  |  |
| --- | --- | --- |
| `typeof(` type `)` |  (1)  |  |
| `typeof(` expression `)` |  (2)  |  |
| `typeof_unqual(` type `)` |  (3)  |  |
| `typeof_unqual(` expression `)` |  (4)  |  |

 ###  Explanation

 
1) produces the type-name with any nested typeof-specifier evaluated  
2) yields the type-name representing the type of its operand. No implicit conversions are applied to expression. 
3,4) the same as (1) and (2) respectively but remove qualifiers ###  Notes

 `typeof` and `typeof_unqual` are collectively called the *typeof operators*. The `typeof` operators cannot be applied to bit-field members. If the type of the operand is a variably modified type, the operand is evaluated; otherwise, the operand is not evaluated. The result of the `typeof_unqual` operator is the non-atomic unqualified type that would result from the `typeof` operator. The `typeof` operator preserves all qualifiers.


###  Example

 ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 6.7.2.5 The typeof specifiers (p: 115-118)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/typeof>

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  |  code unit `*nnn*` |
| `\x*n...*` |  arbitrary hexadecimal value  |  code unit `*n...*` (arbitrary number of hexadecimal digits)  |
|  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, char8\_t (since C23), 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/escape>

malloc
======

 

|  Defined in header `<stdlib.h>` |  |  |
| --- | --- | --- |
| 
```
void *malloc( size_t size );
```
 |  |  |

 Allocates `size` bytes of uninitialized storage.


If allocation succeeds, returns a pointer that is suitably aligned for any object type with [fundamental alignment](../language/object#Alignment "c/language/object").


If `size` is zero, the behavior of `malloc` is implementation-defined. For example, a null pointer may be returned. Alternatively, a non-null pointer may be returned; but such a pointer should not be [dereferenced](../language/operator_member_access "c/language/operator member access"), and should be passed to `[free](free "c/memory/free")` to avoid memory leaks.




|  |  |
| --- | --- |
| `malloc` is thread-safe: it behaves as though only accessing the memory locations visible through its argument, and not any static storage.
A previous call to `[free](free "c/memory/free")` or `[realloc](realloc "c/memory/realloc")` that deallocates a region of memory *synchronizes-with* a call to `malloc` that allocates the same or a part of the same region of memory. This synchronization occurs after any access to the memory by the deallocating function and before any access to the memory by `malloc`. There is a single total order of all allocation and deallocation functions operating on each particular region of memory. | (since C11) |

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  size  |  -  |  number of bytes to allocate  |

 ###  Return value

 On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with `[free()](free "c/memory/free")` or `[realloc()](realloc "c/memory/realloc")`.


On failure, returns a null pointer.


###  Example

  
```
#include <stdio.h>   
#include <stdlib.h> 
 
int main(void) 
{
    int *p1 = malloc(4*sizeof(int));  // allocates enough for an array of 4 int
    int *p2 = malloc(sizeof(int[4])); // same, naming the type directly
    int *p3 = malloc(4*sizeof *p3);   // same, without repeating the type name
 
    if(p1) {
        for(int n=0; n<4; ++n) // populate the array
            p1[n] = n*n;
        for(int n=0; n<4; ++n) // print it back out
            printf("p1[%d] == %d\n", n, p1[n]);
    }
 
    free(p1);
    free(p2);
    free(p3);
}
```
 Output:



```
p1[0] == 0
p1[1] == 1
p1[2] == 4
p1[3] == 9
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.22.3.4 The malloc function (p: 254)

* C11 standard (ISO/IEC 9899:2011):
+ 7.22.3.4 The malloc function (p: 349)

* C99 standard (ISO/IEC 9899:1999):
+ 7.20.3.3 The malloc function (p: 314)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.3.3 The malloc function

 ###  See also

 

|  |  |
| --- | --- |
|  [free](free "c/memory/free") |  deallocates previously allocated memory  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/memory/c/malloc "cpp/memory/c/malloc") for `malloc` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/memory/malloc>

calloc
======

 

|  Defined in header `<stdlib.h>` |  |  |
| --- | --- | --- |
| 
```
void *calloc( size_t num, size_t size );
```
 |  |  |

 Allocates memory for an array of `num` objects of `size` and initializes all bytes in the allocated storage to zero.


If allocation succeeds, returns a pointer to the lowest (first) byte in the allocated memory block that is suitably aligned for any object type with [fundamental alignment](../language/object#Alignment "c/language/object").


If `size` is zero, the behavior is implementation defined (null pointer may be returned, or some non-null pointer may be returned that may not be used to access storage).




|  |  |
| --- | --- |
| `calloc` is thread-safe: it behaves as though only accessing the memory locations visible through its argument, and not any static storage.
A previous call to `[free](free "c/memory/free")` or `[realloc](realloc "c/memory/realloc")` that deallocates a region of memory *synchronizes-with* a call to `calloc` that allocates the same or a part of the same region of memory. This synchronization occurs after any access to the memory by the deallocating function and before any access to the memory by `calloc`. There is a single total order of all allocation and deallocation functions operating on each particular region of memory. | (since C11) |

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  num  |  -  |  number of objects  |
|  size  |  -  |  size of each object  |

 ###  Return value

 On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with `[free()](free "c/memory/free")` or `[realloc()](realloc "c/memory/realloc")`.


On failure, returns a null pointer.


###  Notes

 Due to the alignment requirements, the number of allocated bytes is not necessarily equal to `num*size`.


Initialization to all bits zero does not guarantee that a floating-point or a pointer would be initialized to 0.0 and the null pointer value, respectively (although that is true on all common platforms).


Originally (in C89), support for zero size was added to accommodate code such as.



```
OBJ *p = calloc(0, sizeof(OBJ)); // "zero-length" placeholder
...
while(1) { 
    p = realloc(p, c * sizeof(OBJ)); // reallocations until size settles
    ... // code that may change c or break out of loop
}
```
 ###  Example

  
```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    int *p1 = calloc(4, sizeof(int));    // allocate and zero out an array of 4 int
    int *p2 = calloc(1, sizeof(int[4])); // same, naming the array type directly
    int *p3 = calloc(4, sizeof *p3);     // same, without repeating the type name
 
    if(p2) {
        for(int n=0; n<4; ++n) // print the array
            printf("p2[%d] == %d\n", n, p2[n]);
    }
 
    free(p1);
    free(p2);
    free(p3);
}
```
 Output:



```
p2[0] == 0
p2[1] == 0
p2[2] == 0
p2[3] == 0
```
  ###  References

 * C17 standard (ISO/IEC 9899:2018):
+ 7.22.3.2 The calloc function (p: 253)

* C11 standard (ISO/IEC 9899:2011):
+ 7.22.3.2 The calloc function (p: 348)

* C99 standard (ISO/IEC 9899:1999):
+ 7.20.3.1 The calloc function (p: 313)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.3.1 The calloc function

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/memory/c/calloc "cpp/memory/c/calloc") for `calloc` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/memory/calloc>

free\_aligned\_sized
====================

 

|  Defined in header `<stdlib.h>` |  |  |
| --- | --- | --- |
| 
```
void free_aligned_sized( void* ptr, size_t alignment, size_t size);
```
 |  | (since C23) |

 Deallocates the space previously allocated by `[malloc()](malloc "c/memory/malloc")`, `[calloc()](calloc "c/memory/calloc")`, `aligned_alloc()`, (since C11) or `[realloc()](realloc "c/memory/realloc")`.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ptr  |  -  |  pointer to the memory to deallocate  |
|  alignment  |  -  |  alignment of memory to deallocate  |
|  size  |  -  |  size of memory to deallocate  |

 ###  Return value

 (none).


###  See also

 

|  |  |
| --- | --- |
|  [free](free "c/memory/free") |  deallocates previously allocated memory  (function) |
|  [free\_sized](free_sized "c/memory/free sized")
(C23) |  deallocates previously allocated sized memory  (function) |
|  [malloc](malloc "c/memory/malloc") |  allocates memory  (function) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/memory/free_aligned_sized>

aligned\_alloc
==============

 

|  Defined in header `<stdlib.h>` |  |  |
| --- | --- | --- |
| 
```
void *aligned_alloc( size_t alignment, size_t size );
```
 |  | (since C11) |

 Allocate `size` bytes of uninitialized storage whose alignment is specified by `alignment`. The `size` parameter must be an integral multiple of `alignment`.


`aligned_alloc` is thread-safe: it behaves as though only accessing the memory locations visible through its argument, and not any static storage.


A previous call to `[free](free "c/memory/free")` or `[realloc](realloc "c/memory/realloc")` that deallocates a region of memory *synchronizes-with* a call to `aligned_alloc` that allocates the same or a part of the same region of memory. This synchronization occurs after any access to the memory by the deallocating function and before any access to the memory by `aligned_alloc`. There is a single total order of all allocation and deallocation functions operating on each particular region of memory.


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  alignment  |  -  |  specifies the alignment. Must be a valid alignment supported by the implementation.  |
|  size  |  -  |  number of bytes to allocate. An integral multiple of `alignment` |

 ###  Return value

 On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with `[free](free "c/memory/free")` or `[realloc](realloc "c/memory/realloc")`.


On failure, returns a null pointer.


###  Notes

 Passing a `size` which is not an integral multiple of `alignment` or an `alignment` which is not valid or not supported by the implementation causes the function to fail and return a null pointer (C11, as published, specified undefined behavior in this case, this was corrected by [DR460](https://open-std.org/JTC1/SC22/WG14/www/docs/summary.htm#dr_460)). Removal of size restrictions to make it possible to allocate small objects at restrictive alignment boundaries (similar to [`alignas`](../language/_alignas "c/language/ Alignas")) has been proposed by [N2072](https://open-std.org/JTC1/SC22/WG14/www/docs/n2072.htm).


As an example of the "supported by the implementation" requirement, POSIX function [`posix_memalign`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_memalign.html) accepts any `alignment` that is a power of two and a multiple of `sizeof(void *)`, and POSIX-based implementations of `aligned_alloc` inherit this requirements. Also, this function is not supported in Microsoft C Runtime library because its implementation of `[free](free "c/memory/free")` is [unable to handle aligned allocations](https://learn.microsoft.com/en-us/cpp/standard-library/cstdlib#remarks-6) of any kind. Instead, MSVC provides [`_aligned_malloc`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/aligned-malloc) (to be freed with [`_aligned_free`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/aligned-free)).


Regular `[malloc](malloc "c/memory/malloc")` aligns memory suitable for any object type (which, in practice, means that it is aligned to `alignof([max\_align\_t](http://en.cppreference.com/w/c/types/max_align_t))`). The `aligned_alloc` is useful for over-aligned allocations, such as to [SSE](https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions "enwiki:Streaming SIMD Extensions"), cache line, or [VM page](https://en.wikipedia.org/wiki/Page_(computer_memory)#Multiple_page_sizes "enwiki:Page (computer memory)") boundary.


###  Example

  
```
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    int *p1 = malloc(10*sizeof *p1);
    printf("default-aligned addr:   %p\n", (void*)p1);
    free(p1);
 
    int *p2 = aligned_alloc(1024, 1024*sizeof *p2);
    printf("1024-byte aligned addr: %p\n", (void*)p2);
    free(p2);
}
```
 Possible output:



```
default-aligned addr:   0x1e40c20
1024-byte aligned addr: 0x1e41000
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.22.3.1 The aligned\_alloc function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.22.3.1 The aligned\_alloc function (p: 253)

* C11 standard (ISO/IEC 9899:2011):
+ 7.22.3.1 The aligned\_alloc function (p: 347-348)

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/memory/c/aligned_alloc "cpp/memory/c/aligned alloc") for `aligned_alloc` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/memory/aligned_alloc>

free
====

 

|  Defined in header `<stdlib.h>` |  |  |
| --- | --- | --- |
| 
```
void free( void *ptr );
```
 |  |  |

 Deallocates the space previously allocated by `[malloc()](malloc "c/memory/malloc")`, `[calloc()](calloc "c/memory/calloc")`, `aligned_alloc()`, (since C11) or `[realloc()](realloc "c/memory/realloc")`.


If `ptr` is a null pointer, the function does nothing.


The behavior is undefined if the value of `ptr` does not equal a value returned earlier by `[malloc()](malloc "c/memory/malloc")`, `[calloc()](calloc "c/memory/calloc")`, `[realloc()](realloc "c/memory/realloc")`, or `aligned_alloc()` (since C11).


The behavior is undefined if the memory area referred to by `ptr` has already been deallocated, that is, `free()`, `free_sized()`, `free_aligned_sized()` (since C23), or `[realloc()](realloc "c/memory/realloc")` has already been called with `ptr` as the argument and no calls to `[malloc()](malloc "c/memory/malloc")`, `[calloc()](calloc "c/memory/calloc")`, `[realloc()](realloc "c/memory/realloc")`, or `aligned_alloc()` (since C11) resulted in a pointer equal to `ptr` afterwards.


The behavior is undefined if after `free()` returns, an access is made through the pointer `ptr` (unless another allocation function happened to result in a pointer value equal to `ptr`).




|  |  |
| --- | --- |
| `free` is thread-safe: it behaves as though only accessing the memory locations visible through its argument, and not any static storage.
A call to `free` that deallocates a region of memory *synchronizes-with* a call to any subsequent allocation function that allocates the same or a part of the same region of memory. This synchronization occurs after any access to the memory by the deallocating function and before any access to the memory by the allocation function. There is a single total order of all allocation and deallocation functions operating on each particular region of memory. | (since C11) |

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ptr  |  -  |  pointer to the memory to deallocate  |

 ###  Return value

 (none).


###  Notes

 The function accepts (and does nothing with) the null pointer to reduce the amount of special-casing. Whether allocation succeeds or not, the pointer returned by an allocation function can be passed to `free()`.


###  Example

  
```
#include <stdlib.h>
 
int main(void)
{
    int *p1 = malloc(10*sizeof *p1);
    free(p1); // every allocated pointer must be freed
 
    int *p2 = calloc(10, sizeof *p2);
    int *p3 = realloc(p2, 1000*sizeof *p3);
    if(p3) // p3 not null means p2 was freed by realloc
       free(p3);
    else // p3 null means p2 was not freed
       free(p2);
}
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.24.3.3 The free function

* C17 standard (ISO/IEC 9899:2018):
+ 7.22.3.3 The free function (p: 254)

* C11 standard (ISO/IEC 9899:2011):
+ 7.22.3.3 The free function (p: 348)

* C99 standard (ISO/IEC 9899:1999):
+ 7.20.3.2 The free function (p: 313)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.3.2 The free function

 ###  See also

 

|  |  |
| --- | --- |
|  [malloc](malloc "c/memory/malloc") |  allocates memory  (function) |
|  [free\_sized](free_sized "c/memory/free sized")
(C23) |  deallocates previously allocated sized memory  (function) |
|  [free\_aligned\_sized](free_aligned_sized "c/memory/free aligned sized")
(C23) |  deallocates previously allocated sized and aligned memory  (function) |
| [C++ documentation](https://en.cppreference.com/w/cpp/memory/c/free "cpp/memory/c/free") for `free` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/memory/free>

free\_sized
===========

 

|  Defined in header `<stdlib.h>` |  |  |
| --- | --- | --- |
| 
```
void free_sized( void* ptr, size_t size );
```
 |  | (since C23) |

 Deallocates the space previously allocated by `[malloc()](malloc "c/memory/malloc")`, `[calloc()](calloc "c/memory/calloc")`, or `[realloc()](realloc "c/memory/realloc")` (but not `aligned_alloc()`).


###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ptr  |  -  |  pointer to the memory to deallocate  |
|  size  |  -  |  size of memory previously passed to an allocation function  |

 ###  Return value

 (none).


###  Notes

 ###  Possible implementation

 
```
void free_sized(void* ptr, size_t /*size*/)
{
    free(ptr);
}
```
 ###  Example

  
```
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
 
typedef struct
{
    size_t size;     // current number of elements
    size_t capacity; // reserved number of elements
    void** data;
} PtrVector;
 
PtrVector vector_create(size_t initial_capacity)
{
    PtrVector ret =
    {
        .capacity = initial_capacity,
        .data = (void**) malloc(initial_capacity * sizeof(void*))
    };
    return ret;
}
 
void vector_delete(PtrVector* self)
{
    free_sized(self->data, self->capacity * sizeof(void*));
}
 
void vector_push_back(PtrVector* self, void* value)
{
    if (self->size == self->capacity)
    {
        self->capacity *= 2;
        self->data = (void**) realloc(self->data, self->capacity * sizeof(void*));
    }
    self->data[self->size++] = value;
}
 
int main()
{
    int data = 42;
    float pi = 3.141592f;
    PtrVector v = vector_create(8);
    vector_push_back(&v, &data);
    vector_push_back(&v, &pi);
    printf("data[0] = %i\n", *(int*)v.data[0]);
    printf("data[1] = %f\n", *(float*)v.data[1]);
    vector_delete(&v);
}
```
 Output:



```
data[0] = 42
data[1] = 3.141592
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.24.3.4 The free\_sized function

 ###  See also

 

|  |  |
| --- | --- |
|  [free](free "c/memory/free") |  deallocates previously allocated memory  (function) |
|  [free\_aligned\_sized](free_aligned_sized "c/memory/free aligned sized")
(C23) |  deallocates previously allocated sized and aligned memory  (function) |
|  [malloc](malloc "c/memory/malloc") |  allocates memory  (function) |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/memory/free_sized>

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) |
| 
```
/*QVoid*/* bsearch( const void *key, /*QVoid*/ *ptr, size_t count, size_t size,
                    int (*comp)(const void*, const void*) );
```
 |  (3)  | (since C23) |
| 
```
/*QVoid*/* bsearch_s( const void *key, /*QVoid*/ *ptr, rsize_t count, rsize_t size,
                      int (*comp)(const void *, const void *, void *),
                      void *context );
```
 |  (4)  | (since C23) |

 
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 state 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`  (and the corresponding type-generic macro) (since C23) 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>`](../program "c/program").

 
3,4) Type-generic macros equivalent to (1) and (2) respectively. Let `T` be a unqualified object type (including `void`). * If `ptr` is of type `const T*`, the return type is `const void*`.
* Otherwise, if `ptr` is of type `T*`, the return type is `void*`.
* Otherwise, the behavior is undefined.

 If a macro definition of each of these generic functions is suppressed to access an actual function (e.g. if `(bsearch)`, `(bsearch_s)`, or a function pointer is used), the actual function declaration (1) or (2) becomes visible. 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.




|  |  |
| --- | --- |
| Direct usages of actual functions (1) and (2) are deprecated. | (since C23) |

 ###  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  |  -  |  state of the comparator (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. 
3,4) Same as (1) and (2) respectively, except that cv-qualification is adjusted. ###  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 represent the state of the comparator.


###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/algorithm/bsearch>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcsxfrm>

wcspbrk
=======

 

|  Defined in header `<wchar.h>` |  |  |
| --- | --- | --- |
| 
```
wchar_t *wcspbrk( const wchar_t *dest, const wchar_t *str );
```
 |  (1)  | (since C95) |
| 
```
/*QWchar_t*/ *wcspbrk( /*QWchar_t*/ *dest, const wchar_t *str );
```
 |  (2)  | (since C23) |

 
1) Finds the first character in wide string pointed to by `dest`, that is also in wide string pointed to by `str`. 
2) Type-generic function equivalent to (1). Let `T` be an unqualified wide character object type. * If `dest` is of type `const T*`, the return type is `const wchar_t*`.
* Otherwise, if `dest` is of type `T*`, the return type is `wchar_t*`.
* Otherwise, the behavior is undefined.

 If a macro definition of each of these generic functions is suppressed to access an actual function (e.g. if `(wcspbrk)` or a function pointer is used), the actual function declaration (1) becomes visible. ###  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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcspbrk>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcstok>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/thrd_equal>

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 <locale.h>
#include <stdio.h>
#include <wchar.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.29.4.4.5 The wmemcmp function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.29.4.4.5 The wmemcmp function (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wmemcmp>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/thrd_create>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/thrd_current>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/thrd_sleep>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/thrd_detach>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/thrd_join>

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)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/thrd_errors>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/ATOMIC_VAR_INIT>

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)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/ATOMIC_LOCK_FREE_consts>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_is_lock_free>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_store>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_exchange>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_load>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_compare_exchange>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_fetch_add>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_flag>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_fetch_sub>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/ATOMIC_FLAG_INIT>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_signal_fence>

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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.17.3.1 The kill\_dependency macro (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/kill_dependency>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_thread_fence>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/mtx_init>

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.


####  Release-Consume ordering

 If an atomic store in thread A is tagged `memory_order_release`, an atomic load in thread B from the same variable is tagged `memory_order_consume`, and the load in thread B reads a value written by the store in thread A, then the store in thread A is *dependency-ordered before* the load in thread B.


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`, an atomic load in thread B from the same variable is tagged `memory_order_acquire`, and the load in thread B reads a value written by the store in thread A, then the store in thread A *synchronizes-with* the load in thread B.


All memory writes (including 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

 

|  |  |
| --- | --- |
| 1.  | [MOESI protocol](https://en.wikipedia.org/wiki/MOESI_protocol "enwiki:MOESI protocol") |
| 2.  | [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  |
| 3.  | [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  |
| 4.  | [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  |
| 5.  | [Memory Models](https://research.swtch.com/mm) Russ Cox, 2021  |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/memory_order>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/mtx_lock>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/mtx_timedlock>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/mtx_trylock>

realloc
=======

 

|  Defined in header `<stdlib.h>` |  |  |
| --- | --- | --- |
| 
```
void *realloc( void *ptr, size_t new_size );
```
 |  |  |

 Reallocates the given area of memory. If `ptr` is not NULL, it must be previously allocated by `[malloc](malloc "c/memory/malloc")`, `[calloc](calloc "c/memory/calloc")` or `realloc` and not yet freed with a call to `[free](free "c/memory/free")` or `realloc`. Otherwise, the results are undefined.


The reallocation is done by either:



a) expanding or contracting the existing area pointed to by `ptr`, if possible. The contents of the area remain unchanged up to the lesser of the new and old sizes. If the area is expanded, the contents of the new part of the array are undefined. 
b) allocating a new memory block of size `new_size` bytes, copying memory area with size equal the lesser of the new and the old sizes, and freeing the old block. If there is not enough memory, the old memory block is not freed and null pointer is returned.


If `ptr` is `[NULL](../types/null "c/types/NULL")`, the behavior is the same as calling `[malloc](http://en.cppreference.com/w/c/memory/malloc)(new_size)`.


Otherwise,




|  |  |
| --- | --- |
| if `new_size` is zero, the behavior is implementation defined (null pointer may be returned (in which case the old memory block may or may not be freed), or some non-null pointer may be returned that may not be used to access storage). Such usage is deprecated (via [C DR 400](https://open-std.org/JTC1/SC22/WG14/www/docs/n2396.htm#dr_400)). (since C17). | (until C23) |
| if `new_size` is zero, the behavior is undefined. | (since C23) |

 

|  |  |
| --- | --- |
| `realloc` is thread-safe: it behaves as though only accessing the memory locations visible through its argument, and not any static storage.
A previous call to `[free](free "c/memory/free")` or `realloc` that deallocates a region of memory *synchronizes-with* a call to any allocation function, including `realloc` that allocates the same or a part of the same region of memory. This synchronization occurs after any access to the memory by the deallocating function and before any access to the memory by `realloc`. There is a single total order of all allocation and deallocation functions operating on each particular region of memory. | (since C11) |

 ###  Parameters

 

|  |  |  |
| --- | --- | --- |
|  ptr  |  -  |  pointer to the memory area to be reallocated  |
|  new\_size  |  -  |  new size of the array in bytes  |

 ###  Return value

 On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with `[free](free "c/memory/free")` or `realloc`. The original pointer `ptr` is invalidated and any access to it is undefined behavior (even if reallocation was in-place).


On failure, returns a null pointer. The original pointer `ptr` remains valid and may need to be deallocated with `[free](free "c/memory/free")` or `realloc`.


###  Notes

 Originally (in C89), support for zero size was added to accommodate code such as.



```
OBJ *p = calloc(0, sizeof(OBJ)); // "zero-length" placeholder
/*...*/
while (1)
{
    p = realloc(p, c * sizeof(OBJ)); // reallocations until size settles
    /* code that may change c or break out of loop */
}
```
 ###  Example

  
```
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void print_storage_info(const int* next, const int* prev, int ints)
{
    if (next)
        printf("%s location: %p. Size: %d ints (%ld bytes).\n",
               (next != prev ? "New" : "Old"), (void*)next, ints, ints * sizeof(int));
    else
        printf("Allocation failed.\n");
}
 
int main(void)
{
    const int pattern[] = {1, 2, 3, 4, 5, 6, 7, 8};
    const int pattern_size = sizeof pattern / sizeof(int);
    int *next = NULL, *prev = NULL;
 
    if ((next = (int*)malloc(pattern_size * sizeof *next))) // allocates an array
    {
        memcpy(next, pattern, sizeof pattern); // fills the array
        print_storage_info(next, prev, pattern_size);
    }
    else
        return EXIT_FAILURE;
 
    // Reallocate in cycle using the following values as a new storage size.
    const int realloc_size[] = {10, 12, 512, 32768, 65536, 32768};
 
    for (int i = 0; i != sizeof realloc_size / sizeof(int); ++i)
    {
        if ((next = (int*)realloc(prev = next, realloc_size[i] * sizeof(int))))
        {
            print_storage_info(next, prev, realloc_size[i]);
            assert(!memcmp(next, pattern, sizeof pattern));  // is pattern held
        }
        else // if realloc failed, the original pointer needs to be freed
        {
            free(prev);
            return EXIT_FAILURE;
        }
    }
 
    free(next); // finally, frees the storage
    return EXIT_SUCCESS;
}
```
 Possible output:



```
New location: 0x144c010. Size: 8 ints (32 bytes).
Old location: 0x144c010. Size: 10 ints (40 bytes).
New location: 0x144c450. Size: 12 ints (48 bytes).
Old location: 0x144c450. Size: 512 ints (2048 bytes).
Old location: 0x144c450. Size: 32768 ints (131072 bytes).
New location: 0x7f490c5bd010. Size: 65536 ints (262144 bytes).
Old location: 0x7f490c5bd010. Size: 32768 ints (131072 bytes).
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 7.22.3.5 The realloc function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.22.3.5 The realloc function (p: 254)

* C11 standard (ISO/IEC 9899:2011):
+ 7.22.3.5 The realloc function (p: 349)

* C99 standard (ISO/IEC 9899:1999):
+ 7.20.3.4 The realloc function (p: 314)

* C89/C90 standard (ISO/IEC 9899:1990):
+ 4.10.3.4 The realloc function

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/memory/c/realloc "cpp/memory/c/realloc") for `realloc` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/memory/realloc>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/call_once>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/mtx_unlock>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/mtx_destroy>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/mtx_types>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/thrd_yield>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/cnd_init>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/cnd_signal>

cnd\_broadcast
==============

 

|  Defined in header `<threads.h>` |  |  |
| --- | --- | --- |
| 
```
int cnd_broadcast( cnd_t *cond );
```
 |  | (since C11) |

 Unblocks all threads that are blocked on condition variable `cond` at the time of the call. If no threads are blocked on `cond`, the function 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/cnd_broadcast>

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` 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>`](../wide "c/string/wide").

 ###  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 <locale.h>
#include <stdio.h>
#include <wchar.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

 * C23 standard (ISO/IEC 9899:2023):
+ 7.29.4.2.4 The wmemmove function (p: TBD)
+ K.3.9.2.1.4 The wmemmove\_s function (p: TBD)

* C17 standard (ISO/IEC 9899:2018):
+ 7.29.4.2.4 The wmemmove function (p: TBD)
+ K.3.9.2.1.4 The wmemmove\_s function (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wmemmove>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/cnd_wait>

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 an 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/cnd_timedwait>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/cnd_destroy>

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)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/TSS_DTOR_ITERATIONS>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/string/wide/wcscspn>

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)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/tss_create>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/tss_get>

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)

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/tss_delete>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/attributes/fallthrough>

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

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/static_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)
```
  

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/thread_storage_duration>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/attributes/maybe_unused>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/attributes/deprecated>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_flag_test_and_set>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_fetch_xor>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_flag_clear>

C95
===

 **ISO/IEC 9899/AMD1:1995**, a.k.a. **C95**, is a previous revision of the C standard.


 New language features
----------------------

 * [Digraphs](language/operator_alternative "c/language/operator alternative")
* [`__STDC_VERSION__`](preprocessor/replace "c/preprocessor/replace")

  New library features
---------------------

 ###  New headers

 * [`<iso646.h>`](language/operator_alternative "c/language/operator alternative")
* [`<wctype.h>`](string/wide "c/string/wide")
* [`<wchar.h>`](string/wide "c/string/wide")

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/95>

C11
===

 **ISO/IEC 9899:2011**, a.k.a. **C11**, is a previous revision of the C standard.


 Obsolete
---------

 ###  Removed

 * `[gets()](io/gets "c/io/gets")`

  New language features
----------------------

 * Multithreaded environments
	+ [Atomic objects](language/atomic "c/language/atomic") ([`_Atomic`](keyword/_atomic "c/keyword/ Atomic"))
	+ [Thread local storage](language/storage_duration#Storage_duration "c/language/storage duration") ([`_Thread_local`](keyword/_thread_local "c/keyword/ Thread local"))
* Enhanced alignment support
	+ [Alignment query](language/_alignof "c/language/ Alignof") ([`_Alignof`](keyword/_alignof "c/keyword/ Alignof"))
	+ [Alignment strengthening](language/_alignas "c/language/ Alignas") ([`_Alignas`](keyword/_alignas "c/keyword/ Alignas"))
	+ Over-aligned types
* Unicode support
	+ [`u`/`U` character constants](language/character_constant "c/language/character constant")
	+ [`u8`/`u`/`U` string literals](language/string_literal "c/language/string literal")
* [Generic selection expressions](language/generic "c/language/generic") ([`_Generic`](keyword/_generic "c/keyword/ Generic"))
* [Non-returning functions](language/_noreturn "c/language/ Noreturn") ([`_Noreturn`](keyword/_noreturn "c/keyword/ Noreturn"))
* Anonymous [struct](language/struct "c/language/struct") and [union](language/union "c/language/union") members
* Fine-grained [evaluation order](language/eval_order "c/language/eval order")
* Extending the lifetime of [temporary objects](language/lifetime#Temporary_lifetime "c/language/lifetime")
* [`_Static_assert`](language/_static_assert "c/language/ Static assert")
* [Analyzability](language/analyzability "c/language/analyzability")

 ###  Feature test macros for optional features

 * [`__STDC_ANALYZABLE__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates analyzability is supported.
* [`__STDC_LIB_EXT1__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates bounds checking functions are supported.
* [`__STDC_NO_ATOMICS__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates atomic objects and the atomic operation library are not supported.
* [`__STDC_NO_COMPLEX__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates complex types and the complex math functions are not supported. These features were mandatory in C99.
* [`__STDC_NO_THREADS__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates thread local storage and the thread support library are not supported.
* [`__STDC_NO_VLA__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates [variable length arrays and variably modified types](language/array#Variable-length_arrays "c/language/array") are not supported. These features were mandatory in C99.

  New library features
---------------------

 ###  New headers

 * [`<stdalign.h>`](types "c/types")
* [`<stdatomic.h>`](thread#Atomic_operations "c/thread")
* [`<stdnoreturn.h>`](language/_noreturn "c/language/ Noreturn")
* [`<threads.h>`](thread "c/thread")
* [`<uchar.h>`](string/multibyte "c/string/multibyte")

 ###  Library features

 * [Concurrency support library](thread "c/thread")
* [`aligned_alloc()`](memory/aligned_alloc "c/memory/aligned alloc")
* UTF-16/32 type aliases
	+ [`char16_t`](string/multibyte/char16_t "c/string/multibyte/char16 t")
	+ [`char32_t`](string/multibyte/char32_t "c/string/multibyte/char32 t")
* UTF-16/32 conversion functions
	+ `[mbrtoc16()](string/multibyte/mbrtoc16 "c/string/multibyte/mbrtoc16")`
	+ `[mbrtoc32()](string/multibyte/mbrtoc32 "c/string/multibyte/mbrtoc32")`
	+ `[c16rtomb()](string/multibyte/c16rtomb "c/string/multibyte/c16rtomb")`
	+ `[c32rtomb()](string/multibyte/c32rtomb "c/string/multibyte/c32rtomb")`
* `[quick\_exit](program/quick_exit "c/program/quick exit")`
* `[at\_quick\_exit](program/at_quick_exit "c/program/at quick exit")`
* Exclusive modes of `[fopen()](io/fopen "c/io/fopen")` and `[freopen()](io/freopen "c/io/freopen")` (`"x"`)
* [Bounds checking functions](error#Bounds_checking "c/error")
* [`timespec`](chrono/timespec "c/chrono/timespec")
* [`timespec_get()`](chrono/timespec_get "c/chrono/timespec get")
* [`CMPLX(F|L)?`](numeric/complex/cmplx "c/numeric/complex/CMPLX")
* New numeric limit macros
	+ [`(FLT|DBL|LDBL)_DECIMAL_DIG`](types/limits "c/types/limits")
	+ [`(FLT|DBL|LDBL)_TRUE_MIN`](types/limits "c/types/limits")
	+ [`(FLT|DBL|LDBL)_HAS_SUBNORM`](types/limits "c/types/limits")
* Thread local `[errno](error/errno "c/error/errno")`

  Defect reports
---------------

 [Template:c/language/history/DR11](https://en.cppreference.com/mwiki/index.php?title=Template:c/language/history/DR11&action=edit&redlink=1 "Template:c/language/history/DR11 (page does not exist)").


 Compiler support
-----------------

 [Template:c/compiler support/11](https://en.cppreference.com/mwiki/index.php?title=Template:c/compiler_support/11&action=edit&redlink=1 "Template:c/compiler support/11 (page does not exist)").




 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/11>

Current Status
==============

 **Recent milestones: C17 published, C23 underway**.


C17 has been published, and work is now underway on C23.


[The current schedule is in paper N2984](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2984.pdf).


You can also visit [open-std.org](https://www.open-std.org/jtc1/sc22/wg14/www/documents) to get the latest C standards committee papers. Reading through those proposals, you can track the C developing trends and know how does a cool idea turned into the standard. However, those papers **ARE NOT** and also **SHOULD NOT BE TREATED AS** the standard documents.


###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/current_status "cpp/current status") for Current status |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/current_status>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_fetch_or>

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 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\_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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic/atomic_fetch_and>

\_Alignof operator (since C11)
==============================

 Queries the alignment requirement of its operand type.


###  Syntax

 

|  |  |  |
| --- | --- | --- |
| `_Alignof(` type-name `)` |  | (since C11) |
| `alignof(` type-name `)` |  | (since C23) |

 

|  |  |
| --- | --- |
| This operator is typically used through the convenience macro [`alignof`](../types "c/types"), which is provided in the header [`<stdalign.h>`](../types "c/types") | (until C23) |

 ###  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` (until C23)`alignof` (since C23) with expressions is allowed by some C compilers as a non-standard extension.


###  Keywords

 [`alignof`](../keyword/alignof "c/keyword/alignof"), [`_Alignof`](../keyword/_alignof "c/keyword/ Alignof").


###  Example

  
```
#include <stdalign.h>
#include <stddef.h>
#include <stdio.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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.5.3.4 The sizeof and alignof operators (p: TBD)

* 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` |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/alignof>

C99
===

 **ISO/IEC 9899:1999**, a.k.a. **C99**, is a previous revision of the C standard.


 Obsolete
---------

 ###  Removed

 * Implicit `int` in declarations
* Implicit function declarations

 ###  Deprecated

 * `[gets()](io/gets "c/io/gets")`

  New language features
----------------------

 * Universal-character-names in [identifiers](language/identifier "c/language/identifier")
* Increased [translation limits](language/identifier#Translation_limits "c/language/identifier")
* `//` [comments](comment "c/comment")
* [`restrict`](language/restrict "c/language/restrict") pointers
* Enhanced [arithmetic types](language/arithmetic_types "c/language/arithmetic types")
	+ `_Bool`
	+ `long long` and `unsigned long long`
	+ Extended integer types
	+ [`_Complex`](keyword/_complex "c/keyword/ Complex") types (`float _Complex`, `double _Complex`, and `long double _Complex`)
	+ [`_Imaginary`](keyword/_imaginary "c/keyword/ Imaginary") types (`float _Imaginary`, `double _Imaginary`, and `long double _Imaginary`)
* Flexible array members
* [Variable-length array](language/array#Variable-length_arrays "c/language/array") (VLA) types and variably-modified (VM) types
* Improvements of braced-init-list for [array](language/array_initialization "c/language/array initialization"), [struct and union](language/struct_initialization "c/language/struct initialization") types
	+ Non-constant initializers
	+ Designated initializers
* Idempotent cvr-qualifiers
* Trailing comma in [enumerator-list](language/enum "c/language/enum")
* Hexadecimal [floating constants](language/floating_constant "c/language/floating constant")
* [Compound literals](language/compound_literal "c/language/compound literal")
* Floating-point environment
* Requiring truncation for divisions of signed integer types
* Implicit `return 0;` in the [`main()` function](language/main_function "c/language/main function")
* Declarations and statements in mixed order
* init-statement in [`for`](language/for "c/language/for") loops
* [`inline`](language/inline "c/language/inline") functions
* Predefined variable [`__func__`](language/function_definition "c/language/function definition")
* Cvr-qualifiers and `static` in `[]` within function declarations
* [Variadic macros](preprocessor/replace "c/preprocessor/replace")
* [`_Pragma`](preprocessor/impl "c/preprocessor/impl") preprocessor operator
* Standard pragmas for floating-point evaluation
	+ `STDC` [`FENV_ACCESS`](preprocessor/impl "c/preprocessor/impl")
	+ `STDC` [`FP_CONTRACT`](preprocessor/impl "c/preprocessor/impl")
	+ `STDC` [`CX_LIMITED_RANGE`](preprocessor/impl "c/preprocessor/impl")

 ###  Feature test macros for optional features

 * [`__STDC_IEC_559__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates IEEE-754 binary floating-point arithmetic and required math functions are supported.
* [`__STDC_IEC_559_COMPLEX__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates IEEE-754 complex arithmetic and required math functions are supported.
* [`__STDC_HOSTED__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates that the implementation is [hosted](language/conformance "c/language/conformance").
* [`__STDC_ISO_10646__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates that Unicode is used by the wide literal encodings and expands to the latest supported revision.
* [`__STDC_MB_MIGHT_NEQ_WC__`](preprocessor/replace "c/preprocessor/replace")
	+ Indicates that there are some characters in the basic character set having different code unit values in [ordinary and wide literal encodings](language/character_constant "c/language/character constant").

  New library features
---------------------

 ###  New headers

 * [`<complex.h>`](numeric/complex "c/numeric/complex")
* [`<fenv.h>`](numeric/fenv "c/numeric/fenv")
* [`<inttypes.h>`](types/integer "c/types/integer")
* [`<stdbool.h>`](types "c/types")
* [`<stdint.h>`](types/integer "c/types/integer")
* [`<tgmath.h>`](numeric/tgmath "c/numeric/tgmath")

 ###  Library features

 * [Aliases for integer types](types/integer "c/types/integer")
	+ Integer types with exact width (`int*N*_t` and `uint*N*_t`)
	+ Fastest integer types with at least given width (`int_fast*N*_t` and `uint_fast*N*_t`)
	+ Smallest integer types with at least given width (`int_least*N*_t` and `uint_least*N*_t`)
	+ Integer types capable for cast between object pointers (`[intptr\_t](types/integer "c/types/integer")` and `[uintptr\_t](types/integer "c/types/integer")`)
	+ Integer types with maximum width (`[intmax\_t](types/integer "c/types/integer")` and `[uintmax\_t](types/integer "c/types/integer")`)
* Operations on `long long` and `[intmax\_t](types/integer "c/types/integer")`
	+ `[llabs()](numeric/math/abs "c/numeric/math/abs")`
	+ `[imaxabs()](numeric/math/abs "c/numeric/math/abs")`
	+ `[lldiv()](numeric/math/div "c/numeric/math/div")`
	+ `[imaxdiv()](numeric/math/div "c/numeric/math/div")`
* [Floating-point environment access](numeric/fenv "c/numeric/fenv")
* Extended floating-point math functions
	+ New floating-point math functions
	+ -`f` and -`l` variants for existing and new floating-point math functions
	+ [Math error handling](numeric/math/math_errhandling "c/numeric/math/math errhandling")
* [Complex functions](numeric/complex "c/numeric/complex")
* `[\_Exit()](program/_exit "c/program/ Exit")`
* Formatting support for `long long`, `unsigned long long`, `[intmax\_t](types/integer "c/types/integer")`, and `[uintmax\_t](types/integer "c/types/integer")`
	+ `[atoll()](string/byte/atoi "c/string/byte/atoi")`
	+ `[strtoimax()](string/byte/strtoimax "c/string/byte/strtoimax")`
	+ `[strtoll()](string/byte/strtol "c/string/byte/strtol")`
	+ `[strtoull](string/byte/strtoul "c/string/byte/strtoul")`
	+ `[strtoumax()](string/byte/strtoimax "c/string/byte/strtoimax")`
	+ `[wcstoimax()](string/wide/wcstoimax "c/string/wide/wcstoimax")`
	+ `[wcstoll()](string/wide/wcstol "c/string/wide/wcstol")`
	+ `[wcstoull()](string/wide/wcstoul "c/string/wide/wcstoul")`
	+ `[wcstoumax()](string/wide/wcstoimax "c/string/wide/wcstoimax")`
* `[isblank()](string/byte/isblank "c/string/byte/isblank")` and `[iswblank()](string/wide/iswblank "c/string/wide/iswblank")`
* `[snprintf()](io/fprintf "c/io/fprintf")` and `[vsnprintf()](io/vfprintf "c/io/vfprintf")`
* `[vfscanf()](io/vfscanf "c/io/vfscanf")` and `[vfwscanf()](io/vfwscanf "c/io/vfwscanf")` function families
* Extensions for [`fscanf()`](io/fscanf "c/io/fscanf") and [`fprintf()`](io/fprintf "c/io/fprintf") function families
	+ `ll` length modifier for `long long` and `unsigned long long`
	+ `hh` length modifier for `signed char` and `unsigned char`
	+ `l` length modifier for `double`
	+ `z` length modifier for `[size\_t](types/size_t "c/types/size t")` and its signed version
	+ `t` length modifier for `[ptrdiff\_t](types/ptrdiff_t "c/types/ptrdiff t")` and its unsigned version
	+ `j` length modifier for `[intmax\_t](types/integer "c/types/integer")` and `[uintmax\_t](types/integer "c/types/integer")`
	+ `a` conversion specifier for floating-point types
* Numeric limit macros for `long long` and `unsigned long long`
* Numeric limit macros corresponding to existing and new aliases for integer types
* [Format string macros for integer types](types/integer#Format_macro_constants "c/types/integer")
* [`va_copy`](variadic/va_copy "c/variadic/va copy")
* [Type-generic math macros](numeric/tgmath "c/numeric/tgmath")
* Floating-point comparison macros
* Floating-point classification macros
* Compatibility macros for `_Bool` ([`bool`](types "c/types"), [`true`](types "c/types"), and [`false`](types "c/types"))

  Defect reports
---------------

 [Template:c/language/history/DR99](https://en.cppreference.com/mwiki/index.php?title=Template:c/language/history/DR99&action=edit&redlink=1 "Template:c/language/history/DR99 (page does not exist)").


 Compiler support
-----------------

 ###  C99 core language features

 

|  C99 feature |  Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++ (ex Portland Group/PGI) | Nvidia nvcc |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|  Universal-character-names in [identifiers](language/identifier "c/language/identifier") | N/A | 3.1  | Yes  |  |  |  |  |  |  |  |  |  |  |
|  Increased [translation limits](language/identifier#Translation_limits "c/language/identifier") |  N590  | 0.9  | N/A |  |  |  |  |  |  |  |  |  |  |
| `//` [comments](comment "c/comment") | [N644](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n644.htm) | 2.7  | Yes  |  |  |  |  |  |  |  |  |  |  |
| [`restrict`](language/restrict "c/language/restrict") pointers  |  N448  | 2.95  | Yes  |  |  |  |  |  |  |  |  |  |  |
|  Enhanced [arithmetic types](language/arithmetic_types "c/language/arithmetic types") | [N815](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n815.htm)[N601](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n601.ps)[N620](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n620.ps)[N638](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n638.ps)[N657](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n657.ps)[N694](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n694.ps)[N809](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n809.ps) | Yes  | partial  |  |  |  |  |  |  |  |  |  |  |
|  Flexible array members  | N/A | 3.0  | Yes  |  |  |  |  |  |  |  |  |  |  |
| [Variable-length array](language/array#Variable-length_arrays "c/language/array") (VLA) types  | [N683](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n683.htm) | 0.9  | Yes  |  |  |  |  |  |  |  |  |  |  |
|  Variably-modified (VM) types  | [N2778](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2778.pdf) | N/A | Yes  |  |  |  |  |  |  |  |  |  |  |
|  Designated initializers  | [N494](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n494.pdf) | 3.0  | Yes  |  |  |  |  |  |  |  |  |  |  |
|  Non-constant initializers  | N/A | 1.21  | N/A |  |  |  |  |  |  |  |  |  |  |
|  Idempotent cvr-qualifiers  |  N505  | 3.0  | N/A |  |  |  |  |  |  |  |  |  |  |
|  Trailing comma in [enumerator-list](language/enum "c/language/enum") | N/A | 0.9  | Yes  |  |  |  |  |  |  |  |  |  |  |
|  Hexadecimal [floating constants](language/floating_constant "c/language/floating constant") |  N308  | 2.8  | Yes  |  |  |  |  |  |  |  |  |  |  |
| [Compound literals](language/compound_literal "c/language/compound literal") | [N716](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n716.htm) | 3.1  | Yes  |  |  |  |  |  |  |  |  |  |  |
|  Floating-point environment  | N/A | partial  | partial  |  |  |  |  |  |  |  |  |  |  |
|  Requiring truncation for divisions of signed integer types  | [N617](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n617.htm) | 0.9  | N/A |  |  |  |  |  |  |  |  |  |  |
|  Implicit `return 0;` in the [`main()` function](language/main_function "c/language/main function") | N/A | Yes  | Yes  |  |  |  |  |  |  |  |  |  |  |
|  Declarations and statements in mixed order  | [N740](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n740.htm) | 3.0  | Yes  |  |  |  |  |  |  |  |  |  |  |
| init-statement in [`for`](language/for "c/language/for") loops  | N/A | Yes  | Yes  |  |  |  |  |  |  |  |  |  |  |
| [`inline`](language/inline "c/language/inline") functions  | [N741](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n741.htm) | 4.3  | Yes  |  |  |  |  |  |  |  |  |  |  |
|  Predefined variable [`__func__`](language/function_definition "c/language/function definition") | [N611](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n611.ps) | 2.95  | Yes  |  |  |  |  |  |  |  |  |  |  |
|  Cvr-qualifiers and `static` in `[]` within function declarations  | N/A | 3.1  | Yes  |  |  |  |  |  |  |  |  |  |  |
| [Variadic macros](preprocessor/replace "c/preprocessor/replace") | [N707](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n707.htm) | 2.95  | Yes  |  |  |  |  |  |  |  |  |  |  |
| [`_Pragma`](preprocessor/impl "c/preprocessor/impl") preprocessor operator  | [N634](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n634.ps) | 3.0  | Yes  |  |  |  |  |  |  |  |  |  |  |
|  Standard pragmas for floating-point evaluation  | [N631](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n631.htm)[N696](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n696.ps) |  No  |  No  |  |  |  |  | Yes  | Yes  |  |  |  |  |
|  C99 feature |  Paper(s) | GCC | Clang | MSVC | Apple Clang | EDG eccp | Intel C++ | IBM XLC++ | Sun/Oracle C++ | Embarcadero C++ Builder | Cray | Nvidia HPC C++(ex Portland Group/PGI) | Nvidia nvcc |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/99>

\_Alignas (since C11), alignas (since C23)
==========================================

 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` `(` expression `)` |  (2)  | (since C23) |
| `_Alignas` `(` type `)` |  (3)  | (since C11) |
| `alignas` `(` type `)` |  (4)  | (since C23) |

 

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

 

|  |  |
| --- | --- |
| The keyword `_Alignas` is also available as convenience macro [`alignas`](../types "c/types"), available in the header [`<stdalign.h>`](../types "c/types"). | (until C23) |

 ###  Explanation

 The `_Alignas` (until C23)`alignas` (since C23) specifier can only be used when declaring objects that are not [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,2) the result of the expression, unless it is zero 
3,4) the alignment requirement of type, that is, to `_Alignof(type)` (until C23)`alignof(type)` (since C23)
 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` (until C23)`alignas` (since C23) specifiers appear in the same declaration, the strictest one is used.


`_Alignas` (until C23)`alignas` (since C23) specifier only needs to appear on the [definition](declarations#Definitions "c/language/declarations") of an object, but if any declaration uses `_Alignas` (until C23)`alignas` (since C23), it must specify the same alignment as the `_Alignas` (until C23)`alignas` (since C23) 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` (until C23)`alignas` (since C23) in a member declaration.


###  Keywords

 [`alignas`](../keyword/alignas "c/keyword/alignas"), [`_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
    (void)d; // suppresses "maybe unused" warning
}
```
 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

 * C23 standard (ISO/IEC 9899:2023):
+ 6.7.5 Alignment specifier (p: TBD)
+ 6.2.8 Alignment of objects (p: TBD)
+ 7.15 Alignment <stdalign.h> (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/alignas>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/thread/tss_set>

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/attributes/nodiscard>

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

 Constructing a complete object type such that the number of bytes in its object representation is not representable in the type `[size\_t](../types/size_t "c/types/size t")` (i.e. the result type of [`sizeof`](sizeof "c/language/sizeof") operator), including forming such a VLA type at runtime, (since C99) is undefined behavior.


###  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](bit_field "c/language/bit field") 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
 | (until C23) |

 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, a program necessitating the composite type of both types has undefined behavior.
* 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.

 The element type of the composite type is the composite type of the two element types. 

|  |  |
| --- | --- |
| * 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.
 | (until C23) |

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

 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 (*)[]); // C23: Error: conflicting types for 'f'
// 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 |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/compatible_type>

Static assertion (since C11)
============================

 ###  Syntax

 

|  |  |  |
| --- | --- | --- |
| `_Static_assert` `(` expression `,` message `)` |  | (since C11)(deprecated in C23) |
| `static_assert` `(` expression `,` message `)` |  | (since C23) |
| `_Static_assert` `(` expression `)` |  | (since C23)(deprecated in C23) |
| `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>`](../error "c/error"). | (until C23) |
| Both of `static_assert` and `_Static_assert` have the same effects. `_Static_assert` is a deprecated spelling that is kept for compatibility.
An implementation may also define `static_assert` and/or `_Static_assert` as predefined macros, and `static_assert` is no longer provided by [`<assert.h>`](../error "c/error"). | (since C23) |

 ###  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 as part of the error message (except that characters not in [basic character set](charset "c/language/charset") are not required to be displayed) (until C23)should display message (if provided) as part of the error message (since C23).


Otherwise, if expression does not equal zero, nothing happens; no code is emitted.


###  Keywords

 [`_Static_assert`](../keyword/_static_assert "c/keyword/ Static assert"), [`static_assert`](../keyword/static_assert "c/keyword/static assert").


###  Example

  
```
#include <assert.h> // no longer needed since C23
 
int main(void)
{
    // Test if math works.
    static_assert((2 + 2) % 3 == 1, // or _Static_assert(...
                  "Whoa dude, you knew!");
 
    // This will produce an error at compile time.
    static_assert(sizeof(int) < sizeof(char),
                 "this program requires that int is less than char");
}
```
  ###  References

 * C23 standard (ISO/IEC 9899:2023):
+ 6.7.11 Static assertions (p: TBD)

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

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/static_assert>

Atomic operations library
=========================

 If the macro constant `__STDC_NO_ATOMICS__`(C11) is defined by the compiler, the header `<stdatomic.h>`, the keyword `_Atomic`, and all of the names listed here are not provided.


###  Types

 

|  Defined in header `<stdatomic.h>` |
| --- |
|  [memory\_order](atomic/memory_order "c/atomic/memory order")
(C11) |  defines memory ordering constraints  (enum) |
|  [atomic\_flag](atomic/atomic_flag "c/atomic/atomic flag")
(C11) |  lock-free atomic boolean flag  (struct) |

 ###  Macros

 

|  Defined in header `<stdatomic.h>` |
| --- |
|  [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/atomic_lock_free_consts "c/atomic/ATOMIC LOCK FREE consts")
(C11) |  indicates that the given atomic type is lock-free  (macro constant) |
|  [ATOMIC\_FLAG\_INIT](atomic/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) |
|  [ATOMIC\_VAR\_INIT](atomic/atomic_var_init "c/atomic/ATOMIC VAR INIT")
(C11)(deprecated in C17)(removed in C23) |  initializes a new atomic object  (function macro) |
|  [kill\_dependency](atomic/kill_dependency "c/atomic/kill dependency")
(C11) |  breaks a dependency chain for `[memory\_order\_consume](http://en.cppreference.com/w/c/atomic/memory_order)`  (function macro) |

 ###  Functions

 

|  Defined in header `<stdatomic.h>` |
| --- |
|  [atomic\_flag\_test\_and\_setatomic\_flag\_test\_and\_set\_explicit](atomic/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/atomic_flag_clear "c/atomic/atomic flag clear")
(C11) |  sets an atomic\_flag to false  (function) |
|  [atomic\_init](atomic/atomic_init "c/atomic/atomic init")
(C11) |  initializes an existing atomic object  (function) |
|  [atomic\_is\_lock\_free](atomic/atomic_is_lock_free "c/atomic/atomic is lock free")
(C11) |  indicates whether the atomic object is lock-free  (function) |
|  [atomic\_storeatomic\_store\_explicit](atomic/atomic_store "c/atomic/atomic store")
(C11) |  stores a value in an atomic object  (function) |
|  [atomic\_loadatomic\_load\_explicit](atomic/atomic_load "c/atomic/atomic load")
(C11) |  reads a value from an atomic object  (function) |
|  [atomic\_exchangeatomic\_exchange\_explicit](atomic/atomic_exchange "c/atomic/atomic exchange")
(C11) |  swaps a value with the value of an atomic object  (function) |
|  [atomic\_compare\_exchange\_strongatomic\_compare\_exchange\_strong\_explicitatomic\_compare\_exchange\_weakatomic\_compare\_exchange\_weak\_explicit](atomic/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) |
|  [atomic\_fetch\_addatomic\_fetch\_add\_explicit](atomic/atomic_fetch_add "c/atomic/atomic fetch add")
(C11) |  atomic addition  (function) |
|  [atomic\_fetch\_subatomic\_fetch\_sub\_explicit](atomic/atomic_fetch_sub "c/atomic/atomic fetch sub")
(C11) |  atomic subtraction  (function) |
|  [atomic\_fetch\_oratomic\_fetch\_or\_explicit](atomic/atomic_fetch_or "c/atomic/atomic fetch or")
(C11) |  atomic bitwise OR  (function) |
|  [atomic\_fetch\_xoratomic\_fetch\_xor\_explicit](atomic/atomic_fetch_xor "c/atomic/atomic fetch xor")
(C11) |  atomic bitwise exclusive OR  (function) |
|  [atomic\_fetch\_andatomic\_fetch\_and\_explicit](atomic/atomic_fetch_and "c/atomic/atomic fetch and")
(C11) |  atomic bitwise AND  (function) |
|  [atomic\_thread\_fence](atomic/atomic_thread_fence "c/atomic/atomic thread fence")
(C11) |  generic memory order-dependent fence synchronization primitive  (function) |
|  [atomic\_signal\_fence](atomic/atomic_signal_fence "c/atomic/atomic signal fence")
(C11) |  fence between a thread and a signal handler executed in the same thread  (function) |

 ###  Types

 The standard library offers convenience typedefs for the [core language atomic types](language/atomic "c/language/atomic").




|  Typedef name  |  Full type name  |
| --- | --- |
| `atomic_bool` | `_Atomic _Bool` |
| `atomic_char` | `_Atomic char` |
| `atomic_schar` | `_Atomic signed char` |
| `atomic_uchar` | `_Atomic unsigned char` |
| `atomic_short` | `_Atomic short` |
| `atomic_ushort` | `_Atomic unsigned short` |
| `atomic_int` | `_Atomic int` |
| `atomic_uint` | `_Atomic unsigned int` |
| `atomic_long` | `_Atomic long` |
| `atomic_ulong` | `_Atomic unsigned long` |
| `atomic_llong` | `_Atomic long long` |
| `atomic_ullong` | `_Atomic unsigned long long` |
| `atomic_char16_t` | `_Atomic char16_t` |
| `atomic_char32_t` | `_Atomic char32_t` |
| `atomic_wchar_t` | `_Atomic wchar_t` |
| `atomic_int_least8_t` | `_Atomic [int\_least8\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_least8_t` | `_Atomic [uint\_least8\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_least16_t` | `_Atomic [int\_least16\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_least16_t` | `_Atomic [uint\_least16\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_least32_t` | `_Atomic [int\_least32\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_least32_t` | `_Atomic [uint\_least32\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_least64_t` | `_Atomic [int\_least64\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_least64_t` | `_Atomic [uint\_least64\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_fast8_t` | `_Atomic [int\_fast8\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_fast8_t` | `_Atomic [uint\_fast8\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_fast16_t` | `_Atomic [int\_fast16\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_fast16_t` | `_Atomic [uint\_fast16\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_fast32_t` | `_Atomic [int\_fast32\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_fast32_t` | `_Atomic [uint\_fast32\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_int_fast64_t` | `_Atomic [int\_fast64\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uint_fast64_t` | `_Atomic [uint\_fast64\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_intptr_t` | `_Atomic [intptr\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uintptr_t` | `_Atomic [uintptr\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_size_t` | `_Atomic [size\_t](http://en.cppreference.com/w/c/types/size_t)` |
| `atomic_ptrdiff_t` | `_Atomic [ptrdiff\_t](http://en.cppreference.com/w/c/types/ptrdiff_t)` |
| `atomic_intmax_t` | `_Atomic [intmax\_t](http://en.cppreference.com/w/c/types/integer)` |
| `atomic_uintmax_t` | `_Atomic [uintmax\_t](http://en.cppreference.com/w/c/types/integer)` |

 ###  References

 * C11 standard (ISO/IEC 9899:2011):
+ 7.17 Atomics <stdatomic.h> (p: 273-286)
+ 7.31.8 Atomics <stdatomic.h> (p: 455-456)

 ###  See also

 

|  |
| --- |
| [C++ documentation](https://en.cppreference.com/w/cpp/atomic "cpp/atomic") for Atomic operations library |

 

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/atomic>

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

 © cppreference.com  
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.  

<https://en.cppreference.com/w/c/language/file_scope>

c