Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Data type
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Attribute of data}} {{distinguish|Data structure}} [[File:Python 3. The standard type hierarchy-en.svg|thumb|The standard type hierarchy of [[Python (programming language)|Python]] 3]] In [[computer science]] and [[computer programming]], a '''data type''' (or simply '''type''') is a collection or grouping of [[Value (computer science)|data 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.{{sfn|Parnas|Shore|Weiss|1976}} A data type specification in a program constrains the possible values that an [[Expression (computer science)|expression]], such as a variable or a function call, might take. On literal data, it tells the [[compiler]] or [[Interpreter (computing)|interpreter]] how the programmer intends to use the data. Most programming languages support basic data types of [[integer (computer science)|integer]] numbers (of varying sizes), [[floating point|floating-point]] numbers (which approximate [[real number]]s), [[Character (computing)|characters]] and [[Boolean data type|Booleans]].<ref>{{FOLDOC|type|new=yes}}</ref><ref>{{cite book |last=Shaffer |first=C. A. |title=Data Structures & Algorithm Analysis in C++ |location=Mineola, NY |publisher=Dover |edition=3rd |year=2011 |at=1.2 |isbn=978-0-486-48582-9 }}</ref> == Concept == A data type may be specified for many reasons: similarity, convenience, or to focus the attention. It is frequently a matter of good organization that 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.<ref>{{cite journal |last1=Scott |first1=Dana |title=Data Types as Lattices |journal=SIAM Journal on Computing |date=September 1976 |volume=5 |issue=3 |pages=540–541 |doi=10.1137/0205037}}</ref> Different languages may use different data types or similar types with different semantics. For example, in the [[Python (programming language)|Python programming language]], <code>int</code> represents an [[Arbitrary-precision arithmetic|arbitrary-precision integer]] which has the traditional numeric operations such as addition, subtraction, and multiplication. However, in the [[Java (programming language)|Java programming language]], the type <code>int</code> represents the set of [[32-bit]] [[Integer (computer science)|integers]] ranging in value from −2,147,483,648 to 2,147,483,647, with arithmetic operations that wrap on [[Integer overflow|overflow]]. In [[Rust (programming language)|Rust]] this 32-bit integer type is denoted <code>i32</code> and panics on overflow in debug mode.<ref>{{cite web |title=Rust RFCs - Integer Overflow |url=https://github.com/rust-lang/rfcs/blob/master/text/0560-integer-overflow.md |publisher=The Rust Programming Language |date=12 August 2022}}</ref> 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 three [[byte]]s denoting the amounts each of red, green, and blue, and a string representing the color's name. Data types are used within [[type system]]s, 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 of [[Value (computer science)|value]]s or [[object (computer science)|object]]s stored in computer memory. The type system uses data type information to check [[correctness of computer programs]] that access or manipulate the data. A [[compiler]] 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 many [[C (programming language)|C]] compilers the {{C-lang|float}} data type, for example, is represented in 32 [[bit]]s, in accord with the [[IEEE 754-2008|IEEE specification for single-precision floating point numbers]]. They will thus use floating-point-specific [[instruction set|microprocessor operations]] on those values (floating-point addition, multiplication, etc.). ==Definition== {{harvtxt|Parnas|Shore|Weiss|1976}} identified five definitions of a "type" that were used—sometimes implicitly—in the literature: ; Syntactic: A type is a purely [[syntax|syntactic]] label associated with a [[variable (computer science)|variable]] when it is declared. Although useful for advanced type systems such as [[substructural type system]]s, 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 of [[operator (computer programming)|operator]]s 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 union|disjoint]]) [[union (set theory)|union]]s or [[Cartesian product]]s of types. ; Value space and behaviour: A type is a set of values which a variable can possess and a set of [[function (computer science)|function]]s that one can apply to these values. The definition in terms of a representation was often done in imperative languages such as [[ALGOL]] and [[Pascal (programming language)|Pascal]], while the definition in terms of a value space and behaviour was used in higher-level languages such as [[Simula]] and [[CLU (programming language)|CLU]]. Types including behavior align more closely with [[object-oriented]] models, whereas a [[structured programming]] model would tend to not include code, and are called [[plain old data structure]]s. ==Classification== Data types may be categorized according to several factors: * ''[[Primitive data type]]s'' or ''built-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 an ''atomic type'' is a single data item that cannot be broken into component parts. A value of a ''[[composite type]]'' or ''aggregate type'' is a collection of data items that can be accessed individually.<ref>{{cite book |last1=Dale |first1=Nell B. |last2=Weems |first2=Chip |last3=Headington |first3=Mark R. |title=Programming in C++ |date=1998 |publisher=Jones & Bartlett Learning |isbn=978-0-7637-0537-4 |page=349 |url=https://books.google.com/books?id=yy2qKCf2_UYC&pg=PA349 |language=en}}</ref> 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'' or ''fundamental data types'' are defined axiomatically from fundamental notions or by enumeration of their elements. ''Generated data types'' or ''derived data types'' are specified, and partly defined, in terms of other data types. All basic types are atomic.<ref>[[ISO/IEC 11404]], 6.4</ref> 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.<ref>{{cite book |last1=BHATNAGAR |first1=SEEMA |title=TEXTBOOK OF COMPUTER SCIENCE FOR CLASS XI |date=19 August 2008 |publisher=PHI Learning Pvt. Ltd. |isbn=978-81-203-2993-5 |page=182 |url=https://books.google.com/books?id=bjE5EHw35DkC&pg=PA182 |language=en}}</ref> ==Examples== === Machine data types === All data in computers based on digital electronics is represented as [[bit]]s (alternatives 0 and 1) on the lowest level. The smallest addressable unit of data is usually a group of bits called a [[byte]] (usually an [[octet (computing)|octet]], which is 8 bits). The unit processed by [[machine code]] instructions is called a [[Word (data type)|word]] ({{as of|2025|lc=y}}, typically 64 bits). Machine data types ''expose'' 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 in [[systems programming]] or [[low-level programming language]]s. In higher-level languages most data types are ''abstracted'' in that they do not have a language-defined machine representation. The [[C 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 the <code>char</code> type that represents a byte.<ref>{{cite web|archive-url=https://web.archive.org/web/20181230041359/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf|url=http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf|title=SC22/WG14 N2176|at=Section 6.2.6.2|publisher=Wayback Machine|archive-date=30 December 2018|quote=Which of [sign and magnitude, two's complement, one's complement] applies is implementation-defined}}</ref> ===Boolean type=== The [[Boolean type]] represents the values [[logical truth|true]] and [[false (logic)|false]]. 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. ===Numeric types=== Almost all programming languages supply one or more [[integer (computing)|integer]] data types. They may either supply a small number of predefined subtypes restricted to certain ranges (such as <code>short</code> and <code>long</code> and their corresponding <code>unsigned</code> variants in C/C++); or allow users to freely define subranges such as 1..12 (e.g. [[Pascal (programming language)|Pascal]]/[[Ada (programming language)|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 mathematical [[real numbers]]). They are typically stored internally in the form {{math|a × 2<sup>b</sup>}} (where {{math|a}} and {{math|b}} are integers), but displayed in familiar [[decimal]] form. [[Fixed point (computing)|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, a [[Bignum]] or [[arbitrary precision]] <code>numeric</code> 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.<ref>{{cite web |title=Integer benchmarks — mp++ 0.27 documentation |url=https://bluescarni.github.io/mppp/integer_benchmarks.html |website=bluescarni.github.io}}</ref> ===Enumerations=== The [[enumerated 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 named ''CLUB'', ''DIAMOND'', ''HEART'', ''SPADE'', belonging to an enumerated type named ''suit''. If a variable ''V'' is declared having ''suit'' 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. === String and text types === [[String (computer science)|String]]s are a sequence of [[Character (computing)|character]]s used to store words or [[plain text]], most often textual [[markup languages]] representing [[formatted text]]. Characters may be a letter of some [[alphabet]], a digit, a blank space, a punctuation mark, etc. Characters are drawn from a character set such as [[ASCII]] or [[Unicode]]. 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 as [[Hebrew language|Hebrew]] and [[Chinese language|Chinese]]) 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 the [[Numerical digit|digits]], it is possible to have a numeric string, such as <code>"1234"</code>. These numeric strings are usually considered distinct from numeric values such as <code>1234</code>, although some languages automatically convert between them. === Union types === {{Main|Union (computer science)}} 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 a [[record (computer science)|record]], which could be defined to contain a float ''and'' an integer, a union may only contain one subtype at a time. A [[tagged union]] (also called a [[Variant type|variant]], variant record, discriminated union, or disjoint union) contains an additional field indicating its current type for enhanced type safety. === Algebraic data types === {{Main|Algebraic data type}} An [[algebraic data type]] (ADT) is a possibly recursive [[sum type]] of [[product type]]s. 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 an [[enumerated type]]. One common ADT is the [[option type]], defined in Haskell as {{haskell|1=data Maybe a = Nothing {{!}} Just a}}.<ref>{{Cite web |title=6 Predefined Types and Classes |url=https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x13-1250006.1.8 |access-date=2022-06-15 |website=www.haskell.org}}</ref> ===Data structures === Some types are very useful for storing and retrieving data and are called [[data structure]]s. Common data structures include: * An [[array data type|array]] (also called vector, [[List (abstract data type)|list]], or sequence) stores a number of elements and provides [[random 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 an [[associative array]]) from a specific range (if not all indices in that range correspond to elements, it may be a [[sparse array]]). * [[Record (computer science)|Record]] (also called tuple or struct) Records are among the simplest [[data structure]]s. 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 called ''fields'' or ''members''. * An [[object (computer science)|object]] contains a number of data fields, like a record, and also offers a number of subroutines for accessing or modifying them, called [[Method (computer programming)|methods]]. * the [[singly linked list]], which can be used to implement a [[Queue (abstract data type)|queue]] and is defined in Haskell as the ADT {{haskell|1=data List a = Nil {{!}} Cons a (List a)}}, and * the [[binary tree]], which allows fast searching, and can be defined in Haskell as the ADT {{haskell|1=data BTree a = Nil {{!}} Node (BTree a) a (BTree a)}}<ref>{{cite web |last1=Suresh |first1=S P |title=Programming in Haskell: Lecture 22 |url=https://www.cmi.ac.in/~spsuresh/teaching/prgh19/lectures/lecture22.pdf |publisher=Chennai Mathematical Institute |access-date=10 August 2022}}</ref> ===Abstract data types=== {{Main|Abstract data type}} An [[abstract data type]] is a data type that does not specify the concrete representation of the data. Instead, a formal ''specification'' based on the data type's operations is used to describe it. Any ''implementation'' of a specification must fulfill the rules given. For example, a [[Stack (abstract data type)|stack]] 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 formal [[Semantics (computer science)|semantics]] and program [[Formal verification|verification]] and, less strictly, in [[design]]. ===Pointers and references=== {{Main|Reference (computer science)}} The main non-composite, derived type is the [[pointer (computer programming)|pointer]], a data type whose value refers directly to (or "points to") another value stored elsewhere in the [[computer memory]] using its [[Memory address|address]]. It is a primitive kind of [[reference (computer science)|reference]]. (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. ===Function types=== {{Main|Function type}} [[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 as [[JavaScript]] also have mechanisms for treating functions as data.<ref>{{cite book |last1=Flanagan |first1=David |title=JavaScript: the definitive guide |date=1997 |publisher=O'Reilly & Associates |location=Cambridge |isbn=9781565922341 |edition=2nd |chapter=6.2 Functions as Data Types}}</ref> Most contemporary [[type 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 type <code>Int -> Bool</code> denoting functions taking an integer and returning a Boolean. In C, a function is not a first-class data type but [[function pointer]]s 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. ===Type constructors=== {{Main|Type constructor}} 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. ===Quantified types === Universally-quantified and existentially-quantified types are based on [[predicate logic]]. Universal quantification is written as <math>\forall x.f(x)</math> or <code>forall x. f x</code> and is the intersection over all types <code>x</code> of the body <code>f x</code>, i.e. the value is of type <code>f x</code> for every <code>x</code>. Existential quantification written as <math>\exists x.f(x)</math> or <code>exists x. f x</code> and is the union over all types <code>x</code> of the body <code>f x</code>, i.e. the value is of type <code>f x</code> for some <code>x</code>. In Haskell, universal quantification is commonly used, but existential types must be encoded by transforming <code>exists a. f a</code> to <code>forall r. (forall a. f a -> r) -> r</code> or a similar type. ===Refinement types=== {{Main|Refinement 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 <math>\{n\in \mathbb {N} \,|\,n>5\}</math> ===Dependent types=== {{Main|Dependent type}} 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. ===Intersection types=== {{Main|Intersection type}} An intersection type is a type containing those values that are members of two specified types. For example, in [[Java (programming language)|Java]] the class {{code|Boolean}} implements both the {{code|Serializable}} and the {{code|Comparable}} interfaces. Therefore, an object of type {{code|Boolean}} is a member of the type {{code|Serializable & Comparable}}. Considering types as sets of values, the intersection type <math>\sigma \cap \tau</math> is the set-theoretic [[Intersection (set theory)|intersection]] of <math>\sigma</math> and <math>\tau</math>. It is also possible to define a dependent intersection type, denoted <math>(x : \sigma) \cap \tau</math>, where the type <math>\tau</math> may depend on the term variable <math>x</math>.<ref name=K03>{{cite conference |title=Dependent intersection: A new way of defining records in type theory |last1=Kopylov |first1=Alexei |year=2003 |publisher=IEEE Computer Society |book-title=18th IEEE Symposium on Logic in Computer Science |pages=86–95 |conference=LICS 2003 |doi=10.1109/LICS.2003.1210048 |citeseerx=10.1.1.89.4223 }}</ref> ===Meta types=== {{Main|Metaclass}} Some programming languages represent the type information as data, enabling [[type introspection]] and [[reflective programming]] (reflection). In contrast, [[Type constructor|higher order]] [[type system]]s, while allowing types to be constructed from other types and passed to functions as values, typically avoid basing [[computation]]al decisions on them.{{citation needed|date=September 2021}} ===Convenience types=== For convenience, high-level languages and databases may supply ready-made "real world" data types, for instance times, dates, and monetary values (currency).<ref>{{cite web |last1=West |first1=Randolph |title=How SQL Server stores data types: money |url=https://bornsql.ca/blog/how-sql-server-stores-data-types-money/ |website=Born SQL |access-date=28 January 2022 |date=27 May 2020 |quote=Some time ago I described MONEY as a “convenience” data type which is effectively the same as DECIMAL(19,4), [...]}}</ref><ref>{{cite web |title=Introduction to data types and field properties |url=https://support.microsoft.com/en-us/office/introduction-to-data-types-and-field-properties-30ad644f-946c-442e-8bd2-be067361987c |website=support.microsoft.com |access-date=28 January 2022}}</ref> These may be built-in to the language or implemented as composite types in a library.<ref>{{cite book |last1=Wickham |first1=Hadley |title=R for data science: import, tidy, transform, visualize, and model data |location=Sebastopol, CA |isbn=978-1491910399 |access-date=28 January 2022|chapter=16 Dates and times|year=2017 |chapter-url=https://r4ds.had.co.nz/dates-and-times.html}}</ref> ==See also== {{div col}} * [[C data types]] * [[Data dictionary]] * [[Kind (type theory)|Kind]] * [[Type (model theory)]] * [[Type theory]] for the mathematical models of types * [[Type conversion]] * [[ISO/IEC 11404]], General Purpose Datatypes * [[Statistical data type]] {{div col end}} ==References== {{Reflist}} ==Further reading== *{{cite book|last1 = Parnas|first1=David L.|author-link1=David Parnas|first2=John E.|last2=Shore|first3=David|last3=Weiss|title=Proceedings of the 1976 conference on Data : Abstraction, definition and structure - |chapter=Abstract types defined as classes of variables |year=1976|pages=149–154|doi=10.1145/800237.807133|s2cid=14448258|doi-access=free}} *{{cite journal|last1 = Cardelli|first1=Luca|author-link1=Luca Cardelli|last2=Wegner|first2=Peter|author-link2=Peter Wegner (computer scientist)|title = On Understanding Types, Data Abstraction, and Polymorphism|url=http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf |archive-url=https://web.archive.org/web/20081203071429/http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf |archive-date=2008-12-03 |url-status=live|journal = [[ACM Computing Surveys]]|date = December 1985| volume = 17|issue=4|issn = 0360-0300|pages = 471–523|doi = 10.1145/6041.6042|citeseerx=10.1.1.117.695|s2cid=2921816}} *{{cite book|first=J. Craig|last=Cleaveland|title=An Introduction to Data Types|year=1986|publisher=Addison-Wesley|isbn=978-0201119404}} ==External links== *{{Commons category-inline|Data types}} {{Data types}} {{Authority control}} {{DEFAULTSORT:Data Type}} [[Category:Data types| ]] [[Category:Programming language concepts]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:As of
(
edit
)
Template:Authority control
(
edit
)
Template:C-lang
(
edit
)
Template:Citation needed
(
edit
)
Template:Cite book
(
edit
)
Template:Cite conference
(
edit
)
Template:Cite journal
(
edit
)
Template:Cite web
(
edit
)
Template:Code
(
edit
)
Template:Commons category-inline
(
edit
)
Template:Data types
(
edit
)
Template:Distinguish
(
edit
)
Template:Div col
(
edit
)
Template:Div col end
(
edit
)
Template:FOLDOC
(
edit
)
Template:Harvtxt
(
edit
)
Template:Haskell
(
edit
)
Template:Main
(
edit
)
Template:Math
(
edit
)
Template:Reflist
(
edit
)
Template:Sfn
(
edit
)
Template:Short description
(
edit
)
Template:Talk other
(
edit
)