Typedef

Last updated

typedef is a reserved keyword in the programming languages C, C++, and Objective-C. It is used to create an additional name (alias) for another data type, but does not create a new type, [1] except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type. [2] As such, it is often used to simplify the syntax of declaring complex data structures consisting of struct and union types, although it is also commonly used to provide specific descriptive type names for integer data types of varying sizes. [1]

Contents

Syntax

A typedef declaration follows the same syntax as declaring any other C identifier. The keyword typedef itself is a specifier which means that while it typically appears at the start of the declaration, it can also appear after the type specifiers or between two of them. [3] [4]

In the C standard library and in POSIX specifications, the identifier for the typedef definition is often suffixed with _t, such as in size_t and time_t. This is practiced in some other coding systems, although POSIX explicitly reserves this practice for POSIX data types. In modern codebases, especially in C++, this _t suffix is no longer popular, but does appear in some types in the C++ Standard Library along with other suffixes like _v.

Examples

This snippet declares the type Length as an alias of the type int, allowing a user to use Length as a type in declarations where they would otherwise use int:

typedefintLength;Lengthmy_length=3;// my_length is type 'int'

Documentation use

A typedef declaration may be used to give more contextual meaning than is given by the underlying type, hinting to the user of functions or variables a certain meaning or format is expected. For example, in the code below, the type int is being further clarified to the distinct aliases Points and KmPerHour:

