Typedef
   HOME

TheInfoList



OR:

typedef is a reserved keyword in the
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s C,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, and
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
. It is used to create an additional name (''alias'') for another
data type In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type. As such, it is often used to simplify the syntax of declaring complex
data structure In computer science, a data structure is a data organization, management, and storage format that is usually chosen for efficient access to data. More precisely, a data structure is a collection of data values, the relationships among them, a ...
s consisting of
struct In computer science, a record (also called a structure, struct, or compound data) is a basic data structure. Records in a database or spreadsheet are usually called "rows". A record is a collection of '' fields'', possibly of different data typ ...
and
union type In computer science, a union is a value that may have any of several representations or formats within the same position in memory; that consists of a variable that may hold such a data structure. Some programming languages support special data ...
s, although it is also commonly used to provide specific descriptive type names for integer data types of varying sizes.


Syntax

The syntax of the typedef declaration is: ; ''type-declaration''; The name of the new type alias follows the same syntax as declaring any other C identifier, therefore, in more detailed form: ; ''type-definition'' ''identifier;'' In the C standard library and in
POSIX The Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines both the system- and user-level application programming interf ...
specifications, the identifier for the typedef definition is often suffixed with , such as in size_t and time_t. This is practiced in other coding systems, although POSIX explicitly reserves this practice for POSIX data types.


Examples

This creates the type as a synonym of the type : typedef int length;


Documentation use

A typedef declaration may be used as documentation by indicating the meaning of a variable within the programming context, e.g., it may include the expression of a unit of measurement or counts. The generic declarations, int current_speed; int high_score; void congratulate(int your_score) may be expressed by declaring context specific types: typedef int km_per_hour; typedef int points; // `km_per_hour` is synonymous with `int` here, and thus, the compiler treats // our new variables as integers. km_per_hour current_speed; points high_score; void congratulate(points your_score) Both sections of code execute identically. However, the use of typedef declarations in the second code block makes it clear that the two variables, while representing the same data type , store different or incompatible data. The definition in of indicates to the programmer that (or any other variable not declared as a ) should not be passed as an argument. This would not be as apparent if both were declared as variables of datatype. However, the indication is ''for the programmer only''; the C/C++ compiler considers both variables to be of type and does not flag type mismatch warnings or errors for "wrong" argument types for in the code snippet below: void foo()


Type simplification

A typedef may be used to simplify the declaration of a compound type (
struct In computer science, a record (also called a structure, struct, or compound data) is a basic data structure. Records in a database or spreadsheet are usually called "rows". A record is a collection of '' fields'', possibly of different data typ ...
,
union Union commonly refers to: * Trade union, an organization of workers * Union (set theory), in mathematics, a fundamental operation on sets Union may also refer to: Arts and entertainment Music * Union (band), an American rock group ** ''Un ...
) or pointer type. For example, struct MyStruct ; This defines the data type . A variable declaration of this type in C also requires the keyword , but it may be omitted in C++: struct MyStruct a; A typedef declaration eliminates the requirement of specifying in C. For example, the declaration typedef struct MyStruct newtype; is reduced to: newtype a; The structure declaration and typedef may also be combined into a single statement: typedef struct MyStruct newtype; Or it may be used as follows: typedef struct newtype; In
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, in contrast to C, the keywords , , and are optional in variable declarations that are separate from the definitions, as long as there is no ambiguity to another identifier: struct MyStruct x; MyStruct y; As such, can be used wherever can be used. However, the reverse is not true; for instance, the constructor methods for cannot be named . A notorious example where even
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
needs the keyword is the
POSIX The Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines both the system- and user-level application programming interf ...
stat system call that uses a struct of the same name in its arguments: int stat(const char *filename, struct stat *buf) Here both C as well as
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
need the keyword in the parameter definition.


Pointers

