C data types

Short description: Data types supported by the C programming language

C standard library

General topics

* Data types
* Character classification
* Strings
* Mathematics
* File input/output
* Date/time
* Localization
* Memory allocation
* Process control
* Signals
* Alternative tokens

Miscellaneous headers

* <assert.h>
* <errno.h>
* <setjmp.h>
* <stdarg.h>

* v
* t
* e

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]

## Contents

* 1 Primary types
* 1.1 Main types
* 1.2 Boolean type
* 1.3 Bit-precise integer types
* 1.4 Size and pointer difference types
* 1.5 Interface to the properties of the basic types
* 1.5.1 Properties of integer types
* 1.5.2 Properties of floating-point types
* 2 Fixed-width integer types
* 2.1 Printf and scanf format specifiers
* 2.1.1 printf format string
* 2.1.2 scanf format string
* 2.1.3 Functions
* 3 Additional floating-point types
* 4 Pointers
* 5 Arrays
* 6 Enums
* 7 Structs
* 8 Unions
* 9 Function pointers
* 10 Type qualifiers
* 11 See also
* 12 References

## Primary types

### Main types

The C language provides the four basic arithmetic type specifiers `char`, `int`, `float` and `double` (as well as the Boolean type `bool`), and the modifiers `signed`, `unsigned`, `short`, and `long`. The following table lists the permissible combinations in specifying a large set of storage size-specific declarations.

Type  | Explanation  | Size (bits)[lower-alpha 1] | Format specifier  | Range  | Suffix for decimal constants

|
|
|
|
|

`bool` | Boolean type, added in C23. (Previously `_Bool` added in C99,[3] but its size and its range were not specified.) | 1 (exact) | `%d` | [false, true] | N/A
`char` | 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 `CHAR_BIT` bits.[4] | ≥8 | `%c` | [CHAR_MIN, CHAR_MAX] | N/A
`signed char` | Of the same size as `char`, but guaranteed to be signed. Capable of containing at least the [−127, +127] range.[4][lower-alpha 2] | ≥8 | `%c`[lower-alpha 3] | [SCHAR_MIN, SCHAR_MAX][7] | N/A
`unsigned char` | Of the same size as `char`, but guaranteed to be unsigned. Contains at least the [0, 255] range.[8] | ≥8 | `%c`[lower-alpha 4] | [0, UCHAR_MAX] | N/A

* `short`
* `short int`
* `signed short`
* `signed short int`

| Short signed integer type. Capable of containing at least the [−32767, +32767] range.[4][lower-alpha 2] | ≥16 | `%hi` or `%hd` | [SHRT_MIN, SHRT_MAX] | N/A

* `unsigned short`
* `unsigned short int`

| Short unsigned integer type. Contains at least the [0, 65535] range.[4] | ≥16 | `%hu` | [0, USHRT_MAX] | N/A

* `int`
* `signed`
* `signed int`

| Basic signed integer type. Capable of containing at least the [−32767, +32767] range.[4][lower-alpha 2] | ≥16 | `%i` or `%d` | [INT_MIN, INT_MAX] | none[9]

* `unsigned`
* `unsigned int`

| Basic unsigned integer type. Contains at least the [0, 65535] range.[4] | ≥16 | `%u` | [0, UINT_MAX] | u or U[9]

* `long`
* `long int`
* `signed long`
* `signed long int`

| Long signed integer type. Capable of containing at least the [−2147483647, +2147483647] range.[4][lower-alpha 2] | ≥32 | `%li` or `%ld` | [LONG_MIN, LONG_MAX] | l or L[9]

* `unsigned long`
* `unsigned long int`

| Long unsigned integer type. Capable of containing at least the [0, 4294967295] range.[4] | ≥32 | `%lu` | [0, ULONG_MAX] | both u or U and l or L[9]

* `long long`
* `long long int`
* `signed long long`
* `signed long long int`

| Long long signed integer type. Capable of containing at least the [−9223372036854775807, +9223372036854775807] range.[4][lower-alpha 2] Specified since the C99 version of the standard. | ≥64 | `%lli` or `%lld` | [LLONG_MIN, LLONG_MAX] | ll or LL[9]

* `unsigned long long`
* `unsigned long long int`

| Long long unsigned integer type. Contains at least the [0, 18446744073709551615] range.[4] Specified since the C99 version of the standard. | ≥64 | `%llu` | [0, ULLONG_MAX] | both u or U and ll or LL[9]
`float` | 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:[lower-alpha 5]

