Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

C data types

From Wikipedia, the free encyclopedia
(Redirected fromLimits.h)
Data types supported by the C programming language

C standard library (libc)
General topics
Miscellaneous headers

In theC 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 formemory locations orvariables. Data types also determine the types of operations or methods of processing of data elements.

The C language provides basic arithmetic types, such asinteger andreal number types, and syntax to build array and compound types.Headers for theC standard library, to be used viainclude directives, contain 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

[edit]

Main types

[edit]

The C language provides the four basic arithmetic type specifierschar,int,float anddouble (as well as the boolean typebool), and the modifierssigned,unsigned,short, andlong. The following table lists the permissible combinations in specifying a large set of storage size-specific declarations.

TypeExplanationSize (bits)Format specifierRangeSuffix for decimal constants
boolBoolean type, added inC23.1 (exact)%d[false,true]
charSmallest addressable unit of the machine that can contain basic character set. It is aninteger type. Actual type can be either signed or unsigned. It contains CHAR_BIT bits.[3]≥8%c[CHAR_MIN,CHAR_MAX]
signed charOf the same size aschar, but guaranteed to be signed. Capable of containing at least the[−127, +127] range.[3][a]≥8%c[b][SCHAR_MIN,SCHAR_MAX][6]
unsigned charOf the same size aschar, but guaranteed to be unsigned. Contains at least the[0, 255] range.[7]≥8%c[c][0,UCHAR_MAX]
  • short
  • short int
  • signed short
  • signed short int
Short signed integer type. Capable of containing at least the[−32767,+32767] range.[3][a]≥16%hi or%hd[SHRT_MIN,SHRT_MAX]
  • unsigned short
  • unsigned short int
Short unsigned integer type. Contains at least the[0,65535] range.[3]≥16%hu[0,USHRT_MAX]
  • int
  • signed
  • signed int
Basic signed integer type. Capable of containing at least the[−32767,+32767] range.[3][a]≥16%i or%d[INT_MIN,INT_MAX]none[8]
  • unsigned
  • unsigned int
Basic unsigned integer type. Contains at least the[0,65535] range.[3]≥16%u[0,UINT_MAX]u orU[8]
  • long
  • long int
  • signed long
  • signed long int
Long signed integer type. Capable of containing at least the[−2147483647,+2147483647] range.[3][a]≥32%li or%ld[LONG_MIN,LONG_MAX]l orL[8]
  • unsigned long
  • unsigned long int
Long unsigned integer type. Capable of containing at least the[0,4294967295] range.[3]≥32%lu[0,ULONG_MAX]bothu orU andl orL[8]
  • 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.[3][a] Specified since theC99 version of the standard.≥64%lli or%lld[LLONG_MIN,LLONG_MAX]ll orLL[8]
  • unsigned long long
  • unsigned long long int
Long long unsigned integer type. Contains at least the[0,18446744073709551615] range.[3] Specified since theC99 version of the standard.≥64%llu[0,ULLONG_MAX]bothu orU andll orLL[8]
floatReal 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 theIEEE 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:[d]
  • %f%F
  • %g%G
  • %e%E
  • %a%A
f orF
doubleReal 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 theIEEE 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[e]
none
long doubleReal floating-point type, usually mapped to anextended precision floating-point number format. Actual properties unspecified. It can be eitherx86 extended-precision floating-point format (80 bits, but typically 96 bits or 128 bits in memory withpadding bytes), the non-IEEE "double-double" (128 bits),IEEE 754 quadruple-precision floating-point format (128 bits), or the same as double. Seethe article on long double for details.%Lf%LF
%Lg%LG
%Le%LE
%La%LA[e]
l orL
  1. ^abcdeThe 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).[4] However, most platforms use two's complement, implying a range of the form[−2m−1, 2m−1−1] withmn for these implementations, e.g. [−128,127] (SCHAR_MIN == −128 andSCHAR_MAX == 127) for an 8-bitsigned char. Since C23, the only representation allowed is two's complement, therefore the values range from at least[−2n−1, 2n−1−1].[5]
  2. ^or%hhi for numerical output
  3. ^or%hhu for numerical output
  4. ^These format strings also exist for formatting to text, but operate on a double.
  5. ^abUppercase 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 theinteger 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 thelong long is not smaller thanlong, which is not smaller thanint, which is not smaller thanshort. Aschar's size is always the minimum supported data type, no other data types (exceptbit-fields) can be smaller.