The typedef may be used to define a new pointer type. typedef int *intptr; intptr ptr; // Same as: // int *ptr; is a new alias with the pointer type . The definition, , defines a variable with the type . So, is a pointer which can point to a variable of type . Using typedef to define a new pointer type may sometimes lead to confusion. For example: typedef int *intptr; // Both 'cliff' and 'allen' are of type int*. intptr cliff, allen; // 'cliff2' is of type int*, but 'allen2' is of type int**. intptr cliff2, *allen2; // Same as: // intptr cliff2; // intptr *allen2; Above, means defining 2 variables with type for both. This is because a type defined by typedef is a type, not an expansion. In other words, , which is the type, decorates both and . For , the type decorates the and . So, is equivalent to 2 separate definitions, and . means that is a pointer pointing to a memory with type. Shortly, has the type, .


Constant pointers

Again, because typedef defines a type, not an expansion, declarations that use the const qualifier can yield unexpected or unintuitive results. The following example declares a constant pointer to an integer type, not a pointer to a constant integer: typedef int *intptr; const intptr ptr = NULL; // Same as: // int *const ptr = NULL; Since it is a constant pointer, it must be initialized in the declaration.


Structures and structure pointers

Typedefs can also simplify definitions or declarations for
structure A structure is an arrangement and organization of interrelated elements in a material object or system, or the object or system so organized. Material structures include man-made objects such as buildings and machines and natural objects such as ...
pointer types. Consider this: struct Node ; Using typedef, the above code can be rewritten like this: typedef struct Node Node; struct Node ; In C, one can declare multiple variables of the same type in a single statement, even mixing structure with pointer or non-pointers. However, one would need to prefix an asterisk to each variable to designate it as a pointer. In the following, a programmer might assume that was indeed a , but a typographical error means that is a . This can lead to subtle syntax errors. struct Node *startptr, *endptr, *curptr, *prevptr, errptr, *refptr; By defining the typedef , it is assured that all variables are structure pointer types, or say, that each variable is a
pointer type In computer science, a pointer is an object (computer science), object in many programming languages that stores a memory address. This can be that of another value located in computer memory, or in some cases, that of Memory-mapped I/O, memo ...
pointing to a structure type. typedef struct Node* NodePtr; NodePtr startptr, endptr, curptr, prevptr, errptr, refptr;


Function pointers

int do_math(float arg1, int arg2) int call_a_func(int (*call_this)(float, int)) int final_result = call_a_func(&do_math); The preceding code may be rewritten with typedef specifications: typedef int (*MathFunc)(float, int); int do_math(float arg1, int arg2) int call_a_func(MathFunc call_this) int final_result = call_a_func(&do_math); Here, is the new alias for the type. A is a pointer to a function that returns an integer and takes as arguments a float followed by an integer. When a function returns a
function pointer A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function poi ...
, it can be even more confusing without typedef. The following is the function prototype of ''signal(3)'' from
FreeBSD FreeBSD is a free and open-source Unix-like operating system descended from the Berkeley Software Distribution (BSD), which was based on Research Unix. The first version of FreeBSD was released in 1993. In 2005, FreeBSD was the most popular ...
: void (*signal(int sig, void (*func)(int)))(int); The function declaration above is cryptic as it does not clearly show what the function accepts as arguments, or the type that it returns. A novice programmer may even assume that the function accepts a single as its argument and returns nothing, but in reality it also needs a function pointer and returns another function pointer. It can be written more cleanly: typedef void (*sighandler_t)(int); sighandler_t signal(int sig, sighandler_t func);


Arrays

A typedef can also be used to simplify the definition of array types. For example, typedef char arrType arrType arr = ; arrType *pArr; // Same as: // char arr = ; // char (*pArr) Here, is the new alias for the type, which is an array type with 6 elements. For , is a pointer pointing to the memory of the type.


Type casts

A typedef is created using type ''definition'' syntax but can be used as if it were created using type ''cast'' syntax. ( Type casting changes a data type.) For instance, in each line after the first line of: // `funcptr` is a pointer to a function which takes a `double` and returns an `int`. typedef int (*funcptr)(double); // Valid in both C and C++. funcptr x = (funcptr) NULL; // Only valid in C++. funcptr y = funcptr(NULL); funcptr z = static_cast(NULL); is used on the left-hand side to declare a variable and is used on the right-hand side to cast a value. Thus, the typedef can be used by programmers who do not wish to figure out how to convert definition syntax to type cast syntax. Without the typedef, it is generally not possible to use definition syntax and cast syntax interchangeably. For example: void *p = NULL; // This is legal. int (*x)(double) = (int (*)(double)) p; // Left-hand side is not legal. int (*)(double) y = (int (*)(double)) p; // Right-hand side is not legal. int (*z)(double) = (int (*p)(double));