typedefintKmPerHour;typedefintPoints;KmPerHourtop_speed;Pointshigh_score;voidcongratulate(Pointsyour_score,KmPerHouryour_top_speed){if(your_score>high_score){// ...}if(your_top_speed>top_speed){// ...}}

The use of typedef here is used to indicate that only variables declared as Points (or variables that can be interpreted as a Points type) should be used as the first argument, and variables declared as KmPerHour for the second. The value of using typedef in this manner would be for specific cases where masking the underlying type with an alias would add substantial clarity for the programmer, and not for any sort of type enforcement from the compiler, since typedefs are translated back to underlying types before any error checking occurs. For example, this code will compile, without any error:

voidfoo(){KmPerHourmy_top_speed=100;// compiler: type is 'int'Pointsmy_score=5000;// compiler: type is 'int'congratulate(my_score,my_top_speed);// compiler: arguments are (int, int)congratulate(my_top_speed,my_score);// compiler: arguments are (int, int)}

Declaration simplification

A typedef may be used to simplify the declarations of objects having types with verbose names, such as struct, union, or enum types. [5] The point of this is to make it more convenient to declare variables with certain types. For example,

structNamedLocation{floatx;floaty;char*name;};// normal declarationstructNamedLocationlocation_a;// declares NamedLocationType as an alias to the type 'struct NamedLocation'typedefstructNamedLocationNamedLocationType;NamedLocationTypelocation_b;// type is 'struct NamedLocation'

Along with providing previously declared types directly after the typedef keyword, one may also put a full definition of a struct, union, or enum. This has the effect of providing both a type definition and an alias in one statement.

typedefenumWeather{CLOUDY,RAINY,SUNNY}WeatherType;enumWeatheryesterdays_weather;WeatherTypetodays_weather;

When a definition is provided in the typedef declaration, the tag (i.e. name of the underlying type) is optional, leaving only the alias. Modifying the previous snippet:

typedefenum{CLOUDY,RAINY,SUNNY}WeatherType;enumWeatheryesterdays_weather;// ERROR: "enum Weather" does not exist.WeatherTypetodays_weather;// OK

In C++, unlike in C, the tag of a class, struct, union, or enum type is called a class name, and can be used as a type alias automatically without any typedef declaration.

structMyStruct{intvalue1;charvalue2;};typedefstructMyStructMyNewType;structMyStructx;// OK in C/C++MyNewTypey;// OK in C/C++MyStructz;// OK in C++, error in C

The correspondence between this C++ feature and typedef is very strong, extending to the fact that it is possible to shadow the simple type name in a nested scope by declaring it as the identifier of another kind of entity. In such a case, the C-style full type name (an "elaborated type specifier") can still be used to refer to the class or enum type.

In C++, then, MyStruct can be used anywhere that MyNewType can be used, as long as there are no other declarations of these identifiers. The reverse is not true, however, for C++ requires the class name for some purposes, such as the names of constructor methods.

A notorious example where even C++ needs the struct keyword is the POSIX stat system call that uses a struct of the same name in its arguments:

intstat(constchar*filename,structstat*buf){// ...}

Here both C as well as C++ need the struct keyword in the parameter definition.[ dubious discuss ]

Pointers

The typedef may be used to define a new pointer type.

typedefint*IntPtr;IntPtrptr;// Same as:// int* ptr;

IntPtr is a new alias with the pointer type int*. The definition, IntPtr ptr;, defines a variable ptr with the type int*. So, ptr is a pointer which can point to a variable of type int.

Using typedef to define a new pointer type may sometimes lead to confusion. For example:

typedefint*IntPtr;// Both 'cliff' and 'allen' are of type int*.IntPtrcliff,allen;// 'cliff2' is of type int*, but 'allen2' is of type int**.IntPtrcliff2,*allen2;// Same as:// IntPtr cliff2;// IntPtr* allen2;

Above, IntPtr cliff, allen; means defining 2 variables with int* type for both. This is because a type defined by typedef is a type, not an expansion. In other words, IntPtr, which is the int* type, decorates both cliff and allen. For IntPtr cliff2, *allen2;, the IntPtr type decorates the cliff2 and *allen2. So, IntPtr cliff2, *allen2; is equivalent to 2 separate definitions, IntPtr cliff2; and IntPtr* allen2. IntPtr* allen2 means that allen2 is a pointer pointing to a memory with int* type. Shortly, allen2 has the type, int**.

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:

typedefint*IntPtr;constIntPtrptr=nullptr;// This is equivalent to:// int* const ptr = nullptr;  // Constant pointer to an integer.

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 pointer types. Consider this:

structNode{intdata;structNode*next;};

Using typedef, the above code can be rewritten like this:

typedefstructNodeNode;structNode{intdata;Node*next;};

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 errptr was indeed a Node*, but a typographical error means that errptr is a Node. This can lead to subtle syntax errors.

structNode*startptr,*endptr,*curptr,*prevptr,errptr,*refptr;

By defining the typedef Node*, it is assured that all variables are structure pointer types, or say, that each variable is a pointer type pointing to a structure type.

typedefstructNode*NodePtr;NodePtrstartptr,endptr,curptr,prevptr,errptr,refptr;

Function pointers

intdo_math(floatarg1,intarg2){returnarg2;}intcall_a_func(int(*call_this)(float,int)){intoutput=call_this(5.5,7);returnoutput;}intfinal_result=call_a_func(&do_math);

The preceding code may be rewritten with typedef specifications:

typedefint(*MathFunc)(float,int);intdo_math(floatarg1,intarg2){returnarg2;}intcall_a_func(MathFunccall_this){intoutput=call_this(5.5,7);returnoutput;}intfinal_result=call_a_func(&do_math);

Here, MathFunc is the new alias for the type. A MathFunc 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, it can be even more confusing without typedef. The following is the function prototype of signal(3) from FreeBSD:

void(*signal(intsig,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 int 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:

typedefvoid(*sighandler_t)(int);sighandler_tsignal(intsig,sighandler_tfunc);

Arrays

A typedef can also be used to simplify the definition of array types. For example,

typedefcharArrType[6];ArrTypearr={1,2,3,4,5,6};ArrType*pArr;// Same as:// char arr[6] = {1, 2, 3, 4, 5, 6};// char (*pArr)[6];

Here, ArrType is the new alias for the char[6] type, which is an array type with 6 elements. For ArrType* pArr;, pArr is a pointer pointing to the memory of the char[6] 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`.typedefint(*FuncPtr)(double);// Valid in both C and C++.FuncPtrx=(FuncPtr)nullptr;// Only valid in C++.FuncPtry=FuncPtr(nullptr);FuncPtrz=static_cast<FuncPtr>(nullptr);

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, 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=nullptr;// 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 especially with namespace clutter, and typedef provides a mechanism to assign a simple name to the type.

std::vector<std::pair<std::string,int>>values;for(std::vector<std::pair<std::string,int>>::const_iteratori=values.begin();i!=values.end();++i){std::pair<std::string,int>const&t=*i;// ...}

and

typedefstd::pair<std::string,int>Value;typedefstd::vector<Value>Values;Valuesvalues;for(Values::const_iteratori=values.begin();i!=values.end();++i){Valueconst&t=*i;// ...}

C++11 introduced the possibility to express typedefs with using instead of typedef. For example, the above two typedefs could equivalently be written as

usingValue=std::pair<std::string,int>;usingValues=std::vector<Value>;

Use with templates

C++03 does not provide templated typedefs. For instance, to have StringPair<T> represent std::pair<std::string, T> for every type T one cannot use:

template<typenameT>typedefstd::pair<std::string,T>StringPair<T>;// Doesn't work

However, if one is willing to accept StringPair<T>::Type in lieu of StringPair<T>, then it is possible to achieve the desired result via a typedef within an otherwise unused templated class or struct:

template<typenameT>classStringPair{public:// Prevent instantiation of StringPair<T>.StringPair()=delete;// Make StringPair<T>::Type represent std::pair<std::string, T>.typedefstd::pair<std::string,T>Type;};// Declare a variable of type std::pair<std::string, int>.StringPair<int>::TypemyPairOfStringAndInt;

In C++11, templated typedefs are added with the following syntax, which requires the using keyword rather than the typedef keyword. (See template aliases.) [6]

template<typenameT>usingStringPair=std::pair<std::string,T>;// Declare a variable of type std::pair<std::string, int>.StringPair<int>myPairOfStringAndInt;

Other languages

In SystemVerilog, typedef behaves exactly the way it does in C and C++. [7]

In many statically typed functional languages, like Haskell, Miranda, OCaml, etc., one can define type synonyms, which are the same as typedefs in C. An example in Haskell:

typePairOfInts=(Int,Int)

This example has defined a type synonym PairOfInts as an integer type.

In Swift, one uses the typealias keyword to create a typedef:

typealiasPairOfInts=(Int,Int)

C# contains a feature which is similar to the typedef or the using syntax of C++. [8] [6]

usingInteropMarshal=global::System.Runtime.Interop.Marshal;usingMyEnumType=Wikipedia.Examples.Enums.MyEnumType;usingStringListMap=System.Collections.Generic.Dictionary<string,System.Collections.Generic.List<string>>;

In D the keyword alias [9] allows to create type or partial type synonyms.

structFoo(T){}aliasFooInt=Foo!int;aliasFun=intdelegate(int);

In Python, a type can be aliased using the import as statement:

fromreimportPatternasRegexPattern# can now refer to re.Pattern as RegexPattern

In Rust, a type can be aliased using the use as statement:

// math.rspubfnadd(x:i32,y:i32)->i32{a+b}pubfnsubtract(x:i32,y:i32)->i32{a-b}// main.rsmodmath;// rename add to sum, subtract to diffusemath::{addassum,subtractasdiff};fnmain(){letresult1=sum(10,5);letresult2=diff(10,5);println!("The sum is: {}",result1);println!("The difference is: {}",result2);}

Usage concerns

Kernighan and Ritchie stated two reasons for using a typedef. [1] 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 <stdlib.h> 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, a Linux kernel 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. [10]

See also

References

  1. 1 2 3 Kernighan, Brian W.; Ritchie, Dennis M. (1988). The C Programming Language (2nd ed.). Englewood Cliffs, New Jersey.: Prentice Hall. p.  147. ISBN   0-13-110362-8 . Retrieved 18 June 2016. C provides a facility called typedef for creating new data type names. … It must be emphasized that a typedef declaration does not create a new type in any sense; it merely adds a new name for some existing type.
  2. "const type qualifier". cppreference.com. Retrieved 2020-10-20.
  3. "typedef specifier (C++)". cppreference.com. Retrieved 18 June 2016.
  4. "typedef declaration (C)". cppreference.com. Retrieved 18 June 2016.
  5. Deitel, Paul J.; Deitel, H. M. (2007). C how to program (5th ed.). Upper Saddle River, N.J.: Pearson Prentice Hall. ISBN   9780132404167 . Retrieved 12 September 2012. Names for structure types are often defined with typedef to create shorter type names.
  6. 1 2 "Type alias, alias template (since C++11) - cppreference.com". en.cppreference.com. Retrieved 2018-09-25.
  7. Tala, Deepak Kumar. "SystemVerilog Data Types Part-V". www.asic-world.com. ASIC World. Retrieved 25 September 2018.
  8. "Visual Studio 2003 Retired Technical documentation".
  9. "Declarations - D Programming Language". dlang.org. Retrieved 2017-05-28.
  10. Kroah-Hartman, Greg (2002-07-01). "Proper Linux Kernel Coding Style". Linux Journal . Retrieved 2007-09-23. Using a typedef only hides the real type of a variable.