What is the use of typedef?

CTypedef

C Problem Overview


What is the use of typedef keyword in C ? When is it needed?

C Solutions


Solution 1 - C

typedef is for defining something as a type. For instance:

typedef struct {
  int a;
  int b;
} THINGY;

...defines THINGY as the given struct. That way, you can use it like this:

THINGY t;

...rather than:

struct _THINGY_STRUCT {
  int a;
  int b;
};

struct _THINGY_STRUCT t;

...which is a bit more verbose. typedefs can make some things dramatically clearer, specially pointers to functions.

Solution 2 - C

From wikipedia:

> typedef is a keyword in the C and C++ programming languages. The purpose of typedef is to assign alternative names to existing types, most often those whose standard declaration is cumbersome, potentially confusing, or likely to vary from one implementation to another.

And:

> K&R 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.

And an argument against:

> He (Greg K.H.) 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.

Solution 3 - C

Typedef is used to create aliases to existing types. It's a bit of a [misnomer][1]: typedef does not define new types as the new types are interchangeable with the underlying type. Typedefs are often used for clarity and portability in interface definitions when the underlying type is subject to change or is not of importance.

For example:

// Possibly useful in POSIX:
typedef int filedescriptor_t;

// Define a struct foo and then give it a typedef...
struct foo { int i; };
typedef struct foo foo_t;

// ...or just define everything in one go.
typedef struct bar { int i; } bar_t;

// Typedef is very, very useful with function pointers:
typedef int (*CompareFunction)(char const *, char const *);
CompareFunction c = strcmp;

Typedef can also be used to give names to unnamed types. In such cases, the typedef will be the only name for said type:

typedef struct { int i; } data_t;
typedef enum { YES, NO, FILE_NOT_FOUND } return_code_t;

Naming conventions differ. Usually it's recommended to use a trailing_underscore_and_t or CamelCase.

[1]: http://gustedt.wordpress.com/2010/08/18/misnomers-in-c/ "Misnomers in C by Jens Gustedt"

Solution 4 - C

Explaining the use of typedef in the following example. Further, Typedef is used to make the code more readable.

#include <stdio.h>
#include <math.h>

/*
To define a new type name with typedef, follow these steps:
1. Write the statement as if a variable of the desired type were being declared.
2. Where the name of the declared variable would normally appear, substitute the new type name.
3. In front of everything, place the keyword typedef.
*/

// typedef a primitive data type
typedef double distance;

// typedef struct 
typedef struct{
	int x;
	int y;
} point;

//typedef an array 
typedef point points[100]; 

points ps = {0}; // ps is an array of 100 point 

// typedef a function
typedef distance (*distanceFun_p)(point,point) ; // TYPE_DEF distanceFun_p TO BE int (*distanceFun_p)(point,point)

// prototype a function		
distance findDistance(point, point);

int main(int argc, char const *argv[])
{
	// delcare a function pointer 
	distanceFun_p func_p;

	// initialize the function pointer with a function address
	func_p = findDistance;

	// initialize two point variables 
	point p1 = {0,0} , p2 = {1,1};

	// call the function through the pointer
	distance d = func_p(p1,p2);

	printf("the distance is %f\n", d );
										
	return 0;
}

distance findDistance(point p1, point p2)
{
distance xdiff =  p1.x - p2.x;
distance ydiff =  p1.y - p2.y;

return sqrt( (xdiff * xdiff) + (ydiff * ydiff) );
} In front of everything, place the keyword typedef.
    */

Solution 5 - C

>typedef doesnot introduce a new type but it just provide a new name for a type.

TYPEDEF CAN BE USED FOR:

  1. Types that combine arrays,structs,pointers or functions.

  2. To facilitate the portability , typedef the type you require .Then when you port the code to different platforms,select the right type by making changes only in the typedef.

  3. A typedef can provide a simple name for a complicated type cast.

  4. typedef can also be used to give names to unnamed types. In such cases, the typedef will be the only name for said type.

**NOTE:-**SHOULDNT USE TYPEDEF WITH STRUCTS. ALWAYS USE A TAG IN A STRUCTURE DEFINITION EVEN IF ITS NOT NEEDED.

Solution 6 - C

from Wikipedia: "K&R states that there are two reasons for using a typedef. First ... . Second, a typedef can make a complex declaration easier to understand."

Here is an example of the second reason for using typedef, simplifying complex types (the complex type is taken from K&R "The C programming language second edition p. 136).

char (*(*x())[])()

x is a function returning pointer to array[] of pointer to function returning char.

We can make the above declaration understandable using typedefs. Please see the example below.

typedef char (*pfType)(); // pf is the type of pointer to function returning
                          // char
typedef pfType pArrType[2];  // pArr is the type of array of pointers to
                             // functions returning char

char charf()
{ return('b');
}

pArrType pArr={charf,charf};
pfType *FinalF()     // f is a function returning pointer to array of
                     // pointer to function returning char
{
return(pArr);
}

Solution 7 - C

It can alias another type.

typedef unsigned int uint; /* uint is now an alias for "unsigned int" */

Solution 8 - C

typedef unsigned char BYTE;

After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example..

BYTE b1, b2;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhksView Question on Stackoverflow
Solution 1 - CT.J. CrowderView Answer on Stackoverflow
Solution 2 - COdedView Answer on Stackoverflow
Solution 3 - CandynView Answer on Stackoverflow
Solution 4 - CAmjadView Answer on Stackoverflow
Solution 5 - CCoffee_loverView Answer on Stackoverflow
Solution 6 - Cshaul boyerView Answer on Stackoverflow
Solution 7 - CThomas BoniniView Answer on Stackoverflow
Solution 8 - Cmirhpe danielleView Answer on Stackoverflow