Typedef
Encyclopedia
typedef
is a keywordKeyword (computer programming)
In computer programming, a keyword is a word or identifier that has a particular meaning to the programming language. The meaning of keywords — and, indeed, the meaning of the notion of keyword — differs widely from language to language....
in the C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
and C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
s. The purpose of
typedef
is to assign alternative names to existing typesType system
A type system associates a type with each computed value. By examining the flow of these values, a type system attempts to ensure or prove that no type errors can occur...
, most often those whose standard declaration is cumbersome, potentially confusing, or likely to vary from one implementation to another.
Under C convention (such as in the C standard library
C standard library
The C Standard Library is the standard library for the programming language C, as specified in the ANSI C standard.. It was developed at the same time as the C POSIX library, which is basically a superset of it...
), types declared with typedef end with '_t' (e.g., size t
Size t
size_t is an unsigned data type defined by several C and C++ standards that is defined in stddef.h. It can be further imported by inclusion of stdlib.h as this file internally sub includes stddef.h....
, time t).
Indicating what a variable represents
A typedef can be used to indicate how a variable represents something, e.g., units of measurement or counts:Now consider this:
Both sections of code do the same thing. However, the use of
typedef
in the second example makes it clear that the two variables, while represented by the same data type (int
), represent different and incompatible things. The declaration in congratulate
of your_score
indicates to the programmer that current_speed
(or any other variable not declared as a points
) should not be passed as an argument. This would not be as apparent if both were declared as int
s. However, note that the indication is for the programmer only; the C/C++ compiler considers both variables to be int
s and will not give any type mismatch warnings or errors for the "wrong" argument type for congratulate(points your_score)
in the code snippet below:Simplifying a declaration
A typedef can be used to simplify the declaration for a compound type (struct, union) or pointer type such as:Here (above) a struct var data type has been defined. To declare a variable of this type in C (below) the
struct
key word is required (though it can be omitted in C++):A typedef can be used to eliminate the need for the
struct
key word in C. For example, with:we can now create a variable of this type with:
Note that the structure definition and typedef can instead be combined into a single statement:
Or simply we can also use it as:
In C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
, in contrast to C, the
struct
, class
, and enum
key words are optional in variable declarations that are separate from the definitions:As such,
var
can be used wherever newtype
can be used. However, the reverse is not true; for instance, the constructor methods for var
cannot be named newtype
.Using typedef with pointers
Typedefs can also simplify declarations for pointer types. Consider this:In C, one can declare multiple variables of the same type in a single statement, even mixing pointer and non-pointers. However, one would need to prefix an asterisk to each variable to designate it as a pointer:
A programmer would assume that
errptr
was indeed a Node *
, but a typographical error means that errptr
is a Node
. This can lead to subtle syntax errors.By defining a
Node *
typedef, it is assured that all the variables will be pointer types.Using typedef with type casts
A typedef is created using type declaration syntax but can be used as if it were created using type cast syntax. (Type castingType conversion
In computer science, type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another. This is done to take advantage of certain features of type hierarchies or type representations...
changes a data type.) For instance, in each line after the first line of:
funcptr
is used on the left-hand side to declare a variable and is used on the right-hand side to cast a value. Thus, typedefs can be used by programmers who do not wish to figure out how to convert declaration syntax to type cast syntax.Note that, without the typedef, it is generally not possible to use declaration syntax and cast syntax interchangeably. For example:
Usage concerns
Some people are opposed to the extensive use of typedefs. Most arguments center on the idea that typedefs simply hide the actual data type of a variable. For example, Greg Kroah-HartmanGreg Kroah-Hartman
Greg Kroah-Hartman is a Linux kernel developer. He is the current Linux kernel maintainer for the -stable branch with Chris Wright, the staging subsystem, USB, driver core, debugfs, kref, kobject, and the sysfs kernel subsystems, Userspace I/O and TTY layer. He is also the maintainer of the...
, a Linux kernel
Linux kernel
The Linux kernel is an operating system kernel used by the Linux family of Unix-like operating systems. It is one of the most prominent examples of free and open source software....
hacker and documenter, discourages their use for anything except function prototype declarations. He argues that this practice not only unnecessarily obfuscates code, it can also cause programmers to accidentally misuse large structures thinking them to be simple types.
Others argue that the use of typedefs can make code easier to maintain. K&R
The C Programming Language (book)
The C Programming Language is a well-known programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the language, as well as co-designed the Unix operating system with which development of the language was closely intertwined...
states that there are two reasons for using a typedef. First, it provides a means to make a program more portable. Instead of having to change a type everywhere it appears throughout the program's source files, only a single typedef statement needs to be changed. Second, a typedef can make a complex declaration easier to understand.
Usage in C++
In C++ type names can be very complicated and typedef provides a mechanism to assign a simple name to the type. Consider:and
Use with C++ templates
There is no direct way to have templated typedefs in C++. For instance, to havestringpair
represent std::pair
for every type T
one cannot use:However, if one is willing to accept
stringpair::foo
, or similar, in lieu of stringpair
then it is possible to achieve the desired result via a typedef within an otherwise unused templated class
or struct
:Other languages
In many statically-typed functional languages, like HaskellHaskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...
, Miranda, OCaml, etc., you can define type synonyms, which are the same as typedefs in C. An example in Haskell:
type PairOfInts = (Int, Int)
This example has defined a type synonym "PairOfInts" which means the same as a pair of Ints.
C# also contains a feature which is similar to the typedef of C; however, it must be redeclared for each separate file. See this MSDN article for more
using newType = global::System.Runtime.Interop.Marshal;
using otherType = Enums.MyEnumType;