* `%f` `%F`
* `%g` `%G`
* `%e` `%E`
* `%a` `%A`

|  | f or F
`double` | 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".  |  |

* `%lf` `%lF`
* `%lg` `%lG`
* `%le` `%lE`
* `%la` `%lA`[lower-alpha 6]

|  | none
`long double` | 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` `%LA`[lower-alpha 6] |  | l or L

1. ↑ The standard term for the size of an integer type in bits is width. The width does not include padding bits.
2. ↑ 2.0 2.1 2.2 2.3 2.4 The minimal ranges [−(2n−1−1), 2n−1−1] (e.g. [−127,127]) come from the various integer representations allowed by the standard (ones' complement, sign-magnitude, two's complement).[5] However, most platforms use two's complement, implying a range of the form [−2m−1, 2m−1−1] with m ≥ n for these implementations, e.g. [−128,127] (`SCHAR_MIN == −128` and `SCHAR_MAX == 127`) for an 8-bit signed char. Since C23, the only representation allowed is two's complement, therefore the values range from at least [−2n−1, 2n−1−1].[6]
3. ↑ or `%hhi` for numerical output
4. ↑ or `%hhu` for numerical output
5. ↑ These format strings also exist for formatting to text, but operate on a double.
6. ↑ 6.0 6.1 Uppercase differs from lowercase in the output. Uppercase specifiers produce values in the uppercase, and lowercase in lower (%A, %E, %F, %G produce such values as INF, NAN and E (exponent) in uppercase)

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 `long long` is not smaller than `long`, which is not smaller than `int`, which is not smaller than `short`. As `char`'s size is always the minimum supported data type, no other data types (except bit-fields) can be smaller.

The minimum size for `char` is 8 bits, the minimum size for `short` and `int` is 16 bits, for `long` it is 32 bits and `long long` must contain at least 64 bits.

The type `int` 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.[10]

In practice, `char` is usually 8 bits in size and `short` 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 `char` to be exactly 8 bits in size.[11][12]

Various rules in the C standard make `unsigned char` 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,[8] and the possibility of aliasing.[13]

The actual size and behavior of floating-point types also vary by implementation. The only requirement is that `long double` is not smaller than `double`, which is not smaller than `float`. Usually, the 32-bit and 64-bit IEEE 754 binary floating-point formats are used for `float` and `double` respectively.

The C99 standard includes new real floating-point types `float_t` and `double_t`, defined in `<math.h>`. They correspond to the types used for the intermediate results of floating-point expressions when `FLT_EVAL_METHOD` is 0, 1, or 2. These types may be wider than `long double`.

C99 also added complex types: `float _Complex`, `double _Complex`, `long double _Complex`. C11 added imaginary types (which were described in an informative annex of C99): `float _Imaginary`, `double _Imaginary`, `long double _Imaginary`. Including the header `<complex.h>` allows all these types to be accessed with using `complex` and `imaginary` respectively.

### Boolean type

C99 added a Boolean data type `_Bool`. Additionally, the `<stdbool.h>` header defines `bool` as a convenient alias for this type, and also provides macros for `true` and `false`. `_Bool` functions similarly to a normal integer type, with one exception: any conversion to a `_Bool` 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:

unsigned char b = 256;

if (b) {
// do something

Variable `b` evaluates to false if `unsigned char` 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:

_Bool b = 256;

if (b) {
// do something

The type `_Bool` also ensures true values always compare equal to each other:

_Bool a = 1;
_Bool b = 2;

if (a == b) {
// this code will run

In C23, `bool` (and its values `true` and `false`) became a core functionality of the language (making the contents of `<stdbool.h>` obsolescent[14][15]), allowing for the following examples of code:

bool b = true;

if (b) {
// this code will run

### 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 `_BitInt(N)`, 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 `_BitInt(2)` (or `signed _BitInt(2)`) takes values from −2 to 1 while `unsigned _BitInt(2)` takes values from 0 to 3. The type `unsigned _BitInt(1)` also exists, being either 0 or 1 and has no equivalent signed type.[16] A proposal for C2Y proposes to lift this restriction and allow `signed _BitInt(1)` which then has the possible values 0 and -1, removing the special case for `unsigned _BitInt(1)`.[17]

### Size and pointer difference types

The C language specification includes the typedefs `size_t` and `ptrdiff_t` 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.

`size_t` is an unsigned integer type used to represent the size of any object (including arrays) in the particular implementation. The operator sizeof yields a value of the type `size_t`. The maximum size of `size_t` is provided via `SIZE_MAX`, a macro constant which is defined in the `<stdint.h>` header. `size_t` is guaranteed to be at least 16 bits wide. Additionally, POSIX includes `ssize_t`, which is a signed integer type of the same width as `size_t`.

`ptrdiff_t` 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 long
* `SCHAR_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 long
* `UCHAR_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 long
* `CHAR_MIN` – minimum possible value of char
* `CHAR_MAX` – maximum possible value of char
* `MB_LEN_MAX` – maximum number of bytes in a multibyte character
* `BOOL_WIDTH` (C23) - bit width of `_Bool`, always 1
* `CHAR_WIDTH` (C23) - bit width of `char`; `CHAR_WIDTH`, `UCHAR_WIDTH` and `SCHAR_WIDTH` are equal to `CHAR_BIT` by definition
* `SCHAR_WIDTH`, `SHRT_WIDTH`, `INT_WIDTH`, `LONG_WIDTH`, `LLONG_WIDTH` (C23) - bit width of `signed char`, `short`, `int`, `long`, and `long long` respectively
* `UCHAR_WIDTH`, `USHRT_WIDTH`, `UINT_WIDTH`, `ULONG_WIDTH`, `ULLONG_WIDTH` (C23) - bit width of `unsigned char`, `unsigned short`, `unsigned int`, `unsigned long`, and `unsigned long long` respectively

#### Properties of floating-point types

* `FLT_MIN`, `DBL_MIN`, `LDBL_MIN` – minimum normalized positive value of float, double, long double respectively
* `FLT_TRUE_MIN`, `DBL_TRUE_MIN`, `LDBL_TRUE_MIN` (C11) – minimum positive value of float, double, long double respectively
* `FLT_MAX`, `DBL_MAX`, `LDBL_MAX` – maximum finite value of float, double, long double, respectively
* `FLT_ROUNDS` – rounding mode for floating-point operations
* `FLT_EVAL_METHOD` (C99) – evaluation method of expressions involving different floating-point types
* `FLT_RADIX` – radix of the exponent in the floating-point types
* `FLT_DIG`, `DBL_DIG`, `LDBL_DIG` – number of decimal digits that can be represented without losing precision by float, double, long double, respectively
* `FLT_EPSILON`, `DBL_EPSILON`, `LDBL_EPSILON` – difference between 1.0 and the next representable value of float, double, long double, respectively
* `FLT_MANT_DIG`, `DBL_MANT_DIG`, `LDBL_MANT_DIG` – number of `FLT_RADIX`-base digits in the floating-point significand for types float, double, long double, respectively
* `FLT_MIN_EXP`, `DBL_MIN_EXP`, `LDBL_MIN_EXP` – minimum negative integer such that `FLT_RADIX` raised to a power one less than that number is a normalized float, double, long double, respectively
* `FLT_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, respectively
* `FLT_MAX_EXP`, `DBL_MAX_EXP`, `LDBL_MAX_EXP` – maximum positive integer such that `FLT_RADIX` raised to a power one less than that number is a normalized float, double, long double, respectively
* `FLT_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, respectively
* `DECIMAL_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 of `DECIMAL_DIG` digits and read back in the original floating-point type without changing its value. `DECIMAL_DIG` is 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

