Incomputer science andcomputer programming, adata type (or simplytype) is a collection or grouping ofdata values, usually specified by a set of possible values, a set of allowed operations on these values, and/or a representation of these values as machine types.[1] A data type specification in a program constrains the possible values that anexpression, such as a variable or a function call, might take. On literal data, it tells thecompiler orinterpreter how the programmer intends to use the data. Most programming languages support basic data types ofinteger numbers (of varying sizes),floating-point numbers (which approximatereal numbers),characters andBooleans.[2][3]
A data type may be specified for many reasons: similarity, convenience, or to focus the attention. It is frequently a matter of good organizationthat aids the understanding of complex definitions. Almost all programming languages explicitly include the notion of data type, though the possible data types are often restricted by considerations of simplicity, computability, or regularity. An explicit data type declaration typically allows the compiler to choose an efficient machine representation, but the conceptual organization offered by data types should not be discounted.[4]
Different languages may use different data types or similar types with different semantics. For example, in thePython programming language,int represents anarbitrary-precision integer which has the traditional numeric operations such as addition, subtraction, and multiplication. However, in theJava programming language, the typeint represents the set of32-bitintegers ranging in value from −2,147,483,648 to 2,147,483,647, with arithmetic operations that wrap onoverflow. InRust this 32-bit integer type is denotedi32 and panics on overflow in debug mode.[5]
Most programming languages also allow the programmer to define additional data types, usually by combining multiple elements of other types and defining the valid operations of the new data type. For example, a programmer might create a new data type named "complex number" that would include real and imaginary parts, or a color data type represented by threebytes denoting the amounts each of red, green, and blue, and a string representing the color's name.
Data types are used withintype systems, which offer various ways of defining, implementing, and using them. In a type system, a data type represents a constraint placed upon the interpretation of data, describing representation, interpretation and structure ofvalues orobjects stored in computer memory. The type system uses data type information to checkcorrectness of computer programs that access or manipulate the data. Acompiler may use the static type of a value to optimize the storage it needs and the choice of algorithms for operations on the value. In manyC compilers thefloat data type, for example, is represented in 32bits, in accord with theIEEE specification for single-precision floating point numbers. They will thus use floating-point-specificmicroprocessor operations on those values (floating-point addition, multiplication, etc.).
Parnas, Shore & Weiss (1976) identified five definitions of a "type" that were used—sometimes implicitly—in the literature:
Syntactic
A type is a purelysyntactic label associated with avariable when it is declared. Although useful for advanced type systems such assubstructural type systems, such definitions provide no intuitive meaning of the types.
Representation
A type is defined in terms of a composition of more primitive types—often machine types.
Representation and behaviour
A type is defined as its representation and a set ofoperators manipulating these representations.
Value space
A type is a set of possible values which a variable can possess. Such definitions make it possible to speak about (disjoint)unions orCartesian products of types.
Value space and behaviour
A type is a set of values which a variable can possess and a set offunctions that one can apply to these values.
The definition in terms of a representation was often done in imperative languages such asALGOL andPascal, while the definition in terms of a value space and behaviour was used in higher-level languages such asSimula andCLU. Types including behavior align more closely withobject-oriented models, whereas astructured programming model would tend to not include code, and are calledplain old data structures.
Data types may be categorized according to several factors:
Primitive data types orbuilt-in data types are types that are built-in to a language implementation.User-defined data types are non-primitive types. For example, Java's numeric types are primitive, while classes are user-defined.
A value of anatomic type is a single data item that cannot be broken into component parts. A value of acomposite type oraggregate type is a collection of data items that can be accessed individually.[6] For example, an integer is generally considered atomic, although it consists of a sequence of bits, while an array of integers is certainly composite.
Basic data types orfundamental data types are defined axiomatically from fundamental notions or by enumeration of their elements.Generated data types orderived data types are specified, and partly defined, in terms of other data types. All basic types are atomic.[7] For example, integers are a basic type defined in mathematics, while an array of integers is the result of applying an array type generator to the integer type.
The terminology varies - in the literature, primitive, built-in, basic, atomic, and fundamental may be used interchangeably.[8]
All data in computers based on digital electronics is represented asbits (alternatives 0 and 1) on the lowest level. The smallest addressable unit of data is usually a group of bits called abyte (usually anoctet, which is 8 bits). The unit processed bymachine code instructions is called aword (as of 2025[update], typically 64 bits).
Machine data typesexpose or make available fine-grained control over hardware, but this can also expose implementation details that make code less portable. Hence machine types are mainly used insystems programming orlow-level programming languages. In higher-level languages most data types areabstracted in that they do not have a language-defined machine representation. TheC programming language, for instance, supplies types such as Booleans, integers, floating-point numbers, etc., but the precise bit representations of these types are implementation-defined. The only C type with a precise machine representation is thechar type that represents a byte.[9]
TheBoolean type represents the valuestrue andfalse. Although only two values are possible, they are more often represented as a byte or word rather as a single bit as it requires more machine instructions to store and retrieve an individual bit. Many programming languages do not have an explicit Boolean type, instead using an integer type and interpreting (for instance) 0 as false and other values as true.Boolean data refers to the logical structure of how the language is interpreted to the machine language. In this case a Boolean 0 refers to the logic False. True is always a non zero, especially a one which is known as Boolean 1.
Almost all programming languages supply one or moreinteger data types. They may either supply a small number of predefined subtypes restricted to certain ranges (such asshort andlong and their correspondingunsigned variants in C/C++); or allow users to freely define subranges such as 1..12 (e.g.Pascal/Ada). If a corresponding native type does not exist on the target platform, the compiler will break them down into code using types that do exist. For instance, if a 32-bit integer is requested on a 16 bit platform, the compiler will tacitly treat it as an array of two 16 bit integers.
Floating point data types represent certain fractional values (rational numbers, mathematically). Although they have predefined limits on both their maximum values and their precision, they are sometimes misleadingly called reals (evocative of mathematicalreal numbers). They are typically stored internally in the forma × 2b (wherea andb are integers), but displayed in familiardecimal form.
Fixed point data types are convenient for representing monetary values. They are often implemented internally as integers, leading to predefined limits.
For independence from architecture details, aBignum orarbitrary precisionnumeric type might be supplied. This represents an integer or rational to a precision limited only by the available memory and computational resources on the system. Bignum implementations of arithmetic operations on machine-sized values are significantly slower than the corresponding machine operations.[10]
Theenumerated type has distinct values, which can be compared and assigned, but which do not necessarily have any particular concrete representation in the computer's memory; compilers and interpreters can represent them arbitrarily. For example, the four suits in a deck of playing cards may be four enumerators namedCLUB,DIAMOND,HEART,SPADE, belonging to an enumerated type namedsuit. If a variableV is declared havingsuit as its data type, one can assign any of those four values to it. Some implementations allow programmers to assign integer values to the enumeration values, or even treat them as type-equivalent to integers.
Strings are a sequence ofcharacters used to store words orplain text, most often textualmarkup languages representingformatted text. Characters may be a letter of somealphabet, a digit, a blank space, a punctuation mark, etc. Characters are drawn from a character set such asASCII orUnicode. Character and string types can have different subtypes according to the character encoding. The original 7-bit wide ASCII was found to be limited, and superseded by 8, 16 and 32-bit sets, which can encode a wide variety of non-Latin alphabets (such asHebrew andChinese) and other symbols. Strings may be of either variable length or fixed length, and some programming languages have both types. They may also be subtyped by their maximum size.
Since most character sets include thedigits, it is possible to have a numeric string, such as"1234". These numeric strings are usually considered distinct from numeric values such as1234, although some languages automatically convert between them.
A union type definition will specify which of a number of permitted subtypes may be stored in its instances, e.g. "float or long integer". In contrast with arecord, which could be defined to contain a floatand an integer, a union may only contain one subtype at a time.
Atagged union (also called avariant, variant record, discriminated union, or disjoint union) contains an additional field indicating its current type for enhanced type safety.
Analgebraic data type (ADT) is a possibly recursivesum type ofproduct types. A value of an ADT consists of a constructor tag together with zero or more field values, with the number and type of the field values fixed by the constructor. The set of all possible values of an ADT is the set-theoretic disjoint union (sum), of the sets of all possible values of its variants (product of fields). Values of algebraic types are analyzed with pattern matching, which identifies a value's constructor and extracts the fields it contains.
If there is only one constructor, then the ADT corresponds to a product type similar to a tuple or record. A constructor with no fields corresponds to the empty product (unit type). If all constructors have no fields then the ADT corresponds to anenumerated type.
One common ADT is theoption type, defined in Haskell asdataMaybea=Nothing|Justa.[11]
Some types are very useful for storing and retrieving data and are calleddata structures. Common data structures include:
Anarray (also called vector,list, or sequence) stores a number of elements and providesrandom access to individual elements. The elements of an array are typically (but not in all contexts) required to be of the same type. Arrays may be fixed-length or expandable. Indices into an array are typically required to be integers (if not, one may stress this relaxation by speaking about anassociative array) from a specific range (if not all indices in that range correspond to elements, it may be asparse array).
Record (also called tuple or struct) Records are among the simplestdata structures. A record is a value that contains other values, typically in fixed number and sequence and typically indexed by names. The elements of records are usually calledfields ormembers.
Anobject contains a number of data fields, like a record, and also offers a number of subroutines for accessing or modifying them, calledmethods.
thesingly linked list, which can be used to implement aqueue and is defined in Haskell as the ADTdataLista=Nil|Consa(Lista), and
thebinary tree, which allows fast searching, and can be defined in Haskell as the ADTdataBTreea=Nil|Node(BTreea)a(BTreea)[12]
Anabstract data type is a data type that does not specify the concrete representation of the data. Instead, a formalspecification based on the data type's operations is used to describe it. Anyimplementation of a specification must fulfill the rules given. For example, astack has push/pop operations that follow a Last-In-First-Out rule, and can be concretely implemented using either a list or an array. Abstract data types are used in formalsemantics and programverification and, less strictly, indesign.
The main non-composite, derived type is thepointer, a data type whose value refers directly to (or "points to") another value stored elsewhere in thecomputer memory using itsaddress. It is a primitive kind ofreference. (In everyday terms, a page number in a book could be considered a piece of data that refers to another one). Pointers are often stored in a format similar to an integer; however, attempting to dereference or "look up" a pointer whose value was never a valid memory address would cause a program to crash. To ameliorate this potential problem, a pointer type is typically considered distinct from the corresponding integer type, even if the underlying representation is the same.
Functional programming languages treat functions as a distinct datatype and allow values of this type to be stored in variables and passed to functions. Some multi-paradigm languages such asJavaScript also have mechanisms for treating functions as data.[13] Most contemporarytype systems go beyond JavaScript's simple type "function object" and have a family of function types differentiated by argument and return types, such as the typeInt -> Bool denoting functions taking an integer and returning a Boolean. In C, a function is not a first-class data type butfunction pointers can be manipulated by the program. Java and C++ originally did not have function values but have added them in C++11 and Java 8.
A type constructor builds new types from old ones, and can be thought of as an operator taking zero or more types as arguments and producing a type. Product types, function types, power types and list types can be made into type constructors.
Universally-quantified and existentially-quantified types are based onpredicate logic. Universal quantification is written as orforall x. f x and is the intersection over all typesx of the bodyf x, i.e. the value is of typef x for everyx. Existential quantification written as orexists x. f x and is the union over all typesx of the bodyf x, i.e. the value is of typef x for somex.
In Haskell, universal quantification is commonly used, but existential types must be encoded by transformingexists a. f a toforall r. (forall a. f a -> r) -> r or a similar type.
A refinement type is a type endowed with a predicate which is assumed to hold for any element of the refined type. For instance, the type of natural numbers greater than 5 may be written as
A dependent type is a type whose definition depends on a value. Two common examples of dependent types are dependent functions and dependent pairs. The return type of a dependent function may depend on the value (not just type) of one of its arguments. A dependent pair may have a second value of which the type depends on the first value.
An intersection type is a type containing those values that are members of two specified types. For example, inJava the classBoolean implements both theSerializable and theComparable interfaces. Therefore, an object of typeBoolean is a member of the typeSerializable & Comparable. Considering types as sets of values, the intersection type is the set-theoreticintersection of and. It is also possible to define a dependent intersection type, denoted, where the type may depend on the term variable.[14]
For convenience, high-level languages and databases may supply ready-made "real world" data types, for instance times, dates, and monetary values (currency).[15][16] These may be built-in to the language or implemented as composite types in a library.[17]
^"SC22/WG14 N2176"(PDF). Wayback Machine. Section 6.2.6.2. Archived fromthe original(PDF) on 30 December 2018.Which of [sign and magnitude, two's complement, one's complement] applies is implementation-defined
^Flanagan, David (1997). "6.2 Functions as Data Types".#"/wiki/ISBN_(identifier)" title="ISBN (identifier)">ISBN 9781565922341.
^Kopylov, Alexei (2003). "Dependent intersection: A new way of defining records in type theory".18th IEEE Symposium on Logic in Computer Science. LICS 2003. IEEE Computer Society. pp. 86–95.CiteSeerX10.1.1.89.4223.doi:10.1109/LICS.2003.1210048.
^West, Randolph (27 May 2020)."How SQL Server stores data types: money".Born SQL. Retrieved28 January 2022.Some time ago I described MONEY as a "convenience" data type which is effectively the same as DECIMAL(19,4), [...]
^Wickham, Hadley (2017)."16 Dates and times".R for data science: import, tidy, transform, visualize, and model data. Sebastopol, CA.ISBN978-1491910399. Retrieved28 January 2022.{{cite book}}: CS1 maint: location missing publisher (link)
Parnas, David L.; Shore, John E.; Weiss, David (1976). "Abstract types defined as classes of variables".Proceedings of the 1976 conference on Data : Abstraction, definition and structure -. pp. 149–154.doi:10.1145/800237.807133.S2CID14448258.