Usage in C++

In C++ type names can be complex, and typedef provides a mechanism to assign a simple name to the type. std::vector> values; for (std::vector>::const_iterator i = values.begin(); i != values.end(); ++i) and typedef std::pair value_t; typedef std::vector values_t; values_t values; for (values_t::const_iterator i = values.begin(); i != values.end(); ++i)
C++11 C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
introduced the possibility to express typedefs with instead of . For example, the above two typedefs could equivalently be written as using value_t = std::pair; using values_t = std::vector;


Use with templates

C++03 does not provide templated typedefs. For instance, to have represent for every type one ''cannot'' use: template typedef std::pair stringpair; // Doesn't work However, if one is willing to accept in lieu of , then it is possible to achieve the desired result via a typedef within an otherwise unused templated class or struct: template class stringpair ; // Declare a variable of type `std::pair`. stringpair::type my_pair_of_string_and_int; In
C++11 C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
, templated typedefs are added with the following syntax, which requires the keyword rather than the keyword. (See template aliases.) template using stringpair = std::pair; // Declare a variable of type `std::pair`. stringpair my_pair_of_string_and_int;


Other languages

In
SystemVerilog SystemVerilog, standardized as IEEE 1800, is a hardware description and hardware verification language used to model, design, simulate, test and implement electronic systems. SystemVerilog is based on Verilog and some extensions, and since ...
, typedef behaves exactly the way it does in C and C++. In many statically typed functional languages, like
Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
, Miranda,
OCaml OCaml ( , formerly Objective Caml) is a general-purpose programming language, general-purpose, multi-paradigm programming language which extends the Caml dialect of ML (programming language), ML with object-oriented programming, object-oriented ...
, etc., one 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 as an integer type. In
Seed7 Seed7 is an extensible general-purpose programming language designed by Thomas Mertes. It is syntactically similar to Pascal and Ada. Along with many other features, it provides an extension mechanism. Daniel Zingaro"Modern Extensible Languages" ...
the definition of a constant type is used to introduce a synonym for a type:
const type: myVector is array integer;
In
Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT, ...
, one uses the keyword to create a typedef: typealias PairOfInts = (Int, Int) C# contains a feature which is similar to the typedef or the syntax of C++. using newType = global::System.Runtime.Interop.Marshal; using otherType = Enums.MyEnumType; using StringListMap = System.Collections.Generic.Dictionary>; In D the keyword allows to create type or partial type synonyms. struct Foo(T) alias FooInt = Foo!int; alias Fun = int delegate(int);


Usage concerns

Kernighan and Ritchie stated two reasons for using a typedef. First, it provides a means to make a program more portable or easier to maintain. Instead of having to change a type in every appearance throughout the program's source files, only a single typedef statement needs to be changed. size_t and ptrdiff_t in are such typedef names. Second, a typedef can make a complex definition or declaration easier to understand. Some programmers 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-Hartman Greg Kroah-Hartman (GKH) is a major Linux kernel developer. he is the Linux kernel maintainer for the branch, the staging subsystem, USB, driver core, debugfs, kref, kobject, and the sysfs kernel subsystems, Userspace I/O (with Hans J. Koc ...
, a
Linux kernel The Linux kernel is a free and open-source, monolithic, modular, multitasking, Unix-like operating system kernel. It was originally authored in 1991 by Linus Torvalds for his i386-based PC, and it was soon adopted as the kernel for the GNU ope ...
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.


See also

*
Abstract data type In computer science, an abstract data type (ADT) is a mathematical model for data types. An abstract data type is defined by its behavior (semantics) from the point of view of a ''user'', of the data, specifically in terms of possible values, pos ...
*
C syntax C, or c, is the third letter in the Latin alphabet, used in the modern English alphabet, the alphabets of other western European languages and others worldwide. Its name in English is ''cee'' (pronounced ), plural ''cees''. History "C" ...


References

{{reflist C (programming language) C++ Articles with example C code Articles with example C++ code