开发者

What is the use of typedef?

开发者 https://www.devze.com 2022-12-25 17:02 出处:网络
Wh开发者_StackOverflow社区at is the use of typedef keyword in C ? When is it needed?typedef is for defining something as a type. For instance:

Wh开发者_StackOverflow社区at is the use of typedef keyword in C ? When is it needed?


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.


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.


Typedef is used to create aliases to existing types. It's a bit of a misnomer: 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.


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.
    */


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.


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);
}


It can alias another type.

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


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;

0

精彩评论

暂无评论...
验证码 换一张
取 消