The minimum size forchar is 8 bits, the minimum size forshort andint is 16 bits, forlong it is 32 bits andlong long must contain at least 64 bits.

The typeint 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.[9]

In practice,char is usually 8 bits in size andshort is usually 16 bits in size (as are their unsigned counterparts). This holds true for platforms as diverse as 1990sSunOS 4 Unix, MicrosoftMS-DOS, modernLinux, and Microchip MCC18 for embedded 8-bit PICmicrocontrollers.POSIX requireschar to be exactly 8 bits in size.[10][11]

Various rules in the C standard makeunsigned 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 ofobject representation,[7] and the possibility of aliasing.[12]

The actual size and behavior of floating-point types also vary by implementation. The only requirement is thatlong double is not smaller thandouble, which is not smaller thanfloat. Usually, the 32-bit and 64-bitIEEE 754 binary floating-point formats are used forfloat anddouble respectively.

TheC99 standard includes new real floating-point typesfloat_t anddouble_t, defined in<math.h>. They correspond to the types used for the intermediate results of floating-point expressions whenFLT_EVAL_METHOD is 0, 1, or 2. These types may be wider thanlong double.

C99 also addedcomplex types:float _Complex,double _Complex,long double _Complex.C11 addedimaginary 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 usingcomplex andimaginary respectively.

Boolean type

[edit]

C99 added aBoolean data type_Bool. Additionally, the<stdbool.h> header definesbool as a convenient alias for this type, and also provides macros fortrue andfalse._Bool functions similarly to a normal integer type, with one exception: any assignments to a_Bool that are not 0 (false) are stored as 1 (true). This behavior exists to avoidinteger overflows in implicit narrowing conversions. For example, in the following code:

InC23, the boolean type was moved tobool, making the<stdbool.h> header now useless.

unsignedcharb=256;if(b){/* do something */}

Variableb evaluates to false ifunsigned 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:

_Boolb=256;if(b){/* do something */}

The type_Bool also ensures true values always compare equal to each other:

_Boola=1,b=2;if(a==b){/* this code will run */}

In C23,bool became a core functionality of the language, allowing for the following examples of code:

boolb=true;if(b){/* this code will run */}

Bit-precise integer types

[edit]

SinceC23, 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), whereN 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 ofN is provided byBITINT_MAXWIDTH and is at leastULLONG_WIDTH. Therefore, the type_BitInt(2) (orsigned_BitInt(2)) takes values from −2 to 1 whileunsigned_BitInt(2) takes values from 0 to 3. The typeunsigned_BitInt(1) also exists, being either 0 or 1 and has no equivalent signed type.[13]

Size and pointer difference types

[edit]

The C language specification includes thetypedefssize_t andptrdiff_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 (cstddef in C++).

size_t is an unsigned integer type used to represent the size of any object (including arrays) in the particular implementation. The operatorsizeof yields a value of the typesize_t. The maximum size ofsize_t is provided viaSIZE_MAX, a macro constant which is defined in the<stdint.h> header (cstdint header in C++).size_t is guaranteed to be at least 16 bits wide. Additionally, POSIX includesssize_t, which is a signed integer type of the same width assize_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

[edit]

Information about the actual properties, such as size, of the basic arithmetic types, is provided via macro constants in two headers:<limits.h> header (climits header in C++) defines macros for integer types and<float.h> header (cfloat header in C++) defines macros for floating-point types. The actual values depend on the implementation.

Properties of integer types

