C data types
Template:Short description Template:Use dmy dates Template:More citations needed Template:C Standard Library In the C programming language, data types constitute the semantics and characteristics of storage of data elements. They are expressed in the language syntax in form of declarations for memory locations or variables. Data types also determine the types of operations or methods of processing of data elements.
The C language provides basic arithmetic types, such as integer and real number types, and syntax to build array and compound types. The C standard library contains additional definitions of support types, that have additional properties, such as providing storage with an exact size, independent of the language implementation on specific hardware platforms.[1][2]
Primary types
Main types
The C language provides the four basic arithmetic type specifiers <syntaxhighlight lang="text" class="" style="" inline="1">char</syntaxhighlight>, <syntaxhighlight lang="text" class="" style="" inline="1">int</syntaxhighlight>, <syntaxhighlight lang="text" class="" style="" inline="1">float</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">double</syntaxhighlight> (as well as the Boolean type <syntaxhighlight lang="text" class="" style="" inline="1">bool</syntaxhighlight>), and the modifiers <syntaxhighlight lang="text" class="" style="" inline="1">signed</syntaxhighlight>, <syntaxhighlight lang="text" class="" style="" inline="1">unsigned</syntaxhighlight>, <syntaxhighlight lang="text" class="" style="" inline="1">short</syntaxhighlight>, and <syntaxhighlight lang="text" class="" style="" inline="1">long</syntaxhighlight>. The following table lists the permissible combinations in specifying a large set of storage size-specific declarations.
| Type | Explanation | Size (bits)Template:Efn | Format specifier | Range | Suffix for decimal constants |
|---|---|---|---|---|---|
| <syntaxhighlight lang="text" class="" style="" inline="1">bool</syntaxhighlight> | Boolean type, added in C23. (Previously <syntaxhighlight lang="text" class="" style="" inline="1">_Bool</syntaxhighlight> added in C99,[3] but its size and its range were not specified.) | 1 (exact) | %d |
Template:Bracket | Template:N/a |
| <syntaxhighlight lang="text" class="" style="" inline="1">char</syntaxhighlight> | Smallest addressable unit of the machine that can contain basic character set. It is an integer type. Actual type can be either signed or unsigned. It contains <syntaxhighlight lang="text" class="" style="" inline="1">CHAR_BIT</syntaxhighlight> bits.[4] | ≥8 | %c |
Template:Bracket | Template:N/a |
| <syntaxhighlight lang="text" class="" style="" inline="1">signed char</syntaxhighlight> | Of the same size as <syntaxhighlight lang="text" class="" style="" inline="1">char</syntaxhighlight>, but guaranteed to be signed. Capable of containing at least the Template:Closed-closed range.[4]Template:Efn | ≥8 | %cTemplate:Efn |
Template:Bracket[5] | Template:N/a |
| <syntaxhighlight lang="text" class="" style="" inline="1">unsigned char</syntaxhighlight> | Of the same size as <syntaxhighlight lang="text" class="" style="" inline="1">char</syntaxhighlight>, but guaranteed to be unsigned. Contains at least the Template:Closed-closed range.[6] | ≥8 | %cTemplate:Efn |
Template:Bracket | Template:N/a |
| Template:Plainlist | Short signed integer type. Capable of containing at least the Template:Closed-closed range.[4]Template:Efn | ≥16 | %hi or %hd |
Template:Bracket | Template:N/a |
| Template:Plainlist | Short unsigned integer type. Contains at least the Template:Closed-closed range.[4] | ≥16 | %hu |
Template:Bracket | Template:N/a |
| Template:Plainlist | Basic signed integer type. Capable of containing at least the Template:Closed-closed range.[4]Template:Efn | ≥16 | %i or %d |
Template:Bracket | Template:CNone |
| Template:Plainlist | Basic unsigned integer type. Contains at least the Template:Closed-closed range.[4] | ≥16 | %u |
Template:Bracket | Template:Mono or Template:Mono[7] |
| Template:Plainlist | Long signed integer type. Capable of containing at least the Template:Closed-closed range.[4]Template:Efn | ≥32 | %li or %ld |
Template:Bracket | Template:Mono or Template:Mono[7] |
| Template:Plainlist | Long unsigned integer type. Capable of containing at least the Template:Closed-closed range.[4] | ≥32 | %lu |
Template:Bracket | both Template:Mono or Template:Mono and Template:Mono or Template:Mono[7] |
| Template:Plainlist | Long long signed integer type. Capable of containing at least the Template:Closed-closed range.[4]Template:Efn Specified since the C99 version of the standard. | ≥64 | %lli or %lld |
Template:Bracket | Template:Mono or Template:Mono[7] |
| Template:Plainlist | Long long unsigned integer type. Contains at least the Template:Closed-closed range.[4] Specified since the C99 version of the standard. | ≥64 | %llu |
Template:Bracket | both Template:Mono or Template:Mono and Template:Mono or Template:Mono[7] |
| <syntaxhighlight lang="text" class="" style="" inline="1">float</syntaxhighlight> | Real floating-point type, usually referred to as a single-precision floating-point type. Actual properties unspecified (except minimum limits); however, on most systems, this is the IEEE 754 single-precision binary floating-point format (32 bits). This format is required by the optional Annex F "IEC 60559 floating-point arithmetic". | Converting from text:Template:EfnTemplate:Ubl | Template:Mono or Template:Mono | ||
| <syntaxhighlight lang="text" class="" style="" inline="1">double</syntaxhighlight> | Real floating-point type, usually referred to as a double-precision floating-point type. Actual properties unspecified (except minimum limits); however, on most systems, this is the IEEE 754 double-precision binary floating-point format (64 bits). This format is required by the optional Annex F "IEC 60559 floating-point arithmetic". | Template:Ubl | none | ||
| <syntaxhighlight lang="text" class="" style="" inline="1">long double</syntaxhighlight> | Real floating-point type, usually mapped to an extended precision floating-point number format. Actual properties unspecified. It can be either x86 extended-precision floating-point format (80 bits, but typically 96 bits or 128 bits in memory with padding bytes), the non-IEEE "double-double" (128 bits), IEEE 754 quadruple-precision floating-point format (128 bits), or the same as double. See the article on long double for details. | %Lf %LF%Lg %LG%Le %LE%La %LATemplate:Efn |
Template:Mono or Template:Mono |
The actual size of the integer types varies by implementation. The standard requires only size relations between the data types and minimum sizes for each data type:
The relation requirements are that the <syntaxhighlight lang="text" class="" style="" inline="1">long long</syntaxhighlight> is not smaller than <syntaxhighlight lang="text" class="" style="" inline="1">long</syntaxhighlight>, which is not smaller than <syntaxhighlight lang="text" class="" style="" inline="1">int</syntaxhighlight>, which is not smaller than <syntaxhighlight lang="text" class="" style="" inline="1">short</syntaxhighlight>. As <syntaxhighlight lang="text" class="" style="" inline="1">char</syntaxhighlight>'s size is always the minimum supported data type, no other data types (except bit-fields) can be smaller.
The minimum size for <syntaxhighlight lang="text" class="" style="" inline="1">char</syntaxhighlight> is 8 bits, the minimum size for <syntaxhighlight lang="text" class="" style="" inline="1">short</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">int</syntaxhighlight> is 16 bits, for <syntaxhighlight lang="text" class="" style="" inline="1">long</syntaxhighlight> it is 32 bits and <syntaxhighlight lang="text" class="" style="" inline="1">long long</syntaxhighlight> must contain at least 64 bits.
The type <syntaxhighlight lang="text" class="" style="" inline="1">int</syntaxhighlight> should be the integer type that the target processor is most efficiently working with. This allows great flexibility: for example, all types can be 64-bit. However, several different integer width schemes (data models) are popular. Because the data model defines how different programs communicate, a uniform data model is used within a given operating system application interface.[8]
In practice, <syntaxhighlight lang="text" class="" style="" inline="1">char</syntaxhighlight> is usually 8 bits in size and <syntaxhighlight lang="text" class="" style="" inline="1">short</syntaxhighlight> is usually 16 bits in size (as are their unsigned counterparts). This holds true for platforms as diverse as 1990s SunOS 4 Unix, Microsoft MS-DOS, modern Linux, and Microchip MCC18 for embedded 8-bit PIC microcontrollers. POSIX requires <syntaxhighlight lang="text" class="" style="" inline="1">char</syntaxhighlight> to be exactly 8 bits in size.[9][10]
Various rules in the C standard make <syntaxhighlight lang="text" class="" style="" inline="1">unsigned char</syntaxhighlight> the basic type used for arrays suitable to store arbitrary non-bit-field objects: its lack of padding bits and trap representations, the definition of object representation,[6] and the possibility of aliasing.[11]
The actual size and behavior of floating-point types also vary by implementation. The only requirement is that <syntaxhighlight lang="text" class="" style="" inline="1">long double</syntaxhighlight> is not smaller than <syntaxhighlight lang="text" class="" style="" inline="1">double</syntaxhighlight>, which is not smaller than <syntaxhighlight lang="text" class="" style="" inline="1">float</syntaxhighlight>. Usually, the 32-bit and 64-bit IEEE 754 binary floating-point formats are used for <syntaxhighlight lang="text" class="" style="" inline="1">float</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">double</syntaxhighlight> respectively.
The C99 standard includes new real floating-point types <syntaxhighlight lang="text" class="" style="" inline="1">float_t</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">double_t</syntaxhighlight>, defined in <math.h>. They correspond to the types used for the intermediate results of floating-point expressions when <syntaxhighlight lang="text" class="" style="" inline="1">FLT_EVAL_METHOD</syntaxhighlight> is 0, 1, or 2. These types may be wider than <syntaxhighlight lang="text" class="" style="" inline="1">long double</syntaxhighlight>.
C99 also added complex types: <syntaxhighlight lang="text" class="" style="" inline="1">float _Complex</syntaxhighlight>, <syntaxhighlight lang="text" class="" style="" inline="1">double _Complex</syntaxhighlight>, <syntaxhighlight lang="text" class="" style="" inline="1">long double _Complex</syntaxhighlight>. C11 added imaginary types (which were described in an informative annex of C99): <syntaxhighlight lang="text" class="" style="" inline="1">float _Imaginary</syntaxhighlight>, <syntaxhighlight lang="text" class="" style="" inline="1">double _Imaginary</syntaxhighlight>, <syntaxhighlight lang="text" class="" style="" inline="1">long double _Imaginary</syntaxhighlight>. Including the header <complex.h> allows all these types to be accessed with using <syntaxhighlight lang="text" class="" style="" inline="1">complex</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">imaginary</syntaxhighlight> respectively.
Boolean type
C99 added a Boolean data type <syntaxhighlight lang="text" class="" style="" inline="1">_Bool</syntaxhighlight>. Additionally, the <stdbool.h> header defines <syntaxhighlight lang="text" class="" style="" inline="1">bool</syntaxhighlight> as a convenient alias for this type, and also provides macros for true and false. <syntaxhighlight lang="text" class="" style="" inline="1">_Bool</syntaxhighlight> functions similarly to a normal integer type, with one exception: any conversion to a <syntaxhighlight lang="text" class="" style="" inline="1">_Bool</syntaxhighlight> gives 0 (false) if the value equals 0; otherwise, it gives 1 (true). This behavior exists to avoid integer overflows in implicit narrowing conversions. For example, in the following code:
<syntaxhighlight lang=C> unsigned char b = 256;
if (b) { // do something } </syntaxhighlight>
Variable b evaluates to false if <syntaxhighlight lang="text" class="" style="" inline="1">unsigned char</syntaxhighlight> has a size of 8 bits. This is because the value 256 does not fit in the data type, which results in the lower 8 bits of it being used, resulting in a zero value. However, changing the type causes the previous code to behave normally:
<syntaxhighlight lang=C> _Bool b = 256;
if (b) { // do something } </syntaxhighlight>
The type <syntaxhighlight lang="text" class="" style="" inline="1">_Bool</syntaxhighlight> also ensures true values always compare equal to each other:
<syntaxhighlight lang=C> _Bool a = 1; _Bool b = 2;
if (a == b) { // this code will run } </syntaxhighlight>
In C23, <syntaxhighlight lang="text" class="" style="" inline="1">bool</syntaxhighlight> (and its values true and false) became a core functionality of the language (making the contents of <stdbool.h> obsolescent[12][13]), allowing for the following examples of code:
<syntaxhighlight lang=C> bool b = true;
if (b) { // this code will run } </syntaxhighlight>
Bit-precise integer types
Since C23, the language allows the programmer to define integers that have a width of an arbitrary number of bits. Those types are specified as <syntaxhighlight lang="c" class="" style="" inline="1">_BitInt(N)</syntaxhighlight>, where N is an integer constant expression that denotes the number of bits, including the sign bit for signed types, represented in two's complement. The maximum value of N is provided by BITINT_MAXWIDTH and is at least ULLONG_WIDTH. Therefore, the type <syntaxhighlight lang="c" class="" style="" inline="1">_BitInt(2)</syntaxhighlight> (or <syntaxhighlight lang="c" class="" style="" inline="1">signed _BitInt(2)</syntaxhighlight>) takes values from −2 to 1 while <syntaxhighlight lang="c" class="" style="" inline="1">unsigned _BitInt(2)</syntaxhighlight> takes values from 0 to 3. The type <syntaxhighlight lang="c" class="" style="" inline="1">unsigned _BitInt(1)</syntaxhighlight> also exists, being either 0 or 1 and has no equivalent signed type.[14] A proposal for C2Y proposes to lift this restriction and allow <syntaxhighlight lang="c" class="" style="" inline="1">signed _BitInt(1)</syntaxhighlight> which then has the possible values 0 and -1, removing the special case for <syntaxhighlight lang="c" class="" style="" inline="1">unsigned _BitInt(1)</syntaxhighlight>.[15]
Size and pointer difference types
The C language specification includes the Template:Monos <syntaxhighlight lang="text" class="" style="" inline="1">size_t</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">ptrdiff_t</syntaxhighlight> to represent memory-related quantities. Their size is defined according to the target processor's arithmetic capabilities, not the memory capabilities, such as available address space. Both of these types are defined in the <stddef.h> header.
<syntaxhighlight lang="text" class="" style="" inline="1">size_t</syntaxhighlight> is an unsigned integer type used to represent the size of any object (including arrays) in the particular implementation. The operator Template:Mono yields a value of the type <syntaxhighlight lang="text" class="" style="" inline="1">size_t</syntaxhighlight>.[16] The maximum size of <syntaxhighlight lang="text" class="" style="" inline="1">size_t</syntaxhighlight> is provided via SIZE_MAX, a macro constant which is defined in the <stdint.h> header. <syntaxhighlight lang="text" class="" style="" inline="1">size_t</syntaxhighlight> is guaranteed to be at least 16 bits wide. Additionally, POSIX includes <syntaxhighlight lang="text" class="" style="" inline="1">ssize_t</syntaxhighlight>, which is a signed integer type of the same width as <syntaxhighlight lang="text" class="" style="" inline="1">size_t</syntaxhighlight>.
<syntaxhighlight lang="text" class="" style="" inline="1">ptrdiff_t</syntaxhighlight> is a signed integer type used to represent the difference between pointers. It is guaranteed to be valid only against pointers of the same type; subtraction of pointers consisting of different types is implementation-defined.
Interface to the properties of the basic types
Information about the actual properties, such as size, of the basic arithmetic types, is provided via macro constants in two headers: <limits.h> header defines macros for integer types and <float.h> header defines macros for floating-point types. The actual values depend on the implementation.
Properties of integer types
CHAR_BIT– size of the char type in bits, commonly referred to as the size of a byte (at least 8 bits)SCHAR_MIN,SHRT_MIN,INT_MIN,LONG_MIN,LLONG_MIN(C99) – minimum possible value of signed integer types: signed char, signed short, signed int, signed long, signed long longSCHAR_MAX,SHRT_MAX,INT_MAX,LONG_MAX,LLONG_MAX(C99) – maximum possible value of signed integer types: signed char, signed short, signed int, signed long, signed long longUCHAR_MAX,USHRT_MAX,UINT_MAX,ULONG_MAX,ULLONG_MAX(C99) – maximum possible value of unsigned integer types: unsigned char, unsigned short, unsigned int, unsigned long, unsigned long longCHAR_MIN– minimum possible value of charCHAR_MAX– maximum possible value of charMB_LEN_MAX– maximum number of bytes in a multibyte characterBOOL_WIDTH(C23) - bit width of_Bool, always 1CHAR_WIDTH(C23) - bit width ofchar;CHAR_WIDTH,UCHAR_WIDTHandSCHAR_WIDTHare equal toCHAR_BITby definitionSCHAR_WIDTH,SHRT_WIDTH,INT_WIDTH,LONG_WIDTH,LLONG_WIDTH(C23) - bit width ofsigned char,short,int,long, andlong longrespectivelyUCHAR_WIDTH,USHRT_WIDTH,UINT_WIDTH,ULONG_WIDTH,ULLONG_WIDTH(C23) - bit width ofunsigned char,unsigned short,unsigned int,unsigned long, andunsigned long longrespectively
Properties of floating-point types
FLT_MIN,DBL_MIN,LDBL_MIN– minimum normalized positive value of float, double, long double respectivelyFLT_TRUE_MIN,DBL_TRUE_MIN,LDBL_TRUE_MIN(C11) – minimum positive value of float, double, long double respectivelyFLT_MAX,DBL_MAX,LDBL_MAX– maximum finite value of float, double, long double, respectivelyFLT_ROUNDS– rounding mode for floating-point operationsFLT_EVAL_METHOD(C99) – evaluation method of expressions involving different floating-point typesFLT_RADIX– radix of the exponent in the floating-point typesFLT_DIG,DBL_DIG,LDBL_DIG– number of decimal digits that can be represented without losing precision by float, double, long double, respectivelyFLT_EPSILON,DBL_EPSILON,LDBL_EPSILON– difference between 1.0 and the next representable value of float, double, long double, respectivelyFLT_MANT_DIG,DBL_MANT_DIG,LDBL_MANT_DIG– number ofFLT_RADIX-base digits in the floating-point significand for types float, double, long double, respectivelyFLT_MIN_EXP,DBL_MIN_EXP,LDBL_MIN_EXP– minimum negative integer such thatFLT_RADIXraised to a power one less than that number is a normalized float, double, long double, respectivelyFLT_MIN_10_EXP,DBL_MIN_10_EXP,LDBL_MIN_10_EXP– minimum negative integer such that 10 raised to that power is a normalized float, double, long double, respectivelyFLT_MAX_EXP,DBL_MAX_EXP,LDBL_MAX_EXP– maximum positive integer such thatFLT_RADIXraised to a power one less than that number is a normalized float, double, long double, respectivelyFLT_MAX_10_EXP,DBL_MAX_10_EXP,LDBL_MAX_10_EXP– maximum positive integer such that 10 raised to that power is a normalized float, double, long double, respectivelyDECIMAL_DIG(C99) – minimum number of decimal digits such that any number of the widest supported floating-point type can be represented in decimal with a precision ofDECIMAL_DIGdigits and read back in the original floating-point type without changing its value.DECIMAL_DIGis at least 10.
Fixed-width integer types
The C99 standard includes definitions of several new integer types to enhance the portability of programs.[2] The already available basic integer types were deemed insufficient, because their actual sizes are implementation defined and may vary across different systems. The new types are especially useful in embedded environments where hardware usually supports only several types and that support varies between different environments. All new types are defined in <inttypes.h> header and also are available at <stdint.h> header. The types can be grouped into the following categories:
- Exact-width integer types that are guaranteed to have the same number n of bits across all implementations. Included only if it is available in the implementation.
- Least-width integer types that are guaranteed to be the smallest type available in the implementation, that has at least specified number n of bits. Guaranteed to be specified for at least N=8,16,32,64.
- Fastest integer types that are guaranteed to be the fastest integer type available in the implementation, that has at least specified number n of bits. Guaranteed to be specified for at least N=8,16,32,64.
- Pointer integer types that are guaranteed to be able to hold a pointer. Included only if it is available in the implementation.
- Maximum-width integer types that are guaranteed to be the largest integer type in the implementation.
The following table summarizes the types and the interface to acquire the implementation details (n refers to the number of bits):
| Type category | Signed types | Unsigned types | ||||
|---|---|---|---|---|---|---|
| Type | Minimum value | Maximum value | Type | Minimum value | Maximum value | |
| Exact width | intn_t |
INTn_MIN |
INTn_MAX
|
uintn_t |
0 | UINTn_MAX
|
| Least width | int_leastn_t |
INT_LEASTn_MIN |
INT_LEASTn_MAX
|
uint_leastn_t |
0 | UINT_LEASTn_MAX
|
| Fastest | int_fastn_t |
INT_FASTn_MIN |
INT_FASTn_MAX
|
uint_fastn_t |
0 | UINT_FASTn_MAX
|
| Pointer | intptr_t |
INTPTR_MIN |
INTPTR_MAX
|
uintptr_t |
0 | UINTPTR_MAX
|
| Maximum width | intmax_t |
INTMAX_MIN |
INTMAX_MAX
|
uintmax_t |
0 | UINTMAX_MAX
|
Printf and scanf format specifiers
{{#invoke:Labelled list hatnote|labelledList|Main article|Main articles|Main page|Main pages}}
The <inttypes.h> header provides features that enhance the functionality of the types defined in the <stdint.h> header. It defines macros for printf format string and scanf format string specifiers corresponding to the types defined in <stdint.h> and several functions for working with the intmax_t and uintmax_t types. This header was added in C99.
Template:Mono format string
The macros are in the format PRI{fmt}{type}. Here {fmt} defines the output formatting and is one of d (decimal), x (hexadecimal), o (octal), u (unsigned) and i (integer). {type} defines the type of the argument and is one of n, FASTn, LEASTn, PTR, MAX, where n corresponds to the number of bits in the argument.
Template:Mono format string
The macros are in the format SCN{fmt}{type}. Here {fmt} defines the output formatting and is one of d (decimal), x (hexadecimal), o (octal), u (unsigned) and i (integer). {type} defines the type of the argument and is one of n, FASTn, LEASTn, PTR, MAX, where n corresponds to the number of bits in the argument.
Functions
Additional floating-point types
Similarly to the fixed-width integer types, ISO/IEC TS 18661 specifies floating-point types for IEEE 754 interchange and extended formats in binary and decimal:
_FloatNfor binary interchange formats;_DecimalNfor decimal interchange formats;_FloatNxfor binary extended formats;_DecimalNxfor decimal extended formats.
Pointers
{{#invoke:Labelled list hatnote|labelledList|See also|ifexists=true}}
Every data type T has a corresponding type pointer-to-T. A pointer is a data type that contains the address of a storage location of a variable of a particular type. They are declared with the asterisk (*) type declarator following the basic storage type and preceding the variable name. Whitespace before or after the asterisk is optional.
<syntaxhighlight lang=C>
char *p;
long *q;
int *r;
</syntaxhighlight>
Pointers may also be declared for pointer data types, thus creating multiple indirect pointers, such as <syntaxhighlight lang="text" class="" style="" inline="1">char **</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">int ***</syntaxhighlight>, including pointers to array types. The latter are less common than an array of pointers, and their syntax may be confusing: <syntaxhighlight lang=C> char *pc[10]; // array of 10 elements of 'pointer to char' char (*pa)[10]; // pointer to a 10-element array of char </syntaxhighlight>
The element pc requires ten blocks of memory of the size of pointer-to-char (usually 40 or 80 bytes on common platforms), but element pa is only one pointer (size 4 or 8 bytes), and the data it refers to is an array of ten bytes (<syntaxhighlight lang="c" class="" style="" inline="1">sizeof *pa == 10</syntaxhighlight>).
C also has a "pointer-to-void", void *.[17] The name "pointer-to-void" does not imply it points to void memory (as void is an incomplete type with no size), but rather that it points to something of unspecified type. It must be converted to another pointer type before it can be dereferenced. A void * may not point to a function. A call to malloc returns void *, and free takes a void *.
C uses the concept of a null pointer to denote a pointer that does not refer to any valid data. The macro NULL is often used in place of a null pointer, relying on implicit type conversion when possible. However, this usage can be problematic and may be a source of programming errors. In particular, the expansion of NULL may have a pointer type or an integer type, depending on the implementation. C23 introduced the predefined constant nullptr and its type nullptr_t (which has the single value nullptr) to express a null pointer constant. nullptr is unambiguously a pointer, and may convert to any object or function pointer, and allows a specific nullptr_t case in _Generic.[18] The size and alignment of this type is the same as for a pointer to character type (or void *), but other pointer types may still have a different size and alignment; thus not all null pointers are replaceable with nullptr.[19]
Arrays
{{#invoke:Labelled list hatnote|labelledList|See also|ifexists=true}}
For every type T, except void and function types, there exist the types "array of N elements of type T". An array is a collection of values, all of the same type, stored contiguously in memory. An array of size N is indexed by integers from 0 up to and including N − 1. Here is a brief example:
<syntaxhighlight lang=C> int a[10]; // array of 10 elements, each of type int </syntaxhighlight>
Arrays can be initialized with a compound initializer, but not assigned. Arrays are passed to functions by passing a pointer to the first element. Multidimensional arrays are defined as "array of array ...", and all except the outermost dimension must have compile-time constant size:
<syntaxhighlight lang=C> int aa[10][8]; // array of 10 elements, each of type 'array of 8 int elements' </syntaxhighlight>
In C, a string is often stored as an array of char (char[]), but this is distinct from a pointer-to-char (char *). char[] cannot be reassigned, and lives where it is defined, while char * is reassignable, but cannot be modified.
<syntaxhighlight lang="c">
char s[] = "Hello, world!";
char *p = s; // s decays to &s[0], p points to the first character
</syntaxhighlight>
Even if a function takes T[] as a parameter, it decays into a T * which points to its first element.
<syntaxhighlight lang="c">
void f(int a[]);
// this is the same as: void f(int *a); </syntaxhighlight>
Indexing an array is defined in terms of pointer arithmetic, that is, a[i] is equivalent to *(a + i).[20]
Enums
{{#invoke:Labelled list hatnote|labelledList|Main article|Main articles|Main page|Main pages}}
In C, an enum is an integer type whose values are restricted to a set of named constants.[21] Enums cannot be forward-declared. Enums may also directly be assigned values, and are commonly used with switch to enumerate multiple cases.
<syntaxhighlight lang="c">
- include <stddef.h>
enum Status {
OK = 200, NOT_FOUND = 404, SERVER_ERROR = 500
};
const char *get_status_string(enum Status status) {
switch (status) {
case OK:
return "Success";
case NOT_FOUND:
return "Not found";
case SERVER_ERROR:
return "Server error";
default:
unreachable();
}
}
</syntaxhighlight>
Enum constants are known at compile time, and are often a safer means to define integral constants than macros. An enum's underlying size is usually int, but since C23 an enum's underlying size can be directly specified to be any integral type.
<syntaxhighlight lang="c">
enum Color : char {
RED = 1, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET
}; </syntaxhighlight>
Because enums are not type-safe, they can be assigned a value of another enum. Enums also need not be assigned values necessarily within the range of defined values. <syntaxhighlight lang="c"> enum Color color = YELLOW; // YELLOW = 3 enum Month month = JUNE; // JUNE = 6
color = month; // color is now 6 (INDIGO) month = 999; // there may not be a value of 999 in enum Month, but still allowed </syntaxhighlight>
Structs
{{#invoke:Labelled list hatnote|labelledList|Main article|Main articles|Main page|Main pages}} Structures (structs) aggregate the storage of multiple data items, of potentially differing data types, into one contiguous memory block referenced by a single variable. Members may possibly be padded for memory alignment, and thus it is often recommended to order fields from largest to smallest size for efficient memory usage.
<syntaxhighlight lang=C> struct Student {
char name[50]; unsigned int id; unsigned int semester; float gpa;
};
// Positional initialization - values matches field order struct Student alice = { "Alice", 123, 2, 3.8 }; // Designated initializer (since C99) struct Student bob = {
.name = "Bob", .id = 246, .semester = 1, .gpa = 3.9
}; </syntaxhighlight>
Structs may also use bit fields to allow fields to share the same storage units, but layouts are implementation-defined. <syntaxhighlight lang="c"> struct Properties {
// three fields can be compactly packed in one byte unsigned char visible : 1; // a occupies 1 bit unsigned char color : 3; // b occupies 3 bits unsigned char size : 4; // c occupies 4 bits
}; </syntaxhighlight>
The memory layout of a struct is a language implementation issue for each platform, with a few restrictions. The memory address of the first member must be the same as the address of structure itself. Structs may be initialized or assigned to using compound literals. A function may directly return a struct, although this is often not efficient at run-time. Since C99, a struct may also end with a flexible array member.
Functions may take a struct as a parameter by value, but this is expensive as it copies the entire struct. Meanwhile, passing it by pointer is often preferable as the size of a pointer is known (typically 4 or 8 bytes). <syntaxhighlight lang="c">
- include <stdio.h>
// passing by value void print_student(struct Student s) {
printf("Name: %s, ID: %d, in semester %d, with GPA: %.2f\n", s.name, s.id, s.semester, s.gpa);
}
// passing by pointer void print_student(struct Student *s) {
printf("Name: %s, ID: %d, in semester %d, with GPA: %.2f\n", s->name, s->id, s->semester, s->gpa);
} </syntaxhighlight>
Structs can be composed of other structs: <syntaxhighlight lang="c"> struct Date {
int year; int month; int day;
};
struct Birthday {
char name[50]; struct Date dob;
}; </syntaxhighlight>
A struct containing a pointer to a struct of its own type is commonly used to build linked data structures: <syntaxhighlight lang=C> struct LinkedList {
void *item; // stores the current item struct LinkedList *next; // stores the next list, or NULL if nothing next
}; </syntaxhighlight>
Unions
{{#invoke:Labelled list hatnote|labelledList|See also|ifexists=true}}
A union type is a special construct that permits access to the same memory block by using a choice of differing type descriptions. <syntaxhighlight lang="c"> // holds either an integer or floating point value union Number {
int i; float f;
} d;
d.i = 10; // d now holds 10 d.f = 3.14f; // d now holds 3.14, overwriting 10 </syntaxhighlight>
In the following example, a union of data types may be declared to permit reading the same data either as an integer, a float, or any other user declared type:
<syntaxhighlight lang=C>
union {
int i;
float f;
struct {
unsigned int u;
double d;
} s;
} u;
</syntaxhighlight>
The total size of u is the size of u.s – which happens to be the sum of the sizes of u.s.u and u.s.d – since s is larger than both i and f. When assigning something to u.i, some parts of u.f may be preserved if u.i is smaller than u.f.
Reading from a union member is not the same as casting since the value of the member is not converted, but merely read.
Function pointers
Function pointers allow referencing functions with a particular signature. For example, to store the address of the standard function abs in the variable my_int_f:
<syntaxhighlight lang=C> int (*my_int_f)(int) = &abs; // the & operator can be omitted, but makes clear that the "address of" abs is used here </syntaxhighlight>
Function pointers are invoked by name just like normal function calls. <syntaxhighlight lang="c">
- include <stdio.h>
- include <stdlib.h>
int (*my_abs)(int) = &abs; int x = -42; int abs_of_x = my_abs(x); printf("abs(%d) = %d\n", x, abs_of_x); </syntaxhighlight>
Type qualifiers
{{#invoke:Labelled list hatnote|labelledList|Main article|Main articles|Main page|Main pages}}
The aforementioned types can be characterized further by type qualifiers, yielding a qualified type. Template:As of and C11, there are four type qualifiers in standard C:
const(C89)volatile(C89)restrict(C99)_Atomic(C11)Template:Snd the latter has a private name to avoid clashing with user names,[22] but the more ordinary nameatomiccan be used if the<stdatomic.h>header is included.
Of these, const is by far the best-known and most used{{safesubst:#invoke:Unsubst||date=__DATE__ |$B=
Template:Fix{{#invoke:Check for unknown parameters|check|unknown=Template:Main other|preview=Page using Template:Citation needed with unknown parameter "_VALUE_"|ignoreblank=y| date | name | reason }}}}, appearing in the C standard library and encountered in any significant use of the C language, which must satisfy const-correctness. The other qualifiers are primarily used for low-level programming: volatile is intended suppress compiler optimisations on a variable by suggesting it may change at any time, restrict indicates that the object pointed to by a pointer is accessed only by that pointer, and _Atomic indicates that the object is "atomic", i.e. reads and writes are indivisible.
See also
References
Template:C programming language Template:Data types
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ 2.0 2.1 Template:Cite book
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ 4.00 4.01 4.02 4.03 4.04 4.05 4.06 4.07 4.08 4.09 Template:Cite book
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ 6.0 6.1 Template:Cite book
- ↑ 7.0 7.1 7.2 7.3 7.4 Cite error: Invalid
<ref>tag; no text was provided for refs namedc99intconst - ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ Template:Cite book
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ Template:Cite book
- ↑ Template:Cite book
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ Template:Cite book
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ Template:Cite book
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ C11:The New C Standard, Thomas Plum