Main articles: printf format string and scanf format string

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.

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

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

* `_FloatN` for binary interchange formats;
* `_DecimalN` for decimal interchange formats;
* `_FloatNx` for binary extended formats;
* `_DecimalNx` for decimal extended formats.

## Pointers

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.

char *p;
long *q;
int *r;

Pointers may also be declared for pointer data types, thus creating multiple indirect pointers, such as `char **` and `int ***`, including pointers to array types. The latter are less common than an array of pointers, and their syntax may be confusing:

char *pc[10]; // array of 10 elements of 'pointer to char'
char (*pa)[10]; // pointer to a 10-element array of char

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 (`sizeof *pa == 10`).

C also has a "pointer-to-`void`", `void *`.[18] 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`.[19] 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`.[20]

## Arrays

See also: Array (data type)

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:

int a[10]; // array of 10 elements, each of type int

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:

int aa[10][8]; // array of 10 elements, each of type 'array of 8 int elements'

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.

char s[] = "Hello, world!";
char *p = s; // s decays to &s[0], p points to the first character

Even if a function takes `T[]` as a parameter, it decays into a `T *` which points to its first element.

void f(int a[]);

// this is the same as:
void f(int *a);

Indexing an array is defined in terms of pointer arithmetic, that is, `a[i]` is equivalent to `*(a + i)`.[21]

## Enums

Main article: Enumerated type

In C, an enum is an integer type whose values are restricted to a set of named constants.[22] Enums cannot be forward-declared. Enums may also directly be assigned values, and are commonly used with `switch` to enumerate multiple cases.

#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();

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.

enum Color : char {
RED = 1,
ORANGE,
YELLOW,
GREEN,
BLUE,
INDIGO,
VIOLET

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.

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

## Structs

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.

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

Structs may also use bit fields to allow fields to share the same storage units, but layouts are implementation-defined.

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

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

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

Structs can be composed of other structs:

struct Date {
int year;
int month;
int day;

struct Birthday {
char name[50];
struct Date dob;

A struct containing a pointer to a struct of its own type is commonly used to build linked data structures:

struct LinkedList {
void *item; // stores the current item
struct LinkedList *next; // stores the next list, or NULL if nothing next

## Unions

A union type is a special construct that permits access to the same memory block by using a choice of differing type descriptions.

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

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:

union {
int i;
float f;
struct {
unsigned int u;
double d;
} s;
} u;

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

int (*my_int_f)(int) = &abs;
// the & operator can be omitted, but makes clear that the "address of" abs is used here

Function pointers are invoked by name just like normal function calls.

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

## Type qualifiers

Main article: Type qualifier

The aforementioned types can be characterized further by type qualifiers, yielding a qualified type. As of 2014[update] and C11, there are four type qualifiers in standard C:

* `const` (C89)
* `volatile` (C89)
* `restrict` (C99)
* `Atomic` (C11) - the latter has a private name to avoid clashing with user names,[23] but the more ordinary name `atomic` can be used if the `<stdatomic.h>` header is included.

Of these, `const` is by far the best-known and most used , 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

| The Wikibook C Programming has a page on the topic of: Variables

|

* C syntax
* Uninitialized variable
* Integer (computer science)
* Offsetof

## References

1. ↑ Barr, Michael (2 December 2007). "Portable Fixed-Width Integers in C". https://barrgroup.com/Embedded-Systems/How-To/C-Fixed-Width-Integers-C99.
2. ↑ 2.0 2.1 ISO/IEC 9899:1999 specification, TC3. p. 255, § 7.18 Integer types <stdint.h>. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf.
3. ↑ "Arithmetic types". https://www.cppreference.com/w/c/language/arithmetic_types.html.
4. ↑ 4.00 4.01 4.02 4.03 4.04 4.05 4.06 4.07 4.08 4.09 ISO/IEC 9899:1999 specification, TC3. p. 22, § 5.2.4.2.1 Sizes of integer types <limits.h>. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf.
5. ↑ Rationale for International Standard—Programming Languages—C Revision 5.10. p. 25, § 5.2.4.2.1 Sizes of integer types <limits.h>. https://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf.
6. ↑ ISO/IEC 9899:2023 specification draft. p. 41, § 6.2.6 Representations of types. https://open-std.org/JTC1/SC22/WG14/www/docs/n3096.pdf.
7. ↑ "C and C++ Integer Limits". 21 July 2023. https://docs.microsoft.com/en-us/cpp/c-language/cpp-integer-limits?view=msvc-170.
8. ↑ 8.0 8.1 ISO/IEC 9899:1999 specification, TC3. p. 37, § 6.2.6.1 Representations of types – General. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf.
9. ↑ 9.0 9.1 9.2 9.3 9.4 9.5 ISO/IEC 9899:1999 specification, TC3. p. 56, § 6.4.4.1 Integer constants. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf.
10. ↑ "64-Bit Programming Models: Why LP64?". The Open Group. http://www.unix.org/version2/whatsnew/lp64_wp.html.
11. ↑ "Width of Type (The GNU C Library)". https://www.gnu.org/software/libc/manual/html_node/Width-of-Type.html.
12. ↑ "<limits.h>". https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html.
13. ↑ ISO/IEC 9899:1999 specification, TC3. p. 67, § 6.5 Expressions. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf.
14. ↑ The IEEE and The Open Group (2024). "<stdbool.h>". IEEE Std 1003.1-2024. https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/stdbool.h.html.
15. ↑ cppreference.com. "Standard library header <stdbool.h>". cppreference.com. https://en.cppreference.com/w/c/header/stdbool.html.
16. ↑ ISO/IEC 9899:2023 specification draft. p. 37, § 6.2.5 Types. https://open-std.org/JTC1/SC22/WG14/www/docs/n3096.pdf.
17. ↑ Integer Sets, v3, WG14 N 3699. p. 6, § 1.2 Bit-precise Integers. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3699.pdf.
18. ↑ ISO/IEC 9899:1999 specification, TC3. p. 47, § 6.3.2.3 Pointers. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf.
19. ↑ cppreference.com. "nullptr_t". cppreference.com. https://en.cppreference.com/w/c/types/nullptr_t.html.
20. ↑ "WR14-N3042: Introduce the nullptr constant". 2022-07-22. https://open-std.org/JTC1/SC22/WG14/www/docs/n3042.htm.
21. ↑ Plauger, P J; Brodie, Jim (1992). ANSI and ISO Standard C Programmer's Reference. Redmond, WA: Microsoft Press. p. 108. ISBN 978-1-55615-359-4. https://archive.org/details/ansiisostandardc00plau/.
22. ↑ cppreference.com. "Enumerations". cppreference.com. https://en.cppreference.com/w/c/language/enum.html.
23. ↑ C11:The New C Standard, Thomas Plum

* v
* t
* e

C programming language

* ANSI C
* C89 and C90
* C99
* C11
* C18
* C2x
* Embedded C
* MISRA C

Features|

* Functions
* Header files
* Libraries
* Operators
* String
* Syntax
* Preprocessor
* Data types

Standard library
functions|

* Char (ctype.h)
* File I/O (stdio.h)
* Math (math.h)
* Dynamic memory (stdlib.h)
* String (string.h)
* Time (time.h)
* Variadic (stdarg.h)
* POSIX

Standard
libraries|

* Bionic
* libhybris
* dietlibc
* EGLIBC
* glibc
* klibc
* Microsoft Run-time Library
* musl
* Newlib
* uClibc
* BSD libc

Compilers|

* Comparison of compilers
* ACK
* Borland Turbo C
* Clang
* GCC
* ICC
* LCC
* PCC
* SDCC
* TCC
* Microsoft Visual Studio / Express / C++
* Watcom C/C++

IDEs|

* Comparison of IDEs
* Anjuta
* Code
* CodeLite
* Eclipse
* Geany
* Microsoft Visual Studio
* NetBeans

Comparison with
other languages|

* Compatibility of C and C++
* Comparison with Embedded C
* Comparison with Pascal
* Comparison of programming languages

Descendant
languages|

* C++
* C#
* D
* Objective-C
* Alef
* Limbo
* Go
* Vala

* Category

* v
* t
* e

Data types

Uninterpreted|

* Bit
* Byte
* Trit
* Tryte
* Word
* Bit array

Numeric|

* Arbitrary-precision or bignum
* Complex
* Decimal
* Fixed point
* Floating point
* Double precision
* Extended precision
* Long double
* Octuple precision
* Quadruple precision
* Single precision
* Reduced precision
* Minifloat
* Half precision
* bfloat16
* Integer
* signedness
* Interval
* Rational

Pointer|

* Address
* physical
* virtual
* Reference

Text|

* Character
* String
* null-terminated

Composite|

* Algebraic data type
* generalized
* Array
* Associative array
* Class
* Dependent
* Equality
* Inductive
* Intersection
* List
* Object
* metaobject
* Option type
* Product
* Record or Struct
* Refinement
* Set
* Union
* tagged

Other|

* Boolean
* Bottom type
* Collection
* Enumerated type
* Exception
* Function type
* Opaque data type
* Recursive data type
* Semaphore
* Stream
* Top type
* Type class
* Unit type
* Void

Related
topics|

* Abstract data type
* Data structure
* Generic
* Kind
* metaclass
* Parametric polymorphism
* Primitive data type
* Protocol
* interface
* Subtyping
* Type constructor
* Type conversion
* Type system
* Type theory

See also platform-dependent and independent units of information

0.00

(0 votes)

Original source: https://en.wikipedia.org/wiki/C data types. Read more

|

Retrieved from "https://handwiki.org/wiki/index.php?title=C_data_types&oldid=4572310"
*[v]: View this template
*[t]: Discuss this template
*[e]: Edit this template