[edit]
  • CHAR_BIT – size of the char type in bits, commonly referred to as the size of abyte (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 ofchar;CHAR_WIDTH,UCHAR_WIDTH andSCHAR_WIDTH are equal toCHAR_BIT by definition
  • SCHAR_WIDTH,SHRT_WIDTH,INT_WIDTH,LONG_WIDTH,LLONG_WIDTH (C23) - bit width ofsigned char,short,int,long, andlong long respectively
  • UCHAR_WIDTH,USHRT_WIDTH,UINT_WIDTH,ULONG_WIDTH,ULLONG_WIDTH (C23) - bit width ofunsigned char,unsigned short,unsigned int,unsigned long, andunsigned long long respectively

Properties of floating-point types

[edit]
  • 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_EPSILONdifference between 1.0 and the next representable value of float, double, long double, respectively
  • FLT_MANT_DIG,DBL_MANT_DIG,LDBL_MANT_DIG – number ofFLT_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 thatFLT_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 thatFLT_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 ofDECIMAL_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

[edit]

TheC99 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 inembedded environments where hardware usually supports only several types and that support varies between different environments. All new types are defined in<inttypes.h> header (cinttypes header in C++) and also are available at<stdint.h> header (cstdint header in C++). The types can be grouped into the following categories:

  • Exact-width integer types that are guaranteed to have the same numbern 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 numbern 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 numbern 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 categorySigned typesUnsigned types
TypeMinimum valueMaximum valueTypeMinimum valueMaximum value
Exact widthintn_tINTn_MININTn_MAXuintn_t0UINTn_MAX
Least widthint_leastn_tINT_LEASTn_MININT_LEASTn_MAXuint_leastn_t0UINT_LEASTn_MAX
Fastestint_fastn_tINT_FASTn_MININT_FASTn_MAXuint_fastn_t0UINT_FASTn_MAX
Pointerintptr_tINTPTR_MININTPTR_MAXuintptr_t0UINTPTR_MAX
Maximum widthintmax_tINTMAX_MININTMAX_MAXuintmax_t0UINTMAX_MAX

Printf and scanf format specifiers

[edit]
Main articles:printf format string andscanf format string

The<inttypes.h> header (cinttypes in C++) provides features that enhance the functionality of the types defined in the<stdint.h> header. It defines macros forprintf format string andscanf format string specifiers corresponding to the types defined in<stdint.h> and several functions for working with theintmax_t anduintmax_t types. This header was added inC99.

Printf format string

[edit]

The macros are in the formatPRI{fmt}{type}. Here{fmt} defines the output formatting and is one ofd (decimal),x (hexadecimal),o (octal),u (unsigned) andi (integer).{type} defines the type of the argument and is one ofn,FASTn,LEASTn,PTR,MAX, wheren corresponds to the number of bits in the argument.

Scanf format string

[edit]

The macros are in the formatSCN{fmt}{type}. Here{fmt} defines the output formatting and is one ofd (decimal),x (hexadecimal),o (octal),u (unsigned) andi (integer).{type} defines the type of the argument and is one ofn,FASTn,LEASTn,PTR,MAX, wheren corresponds to the number of bits in the argument.

Functions

[edit]
[icon]
This sectionneeds expansion. You can help byadding to it.(October 2011)

Additional floating-point types

[edit]

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.

Structures

[edit]

Structures aggregate the storage of multiple data items, of potentially differing data types, into one memory block referenced by a single variable. The following example declares the data typestruct birthday which contains the name and birthday of a person. The structure definition is followed by a declaration of the variableJohn that allocates the needed storage.

structbirthday{charname[20];intday;intmonth;intyear;};structbirthdayJohn;

The memory layout of a structure 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. Structures may beinitialized or assigned to using compound literals. A function may directly return a structure, although this is often not efficient at run-time. SinceC99, a structure may also end with aflexible array member.

A structure containing a pointer to a structure of its own type is commonly used to buildlinked data structures:

structnode{intval;structnode*next;};

Arrays

[edit]

For every typeT, exceptvoid and function types, there exist the types"array ofN elements of typeT". An array is a collection of values, all of the same type, stored contiguously in memory. An array of sizeN is indexed by integers from0 up to and includingN−1. Here is a brief example:

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

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

Pointers

[edit]
See also:Pointer (computer programming) § C pointers

Every data typeT has a corresponding typepointer toT. Apointer 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*square;long*circle;int*oval;

Pointers may also be declared for pointer data types, thus creating multiple indirect pointers, such aschar ** andint ***, 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 elementpc requires ten blocks of memory of the size ofpointer tochar (usually 40 or 80 bytes on common platforms), but elementpa is only one pointer (size 4 or 8 bytes), and the data it refers to is an array of ten bytes (sizeof*pa==10).

Unions

[edit]
See also:Union type § C/C++

Aunion type is a special construct that permits access to the same memory block by using a choice of differing type descriptions. For 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{inti;floatf;struct{unsignedintu;doubled;}s;}u;

The total size ofu is the size ofu.s – which happens to be the sum of the sizes ofu.s.u andu.s.d – sinces is larger than bothi andf. When assigning something tou.i, some parts ofu.f may be preserved ifu.i is smaller thanu.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

[edit]

Function pointers allow referencing functions with a particular signature. For example, to store the address of the standard functionabs in the variablemy_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. Function pointers are separate from pointers andvoid pointers.

Type qualifiers

[edit]
Main article:Type qualifier

The aforementioned types can be characterized further bytype qualifiers, yielding aqualified type. As of 2014[update] andC11, there are four type qualifiers in standard C:const (C89),volatile (C89),restrict (C99) and_Atomic (C11) – the latter has a private name to avoid clashing with user names,[14] but the more ordinary nameatomic can be used if the<stdatomic.h> header is included. Of these,const is by far the best-known and most used, appearing in thestandard library and encountered in any significant use of the C language, which must satisfyconst-correctness. The other qualifiers are used for low-level programming, and while widely used there, are rarely used by typical programmers.[citation needed]

See also

[edit]
The WikibookC Programming has a page on the topic of:Variables

References

[edit]
  1. ^Barr, Michael (2 December 2007)."Portable Fixed-Width Integers in C". Retrieved18 January 2016.
  2. ^abISO/IEC 9899:1999 specification, TC3(PDF). p. 255, § 7.18Integer types <stdint.h>.
  3. ^abcdefghijISO/IEC 9899:1999 specification, TC3(PDF). p. 22, § 5.2.4.2.1Sizes of integer types <limits.h>.
  4. ^Rationale for International Standard—Programming Languages—C Revision 5.10(PDF). p. 25, § 5.2.4.2.1Sizes of integer types <limits.h>.
  5. ^ISO/IEC 9899:2023 specification draft(PDF). p. 41, § 6.2.6Representations of types.
  6. ^"C and C++ Integer Limits". 21 July 2023.
  7. ^abISO/IEC 9899:1999 specification, TC3(PDF). p. 37, § 6.2.6.1Representations of types – General.
  8. ^abcdefISO/IEC 9899:1999 specification, TC3(PDF). p. 56, § 6.4.4.1Integer constants.
  9. ^"64-Bit Programming Models: Why LP64?". The Open Group. Retrieved9 November 2011.
  10. ^"Width of Type (The GNU C Library)".www.gnu.org. Retrieved30 July 2022.
  11. ^"<limits.h>".pubs.opengroup.org. Retrieved30 July 2022.
  12. ^ISO/IEC 9899:1999 specification, TC3(PDF). p. 67, § 6.5Expressions.
  13. ^ISO/IEC 9899:2023 specification draft(PDF). p. 37, § 6.2.5Types.
  14. ^C11:The New C Standard, Thomas Plum
Features
Standard library
Implementations
Compilers
IDEs
Comparison with
other languages
Descendant
languages
Designer
Uninterpreted
Numeric
Pointer
Text
Composite
Other
Related
topics
Retrieved from "https://en.wikipedia.org/w/index.php?title=C_data_types&oldid=1280409810#limits.h"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp